python-3.x - Python3(os.system)中的错误处理

标签 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')

提前致谢

最佳答案

您应该考虑使用[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/

相关文章:

python - python 从 stdin 读取的行长度

javascript - 显示 openweathermap API 错误时出错

c# - Serilog Logcontext 属性在异常处理程序之后消失了

python - 将终端输出写入文件

带有 os.system() 调用的 Python 线程。 ctrl+c 主线程不退出

python - 我遇到错误 "ModuleNotFoundError: No module named ' __main__.models'; '__main__' 不是一个包”

python - 使用 Homebrew 和 pyenv 在 Mac 上为 Python 3 安装 OpenCV 3

python - 将字典中的值四舍五入到 python 中最接近的 5?

php - CakePHP : Customized error message should display on the same page instead of moving some other page

python - 如何从 python 脚本执行 7zip 命令