首页 > 解决方案 > 停止执行多个文件 - 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
 

标签: pythonwindowsif-statementautomationoperating-system

解决方案


如果条件在其他文件之一中(如您的情况),请提出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

推荐阅读