首页 > 解决方案 > 如何在运行时更改 python

问题描述

我有代码运行..

counter =0
while 1:
    counter +=1
    print('test1')
    if counter == 12345:
        exit(1)

如何在运行时更改此代码而不是exit(1)print('hi')

标签: pythonpython-3.x

解决方案


我认为这不可能在单个文件中完成——Python 解释器似乎在运行它之前将整个文件加载到内存中,并且使用 Python 的构建方式重新加载当前文件是不可能的。

但是,您可以重新加载模块。知道了这一点,您可以执行以下操作:

# main.py
import importlib
import some_module
import time
counter = 0
while 1:
    print("Counter is", counter)
    importlib.reload(some_module)
    some_module.some_function()
    time.sleep(1)
    counter += 1
# some_module.py
def some_function():
    print("This is the original function")

现在,您可以编辑some_module.py,更改将应用​​于当前正在运行的程序:

...
Counter is 16
This is the original function
Counter is 17
This is the original function
Counter is 18
This is the original function
Counter is 19
This is the original function
Counter is 20
I just edited the file!
Counter is 21
I just edited the file!
Counter is 22
I just edited the file!
Counter is 23
I just edited the file!
Counter is 24
I just edited the file!
...

推荐阅读