Python 3.x Python3(操作系统)中的错误处理

Python 3.x Python3(操作系统)中的错误处理,python-3.x,error-handling,os.system,try-catch-finally,Python 3.x,Error Handling,Os.system,Try Catch Finally,在Python中,我从主Python文件调用子文件。 在所有子python文件中,我都包含了try和except块。 在主文件中,我需要按照下面提到的顺序执行子文件。 如果在os.system(“python SubFile1.py”)语句中发现任何错误,是否有方法停止执行os.system(“python SubFile2.py”)语句? 我还需要在主python文件中获取错误详细信息 这是主文件的代码段: import os import sys print("start here") t

在Python中,我从主Python文件调用子文件。 在所有子python文件中,我都包含了try和except块。 在主文件中,我需要按照下面提到的顺序执行子文件。 如果在
os.system(“python SubFile1.py”)
语句中发现任何错误,是否有方法停止执行
os.system(“python SubFile2.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')

预先感谢

< P>您应该考虑使用<代码> [Sub Prime](1)< /Code >。如果您想捕获异常并结束另一个进程,不建议使用<代码> OS > Stase< /Code >,因为<代码> OS·SoC()/代码>通过该方法的退出代码指示了一个失败。对于更多细节,你应该考虑阅读这个答案:

对于您的变通方法,您可以尝试使用这段代码,尽管我使用了子流程

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 

当x子文件中遇到错误时,是否也要退出主进程?是的,主进程应退出确定,请检查我的答案。不过,您应该考虑使用<代码>子进程< /代码>。