简体   繁体   English

如何在不重新启动应用程序的情况下自动重新加载 python 模块?

[英]How to auto reload python module without restarting app?

I am interested in adapting python file after I run the app.我有兴趣在运行应用程序后调整 python 文件。 Suppose we have a script:假设我们有一个脚本:

import time

while True:
    time.sleep(10)
    print(2)

I run it, so it prints number 2 every 10 seconds.我运行它,所以它每 10 秒打印一次数字2 I would like to be able to change 2 to 5 so that I don't need to rerun script, but output changed to 5.我希望能够将2更改为5这样我就不需要重新运行脚本,但输出更改为5.

This mechanism is somehow implemented in Django , after file is edited, data on server is reloaded.这种机制在Django以某种方式实现,在编辑文件后,重新加载服务器上的数据。

Edit:编辑:

import time
from importlib import reload
import data

while True:
    reload(data)
    print(data.some_data)
    time.sleep(1)

something like this would do the job, but maybe there is better way of achieving such behaviour?像这样的事情可以完成这项工作,但也许有更好的方法来实现这种行为?

You could create a seperate file to manage dynamic content.您可以创建一个单独的文件来管理动态内容。 And then import the data that you need from that file.然后从该文件导入您需要的数据。

data.py数据文件

some_data = 10

script.py脚本文件

import time
from .data import some_data

while True:
    time.sleep(10)
    print(some_data)

and then you can just edit the value in data.py to whatever value you want without restarting the script.然后您可以将 data.py 中的值编辑为您想要的任何值,而无需重新启动脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM