模块重新加载没有按预期工作

Module reload doesn't work as expected

我无法理解为什么 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.

问题是您的代码会立即更改文件,因此文件显示为未修改。 参见 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

解决方法

  1. 删除为您的模块生成的 .pyc 文件(some_file.pyc,或类似的文件)。这将迫使 python 重新编译它。
  2. 只需在写入文件的同时即时更改模块。参见 this。像

    some_file.message = "Second\n"
    f = open('some_file.py', 'w')
    f.write('message = "Second"\n')
    f.close()