我在解释为什么reload()
在以下代码中无法正常工作时遇到问题:
# Create initial file content
f = open('some_file.py', 'w')
f.write('message = "First"\n')
f.close()
import some_file
print(some_file.message) # First
# Modify file content
f = open('some_file.py', 'w')
f.write('message = "Second"\n')
f.close()
import some_file
print(some_file.message) # First (it's fine)
reload(some_file)
print(some_file.message) # First (not Second, as expected)
如果我使用外部编辑器手动更改文件some_file.py
(程序运行时),那么一切都按预期工作。所以我想这可能与同步有关。
环境:Linux,Python 2.7。
答案 0 :(得分:2)
问题是您的代码会立即更改文件,因此文件显示为未修改。 见this answer
我已经尝试过你的代码,文件写入之间的睡眠时间相同,并且工作正常
import time
# Create initial file content
f = open('some_file.py', 'w')
f.write('message = "First"\n')
f.close()
import some_file
print(some_file.message) # First
time.sleep(1) # Wait here
# Modify file content
f = open('some_file.py', 'w')
f.write('message = "Second"\n')
f.close()
import some_file
print(some_file.message) # First
reload(some_file)
print(some_file.message) # Second, as expected
<强>变通方法强>
.pyc
文件(some_file.pyc
或类似内容)。这将迫使python重新编译它。只需动态更改模块并写入文件即可。见this。像
这样的东西some_file.message = "Second\n"
f = open('some_file.py', 'w')
f.write('message = "Second"\n')
f.close()