【问题标题】:catch exception in python script which calls another script在调用另一个脚本的python脚本中捕获异常
【发布时间】:2014-07-21 03:17:09
【问题描述】:

我正在从另一个 python 文件运行 python 脚本。有没有办法知道第二个脚本中是否发生了错误?

EX: script1.py 调用 script2.py 蟒蛇脚本2。 py -参数 script1如何知道script2是否发生异常?

运行.py

import subprocess

subprocess.call("python test.py -t hi", shell=True)

test.py

import argparse
print "testing exception"

parser = argparse.ArgumentParser(description='parser')
parser.add_argument('-t', "--test")

args = parser.parse_args()

print args.test
raise Exception("this is an exception")

谢谢

【问题讨论】:

    标签: python exception


    【解决方案1】:

    当 Python 程序抛出异常时,进程会返回一个非零返回码。默认情况下,call 等子进程函数将返回返回码。因此,要检查是否发生异常,请检查非零退出代码。

    这里是一个检查返回码的例子:

        retcode = subprocess.call("python test.py", shell=True)
        if retcode == 0:
            pass  # No exception, all is good!
        else:
            print("An exception happened!")
    

    另一种方法是使用subprocess.check_call,它会在非零退出状态下引发 subprocess.CalledProcessError 异常。一个例子:

    try:
        subprocess.check_call(["python test.py"], shell=True)
    except subprocess.CalledProcessError as e:
        print("An exception occured!!")
    

    如果您需要知道您的测试程序中发生了哪个异常,您可以使用 exit() 更改异常。例如,在您的 test.py 中:

    try:
        pass  # all of your test.py code goes here
    except ValueError as e:
        exit(3)
    except TypeError as e:
        exit(4)
    

    在你的父程序中:

    retcode = subprocess.call("python test.py", shell=True)
    if retcode == 0:
        pass  # No exception, all is good!
    elif retcode == 3:
        pass  # ValueError occurred
    elif retcode == 4:
        pass  # TypeError occurred
    else:
        pass  # some other exception occurred
    

    【讨论】:

    • @user3330263 更新了答案以反映您的示例代码
    【解决方案2】:

    可能最好的方法是使 script2 成为一个实际的模块,将您想要的内容导入 script1,然后使用现有的 try/except 机制。但也许这不是一个选择?否则我认为从 os.system 返回的内容可能包括您需要的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多