【问题标题】:capturing the error when using sys.exit()使用 sys.exit() 时捕获错误
【发布时间】:2020-10-23 02:33:33
【问题描述】:

是否可以捕获生成的错误并将其返回给调用者脚本?

p1.py
def fun1():
    try:
        ...
    except Exception as err:
        print('ERROR from p1.py')
        sys.exit(1)



p2.py
import p1
def fun2():
    try:
        ...
     except Exception as err:
        print('ERROR from p2.py')
        sys.exit(1)
           
p3.py
import p2
#want to catch the errors here
errors1 = 'ERROR from p1.py'
errors2 = 'ERROR from p2.py'

有没有办法从 p3.py 中的 p1.py('ERROR from p1.py')或 p2.py('ERROR from p2.py')获取错误?

【问题讨论】:

    标签: python-3.x error-handling


    【解决方案1】:

    当您在 p3.py 文件中执行 p1.py 和 p2.py 文件的功能时,一种方法可能是在哪里处理异常,您可以在 p3.py 中执行 try-except(而不是在每个函数中捕获异常):

    p3.py

    from p1 import fun1
    from p2 import fun2
    
    # calling the function from p1.py
    try:
      fun1()
    except Exception as err:
      print('You have the error from fun1 in p1.py, you can make your logic here')
      sys.exit(1)
    # calling function from p2.py
    try:
      fun2()
    except Exception as err:
      print('You have the error from fun2 in p2.py, you can make your logic here')
      sys.exit(1)
    

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2018-01-08
      相关资源
      最近更新 更多