假设我有一个 Python 脚本main.py
可以导入othermodule.py
. 是否可以写一个reload(othermodule)
inmain.py
以便当我对 进行更改时othermodule.py
,我仍然可以reload(main)
,然后重新加载其他模块?
问问题
3791 次
2 回答
4
好吧,事情没那么简单。假设你有main.py
这样的...
import time
import othermodule
foo = othermodule.Foo()
while 1:
foo.foo()
time.sleep(5)
reload(othermodule)
...和othermodule.py
这样的...
class Foo(object):
def foo(self):
print 'foo'
......那么如果你改变othermodule.py
这个......
class Foo(object):
def foo(self):
print 'bar'
...虽然main.py
仍在运行,但它会继续打印foo
,而不是bar
,因为foo
in 中的实例main.py
将继续使用旧的类定义,尽管您可以通过main.py
这样来避免这种情况...
import time
import othermodule
while 1:
foo = othermodule.Foo()
foo.foo()
time.sleep(5)
reload(othermodule)
重点是,您需要了解导入模块的各种更改,这些更改会在reload()
.
可能有助于在原始问题中包含一些源代码,但在大多数情况下,重新启动整个脚本可能是最安全的。
于 2013-05-21T17:07:41.660 回答