在Python上重新加载JSON文件

时间:2017-12-03 22:27:53

标签: python json

我正在尝试创建一个在每次修改时更新(重新加载)JSON文件内容的函数。

我(显然)已加载文件:

comandos = json.load(open('comandos.json'))

但每次更新json时,我都必须杀死python进程再次加载它。

- 更新

脚本处于循环中,我将其用作Bot(连接到Telegram,侦听来自用户组的任何命令)。

在这种情况下,当我'释放'新功能(新命令)时,我希望机器人重新加载文件'comandos.json'上的所有内容,以获得Telegram频道上的新选项。

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

您需要在更改时重新加载此文件。您可以使用watchdog之类的内容来了解​​何时重新加载。

答案 1 :(得分:-2)

编辑:此解决方案多次读取文件,但不依赖于库,并且与平台无关。

请提供更多细节!

以下是您可以使用的解决方案。当然有其他选择,但我不知道确切的用例。我想你想要在修改文件后重新加载文件。

def fileWatcher():
    global comandos, comandosText
    while True:
        f = open('comandos.json')
        content = f.read()
        f.close()
        if content != comandosText:
            print("File was modified! Reloading it...")
            comandos = json.loads(content)
            comandosText = content
        time.sleep(0.5) #Adjust this to get the best performance

然后在你的主要代码......

import time
import threading
import json
threading.Thread(target=fileWatcher).start()

这会在后台异步启动文件监视器,并在您更新文件后更新comandos

此代码应该是开箱即用的。