reload() 似乎没有重新加载模块 [英] reload() does not appear to reload the module

查看:93
本文介绍了reload() 似乎没有重新加载模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本可以将一些参数动态写入配置文件,我需要根据更新的参数从链接模块调用一些函数.但是,当我在配置文件上调用 reload() 时,有时我看不到任何变化.

I have a script that writes some parameters to a config file dynamically and I need to call some functions from a linked module based on the updated parameters. However, when I call reload() on the config file, sometimes I see no change.

以下代码片段将解释该场景:

The following code snippet will explain the scenario:

import options
import os
import someothermodule

def reload_options():
    global options
    options = reload(options)

def main():
    print dir(options)

    # do some work to get new value of the parameter
    new_value = do_some_work()

    with open('./options.py', 'w') as fd_out:
        fd_out.write('NEW_PARAMETER = %d\n' % (new_value,))  # write

        fd_out.flush()
        os.fsync(fd_out.fileno())

    reload_options()
    print dir(options)

    someothermodule.call_some_func()

if __name__ == '__main__':
    main()

有时(这并不总是发生),在两个打印语句中打印相同的数据,这意味着 NEW_PARAMETER 从未出现过.我怀疑这是因为文件没有被刷新到磁盘,所以我添加了 flush()fsync() 语句,但它们似乎没有帮助.

Sometimes (this does not occur always), same data is printed at both print statements, which meant that NEW_PARAMETER never showed up. I suspected this is because the file is not getting flushed to the disk, so I added flush() and fsync() statements, but they do not seem to help.

有人可以帮我诊断问题吗?

Can anybody help me diagnose the issue?

推荐答案

该问题可能与具有相同创建日期的文件有关.看到这个问题:Python 的 imp.reload() 函数不起作用?

The problem is likely to do with the files having the same creation date. See this SO question : Python's imp.reload() function is not working?

我可以通过插入 sleep 语句使此代码正常工作:

I was able to get this code working by inserting a sleep statement:

   # replace NEW_PARAMETER in options.py with numbers in the range 0-9
   for ii in range(10):
        new_value = ii

        # Sleep here to let the system clock tick over
        time.sleep(1)

        with open('./options.py', 'w') as fd_out:
            fd_out.write('NEW_PARAMETER = %d\n' % (new_value,))  # write                                                 
            fd_out.flush()
            os.fsync(fd_out.fileno())

        reload_options()
        print ii,options.NEW_PARAMETER 

这篇关于reload() 似乎没有重新加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆