我想从一个主文件运行几个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
内部,我写了几个断言。second_file
不得运行,除非所有断言都已运行且未在first_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
但是这没有任何作用:即使second_file
中的断言失败,first_file
也会运行。
断言在这里总是会失败的,因为run
返回None
,这反过来会得出False
。
一个简单的解决方法:
def run(file):
os.system(f"python3 -m folder.subfolder.{file}")
return True
try:
doSomeFunStuff()
except Exception, e:
handleException(e)
raise
OR,
import sys
try:
print("something")
except:
sys.exit(1)