从主文件执行 Python 文件,并在任何文件中的断言失败时停止运行



我想从一个主文件运行几个Python文件。 我正在使用my_module中的以下自定义函数执行此操作:

import os
def run(file):
os.system(f"python3 -m folder.subfolder.{file}")

在主文件中,我有:

from folder.my_module import run
run("first_file")
run("second_file")

first_filesecond_file里面,我写了几个断言。除非所有断言都运行且未在first_file中引发错误,否则second_file不得运行。

通常,我希望当任何文件中发生错误时,整个程序停止运行。

我试过:

assert run("first_file"), "Error in file 1"
assert run("second_file"), "Error in file 2"

但是程序总是在第一个文件运行后停止工作,无论是否发生异常。

我也尝试过:

try:
run("first_file")
except:
raise
try:
run("second_file")
except:
raise

但这没有任何影响:即使断言在first_file中失败,second_file也会运行。

断言在这里总是失败,因为run返回None,而又计算结果为False

一个简单的修复:

def run(file):
os.system(f"python3 -m folder.subfolder.{file}")
return True

编辑

我不得不仔细检查os模块。os.system将返回您正在运行的程序的退出代码,因此您实际上应该将其与0(正常的非错误退出状态)进行比较,如下所示:

def run(file):
return 0 == os.system(f"python3 -m folder.subfolder.{file}")

os.system(f"python3 -m folder.subfolder.{file}")命令将返回所提供命令的退出代码。碰巧的是,以 AssertionError 结尾的 Python 程序的退出代码为 2(在 Linux 上,其他地方可能有所不同),尽管实际上任何非零代码都意味着错误。

您可以在命令行上自行测试:

$ python3 -c "assert True"
$ echo $?
0
$ python3 -c "assert False"
$ echo $?
2

只需检查os.system()调用的返回值即可。

最新更新