python - 如何在运行时更改 python
问题描述
我有代码运行..
counter =0
while 1:
counter +=1
print('test1')
if counter == 12345:
exit(1)
如何在运行时更改此代码而不是exit(1)
将print('hi')
解决方案
我认为这不可能在单个文件中完成——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!
...
推荐阅读
- java - Web 服务器启动时将 JSON 文件转换为 java 对象
- javascript - 如何修复 React Native 中的导航问题(TypeError: undefined is not an object(evalating '_this.props.navigation)
- mapbox-android - Mapbox 交通插件错误
- angular - 下拉菜单未显示加载值
- mongodb - 提高猫鼬种群性能
- ios - 如何获取集合视图中所选项目的位置?
- python - 从 txt 文件中的数组发送单个电子邮件
- python - 使用 Python 将输出打印到 CSV 文件并对其进行格式化
- sql - 多个 SQL 查询条件
- node.js - npm 安装 @types/.../node_modules/react