Python3(os.system)中的错误处理

时间:2018-08-11 03:16:39

标签: python-3.x error-handling os.system try-catch-finally

在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')

预先感谢

1 个答案:

答案 0 :(得分:0)

如果您想捕获异常并结束另一个进程,则不建议使用[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 
相关问题