python - 停止执行多个文件 - Python
问题描述
我试图通过 Windows 终端停止执行脚本 (run_all.py),该终端运行包含在列表中的多个文件,具体取决于每个文件中满足的特定条件。具体来说,在 file_2.py 中,我想根据“y”参数的值暂停该文件的执行,然后停止执行文件列表中尚未运行的任何文件(即 file_3.py)。我目前正在使用 time 模块将 file_2.py 暂停 60 秒,但我需要一种更优雅的方式来停止执行,而无需手动键盘命令(例如 Ctrl + C)......非常感谢任何帮助!
文件_1.py
print("Math is fun!")
文件_2.py
import os
import time
x=1
y=2
if x < 10:
print("x is small")
else:
print("x is invalid")
if y < 10:
print("y is also small")
else:
print('press "ctrl + c" to stop execution of the workflow')
time.sleep(60)
文件_3.py
print("python is so cool!")
run_all.py(从 Windows 终端运行的主脚本)
import os
path = "C:\\users\\mdl518\\Desktop\\"
file_list = ['file_1.py', 'file_2.py', 'file_3.py']
for filename in file_list:
os.system('python' + ' ' + os.path.join(path,filename)) # runs all files in the file_list
解决方案
如果条件在其他文件之一中(如您的情况),请提出ValueError
. 例如:
x = 2
y = 9
if x < 10:
raise ValueError("x is small")
if y < 10:
raise ValueError("y is small")
将这些文件中的代码转换为函数并将函数导入run_all
文件中而不是调用 python 将它们作为单独的进程运行会是一个更好的做法。例如:
文件 1(f1.py):
def f1():
print("Math is fun!")
文件 2 (f2.py):
def f2(x, y):
if x < 10:
raise ValueError("y is small")
if y < 10:
raise ValueError("y is small")
文件 3 (f3.py):
def f3():
print("python is so cool!")
run_all 文件:
from f1 import f1
from f2 import f2
from f3 import f3
funs = [f1(), f2(1, 2), f3()]
for f in funs:
f
推荐阅读
- ios - 有没有办法使用 IOS 设备扫描产品的条形码并获取产品的输入(例如可口可乐、薯片袋……)
- sql - Oracle APEX 错误 ora-01403:无法编辑报告
- python - Python 和 lmfit:如何绘制通过最小化函数的残差获得的多重拟合
- java - 当从另一个活动回调时,包含消息计数的 textView 返回 null
- javascript - 无法正确读取 url
- tableau-api - Tableau - 每周峰值(7 天的滑动次数),然后是平均值
- python - 在 Python 中测试请求 REST API 的类
- amazon-redshift - 在 Redshift 中创建表失败
- node.js - Express.js 重定向实际上并不是重定向页面
- mysql - mysql如何通过bash脚本进行查询