1

Say you have a config.py which inside has

settings = read_yaml('settings.yaml')

so config.settings is a dictionary.

in one script foo.py you have:

import config
config.settings['foo'] = str(time.time())
write_yaml('settings.yaml', config.settings)

and in another script bar.py you have

import config
while True:
    sleep(10)
    print config.settings['foo']

How would you keep the printed value in bar.py up to date with the new value after running foo.py at any time without the obvious reading the file again seeing as the while loop in bar.py needs to be as quick as possible!

I currently run these on seperate bash threads i.e:

$ python bar.py
$ python foo.py

But I could run bar in a thread if that is possible?

4

1 回答 1

2

我不知道你需要多快。但是当然可以只用 .reload 重新加载config模块importlib.reload。因此config.pyfoo.py保持不变,您的bar.py更改为:

import importlib
import config

while True:
    print config.settings['foo']
    sleep(10)
    importlib.reload(config)

更新

上面的示例适用于 Python >= 3.4,imp.reload适用于早期版本的 Python 3 或reloadPython 2。

于 2019-01-01T18:41:21.303 回答