【问题标题】:How to catch all exceptions in Try/Catch Block Python?如何在 Try/Catch Block Python 中捕获所有异常?
【发布时间】:2018-05-23 00:33:02
【问题描述】:

我正在编写 python 代码来在 linux 环境中安装我的程序所需的所有库包。所以 linux 可能包含 python 2.7 或 2.6 或两者,所以我开发了一个 try and except 块代码,它将安装 pip 包linux。 Try 块代码由 python 2.7 版本 pip install 组成,Catch 块包含 python 2.6 版本 pip install。我的问题是代码的和平工作正常,当我尝试在 python 2.6 中安装熊猫时,它给了我一些错误。我想抓住那个异常。你能告诉我如何改进我的 try except 块以捕获该异常

required_libraries = ['pytz','requests','pandas']
try:
   from subprocess import check_output
   pip27_path = subprocess.check_output(['sudo','find','/','-name','pip2.7'])
   lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except:
   p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
   lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

【问题讨论】:

  • 再试一次:except: 阻塞在你已经拥有的 except 内?
  • @ChrisCharles 刚才我尝试了同一个。仍然没有捕捉到异常
  • @ChrisCharles 除外:尝试:p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE );pip26_path, err = p.communicate() lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]除了 Exception as e: logging.info("error in pip_installs function '%s'" %e)
  • 捕获所有异常通常是一个糟糕的主意。见stackoverflow.com/questions/10594113/…

标签: python python-3.x python-2.7 exception subprocess


【解决方案1】:

您可以使用一个块捕获多个异常。让我们使用 Exception 和 ArithmeticError 来处理异常。

try:
    # Do something
    print(q)

# Catch exceptions  
except (Exception, ArithmeticError) as e:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(e).__name__, e.args)
    print (message)

如果您需要捕获多个异常并单独处理每个异常,那么您应该为每个异常编写一个 except 语句。

try:
    # Do something
    print(q)

# Catch exceptions  
except Exception as e:
    print (1)

except ArithmeticError as e:
    print (2)

# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement

else:
    print (3)

您还可以检查异常是否属于“MyCustomException”类型,例如使用 if 语句。

if isinstance(e, MyCustomException):
    # Do something
    print(1)

至于你的问题,我建议将代码分成两个函数。

install(required_libraries)

def install(required_libraries, version='pip2.7'):
    # Perform installation
    try:
        from subprocess import check_output
        pip27_path = subprocess.check_output(['sudo','find','/','-name', version])
        lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        backup(required_libraries)

def backup(required_libraries, version='pip2.6'):
    try:
        p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
        lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(e).__name__, e.args)
        print (message)

        #Handle exception

注意:我没有对此进行测试,我也不是专家,所以希望能提供帮助。

有用的链接:

  1. Built-in Exceptions
  2. Errors and Exceptions
  3. Compound statements

【讨论】:

  • 非常感谢您的回复。我会检查哪一个最适合该代码。
  • @Rahul 如果我的建议有效,请接受答案!祝你好运!
  • @我肯定会这样做
  • 第二个代码块中关于 try-except-else 块中 'else' 用途的注释 "If it's an exception but it's not the above" 是不正确。事实上,只有在 'try' 中没有引发任何异常时,才会执行 'else' 套件中的代码。请参阅Python docs:“如果控制流离开 try 套件,则执行可选的 else 子句,没有引发异常,也没有执行 return、continue 或 break 语句。”
  • @MattP 感谢您的澄清,更新了我的帖子
猜你喜欢
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2015-06-21
  • 2011-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多