reload()似乎没有重新加载模块

1 投票
2 回答
854 浏览
提问于 2025-04-18 01:58

我有一个脚本,它会动态地把一些参数写入配置文件,然后我需要根据更新后的参数调用一些来自关联模块的函数。不过,当我对配置文件使用reload()时,有时候我发现没有任何变化。

下面的代码片段可以帮助解释这个情况:

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()这两个语句,但似乎没有什么效果。

有没有人能帮我找出问题所在?

2 个回答

1

与其依赖于 reload,为什么不直接在模块上添加或修改属性,这样不仅可以在当前使用,还可以把它输出到文件中,以便将来使用呢?

import options
import os
import someothermodule

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

    # assign value for now
    options.NEW_PARAMETER = new_value

    # store value for later
    with open('./options.py', 'w') as fd_out:
        fd_out.write('NEW_PARAMETER = {}'.format(new_value))

    print dir(options)

    someothermodule.call_some_func()
2

这个问题可能跟文件的创建日期相同有关。可以看看这个StackOverflow上的问题:Python的imp.reload()函数不起作用?

我通过插入一个暂停的语句让这段代码正常工作了:

   # 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 

撰写回答