我试图将代码作为模块加载,然后在Python中以编程方式重新加载相同的模块但不同的代码:
import imp a = """ def test(): print "Hello from a" """ b = """ def test(): print "Hello from b" """ for code in [a, b]: with open('user.py', 'wb') as f: f.write(code) mod = imp.load_source('user', 'user.py') getattr(mod, "test")()预期产量:
Hello from a Hello from b实际产量:
Hello from a Hello from a显然,我对它是如何工作的理解是不正确的,但我似乎无法弄清楚我的错误。
我能让它工作的唯一方法是在我在文件f编写代码之前删除生成的.pyc文件。 有没有更好的办法?
I am trying to load code as a module and then reload the same module but different code programmatically in Python:
import imp a = """ def test(): print "Hello from a" """ b = """ def test(): print "Hello from b" """ for code in [a, b]: with open('user.py', 'wb') as f: f.write(code) mod = imp.load_source('user', 'user.py') getattr(mod, "test")()Expected output:
Hello from a Hello from bActual output:
Hello from a Hello from aObviously my understanding of how it works is not correct but I can't seem to figure out my mistake.
The only way I could get it to work was if I deleted the generated .pyc file before I wrote the code in the file f. Is there a better way?
最满意答案
可能不是因为.pyc文件的时间戳(精确到一秒)不会比新写的.py文件的时间戳更旧; 因此imp将使用“当前” .pyc文件,除非您先删除它。
或者,您可以尝试在重新加载模块之前等待两秒钟。
Probably not because the timestamp of your .pyc file (accurate to a second) will not be older than the timestamp for your newly written .py file; therefore imp will use the "current" .pyc file unless you delete it first.
Alternatively, you could try waiting for two seconds before reloading the module.
更多推荐
发布评论