问题是,您的代码会立即更改文件,因此文件看起来没有修改。
看见
this answer
我在文件写入之间用同样的1秒睡眠尝试了你的代码,效果很好
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()