怎么if __name__ == "__main__":办?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
Run Code Online (Sandbox Code Playgroud) if __FILE__ == $0
$:.unshift File.join(File.dirname(__FILE__),'..')
Run Code Online (Sandbox Code Playgroud)
我在Ruby中发现了这个代码,这是什么意思?
假设我有一个Perl文件,其中只有在我被称为脚本时才需要运行的部分.我记得有时读过在main()方法中包含这些部分并做一个
main() unless(<some condition which tests if I'm being used as a module>);
Run Code Online (Sandbox Code Playgroud)
但我忘了条件是什么.搜索Google并没有发现任何有益的结果.有人能指出正确的地方寻找这个吗?
我知道Perl有一个称为modulino的设计模式,其中库模块文件既可以作为库也可以作为脚本.在Ruby/Python中有没有相同的东西?
我认为这种设计模式对我来说非常有用; 我正在编写相当短的工作者,但也需要一个脚本来运行它们.我认为将这一切都从同一个地方运行会很方便.
谢谢!