【问题标题】:Module reload doesn't work as expected模块重新加载无法按预期工作
【发布时间】:2017-11-20 12:52:53
【问题描述】:

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

【问题讨论】:

  • 有趣的是,我无法在 Windows 上的 Python 3.4 上使用 importlib.reload 重现这一点。我得到了输出First ; First ; Second
  • @DeepSpace 在 Python 3.X 上运行良好!

标签: python file python-module


【解决方案1】:

问题是您的代码会立即更改文件,因此文件看起来未修改。 见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()
    

【讨论】:

  • 我已经尝试过这个想法。大多数时候它有效(第一,第一,第二),有时它不起作用(第二,第二,第二 - 当你第二次立即运行脚本时)。在我看来,用 sleep 填充代码并不是最好的主意,因此我正在寻找更强大的解决方案。
  • 我同意用无意义的睡眠污染代码是一种不好的做法。我的意思是解释而不是解决方案。我已经用一些解决方法更新了答案。
猜你喜欢
  • 2018-08-21
  • 1970-01-01
  • 2023-03-17
  • 2020-12-25
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
相关资源
最近更新 更多