【问题标题】:Stop Execution for Multiple Files - Python停止执行多个文件 - Python
【发布时间】:2023-03-28 16:27:01
【问题描述】:

我正在尝试通过 Windows 终端停止执行脚本 (run_all.py),该终端运行列表中包含的多个文件,具体取决于每个文件中满足的特定条件。具体来说,在 file_2.py 中,我想根据“y”参数的值暂停该文件的执行,然后停止执行文件列表中尚未运行的任何文件(即 file_3.py)。我目前正在使用 time 模块将 file_2.py 暂停 60 秒,但我需要一种更优雅的方式来停止执行,而无需手动键盘命令(例如 Ctrl + C)......非常感谢任何帮助!

file_1.py

print("Math is fun!")

file_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)

file_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
 

【问题讨论】:

    标签: python windows if-statement automation operating-system


    【解决方案1】:

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

    【讨论】:

    • 谢谢@feline,您提出的解决方案很有意义! “break”语句从 For 循环中跳出,而不是 If 语句。我将根据您的编辑调整我的原始帖子,并确认您的答案是正确的解决方案 - 再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2022-08-18
    • 2021-04-12
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多