如何在Try / Catch Block Python中捕获所有异常? [英] How to catch all exceptions in Try/Catch Block Python?

查看:570
本文介绍了如何在Try / Catch Block Python中捕获所有异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写python代码以在Linux环境中安装我的程序所需的所有库程序包。因此linux可能包含python 2.7或2.6或同时包含这两个程序,因此我进行了尝试,除了阻止代码外,还将在其中安装pip程序包linux。尝试块代码包含python 2.7版本的pip安装,而Catch块包含python 2.6版本的pip安装。我的问题是,当我尝试在python 2.6中安装pandas时,代码的安全性正常运行,这使我有些误解。我想抓住那个例外。能否请您告诉我如何改进除阻止该异常的块以外的尝试

I am writing python code to install all the library packages required by my program in the linux environment.So the linux may contain python 2.7 or 2.6 or both so I have developed a try and except block codes that will install pip packages in linux. Try block code consists of python 2.7 version pip install and Catch block contains python 2.6 version pip install. My Problem is the peace of code is working fine, when i tried to install pandas in python 2.6 its getting me some errror. I want to catch that exception. Can you please tell me how to improve my try except blocks to catch that exception

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]


推荐答案

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

You can catch several exceptions using one block. Let's use Exception and ArithmeticError for exceptions.

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语句。

If you need to catch several exceptions and handle each one on its own then you'd write an except statement for each one.

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类型,例如

You can also check if the exception is of type "MyCustomException" for example using if statements.

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

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

As for your problem, I suggest splitting the code into two functions.

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

注意:我没有测试过,我也不是专家,所以我希望可以提供帮助。

Note: I didn't test this, I'm no expert as well so I hope I can help.

有用的链接:


  1. 内置异常

  2. 错误和异常

  3. 复合语句

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

这篇关于如何在Try / Catch Block Python中捕获所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆