在Python中,我从主python文件调用子文件。
在所有子python文件中,我都包含了try和except块。
在主文件中,我需要按照下面提到的顺序执行子文件。
如果os.system("python SubFile2.py")
语句中发现任何错误,是否有一种方法可以停止执行os.system("python SubFile1.py")
语句?
而且我还需要在主python文件中获取错误详细信息。
这是主文件的代码片段:
import os
import sys
print("start here")
try:
print('inside try')
os.system("python SubFile1.py")
os.system("python SubFile2.py")
os.system("python SubFile4.py")
except:
print("Unexpected error:")
print(sys.exc_info()[0])
print(sys.exc_info()[1])
print(sys.exc_info()[2])
finally:
print('finally ended')
提前致谢
最佳答案
您应该考虑使用[subprocess][1]
如果要捕获异常并结束另一个进程,则不建议使用os.system
,因为os.system()
通过该方法的退出代码指示失败。有关更多详细信息,您应该考虑阅读以下答案:Python try block does not catch os.system exceptions
对于您的解决方法,您可以尝试使用此代码,该代码有效,但是我使用了子流程。
import os
import sys
import subprocess
print("start here")
files = ["first.py", "second.py"]
count=0
for file in files:
try:
cmd = subprocess.Popen(["python", file],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output, error = cmd.communicate()
if(error):
print(error)
sys.exit()
except OSError as e:
print("inside exception", e)
sys.exit()
count+=1
关于python-3.x - Python3(os.system)中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51796164/