无法在不删除pyc文件的情况下在Python中重新加载正确的模块(Unable to reload the correct module in Python without deleting the

编程入门 行业动态 更新时间:2024-10-12 03:28:12
无法在不删除pyc文件的情况下在Python中重新加载正确的模块(Unable to reload the correct module in Python without deleting the pyc file)

我试图将代码作为模块加载,然后在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 b

Actual output:

Hello from a Hello from a

Obviously 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.

更多推荐

本文发布于:2023-08-03 09:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   情况下   加载   正确   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!