【问题标题】:Error Handling in Python3 (os.system)Python3 (os.system) 中的错误处理
【发布时间】:2019-01-18 15:20:44
【问题描述】:

在 Python 中,我从主 python 文件调用子文件。 在所有子 python 文件中,我都包含了 try 和 except 块。 在主文件中,我需要按照我在下面提到的顺序执行子文件。 如果在os.system("python SubFile1.py") 语句中发现任何错误,有没有办法停止执行os.system("python SubFile2.py") 语句? 而且我还需要在主 python 文件中获取错误详细信息。

这是主文件的代码sn-p:

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

提前致谢

【问题讨论】:

  • 当x子文件出现错误时,您是否希望您的主进程也退出?
  • 是的,应该退出主进程
  • 好的,那么请检查我的答案。不过,您应该考虑使用subprocess

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2015-09-24
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多