我想从一个主文件运行几个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_file
和second_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()
调用的返回值即可。