代码之家  ›  专栏  ›  技术社区  ›  Konstantin

模块重新加载未按预期工作

  •  0
  • Konstantin  · 技术社区  · 7 年前

    我不明白为什么 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。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Alex Mozharov    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()