如何捕获Try/Catch Block Python中的所有异常?

Rah*_*hul 3 python subprocess exception python-2.7 python-3.x

我正在编写python代码来安装我的程序在linux环境中所需的所有库包.所以linux可能包含python 2.7或2.6或两者,所以我开发了一个try和除了块代码,将在linux中安装pip包.尝试块代码包含python 2.7版本pip install和Catch块包含python 2.6版本pip install.我的问题是代码的和平工作正常,当我试图在python 2.6中安装pandas它让我有些错误.我想抓住那个例外.你能否告诉我如何改进我的尝试,除了阻止异常的块

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]
Run Code Online (Sandbox Code Playgroud)

hal*_*sec 14

您可以使用一个块捕获几个异常.让我们对异常使用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)
Run Code Online (Sandbox Code Playgroud)

如果您需要捕获几个异常并自己处理每个异常,那么您将为每个异常编写一个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)
Run Code Online (Sandbox Code Playgroud)

您还可以检查异常是否为"MyCustomException"类型,例如使用if语句.

if isinstance(e, MyCustomException):
    # Do something
    print(1)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

注意:我没有测试过这个,我也不是专家,所以我希望我能提供帮助.

有用的链接:

  1. 内置例外
  2. 错误和例外
  3. 复合语句

  • 关于 try- except-else 块中 'else' 的目的,第二个代码块中的注释 *“如果它是异常,但不是上述任何一个”* 是不正确的。事实上,只有在“try”中没有引发任何异常时,才会执行“else”套件中的代码。请参阅 [Python 文档](https://docs.python.org/2/reference/compound_stmts.html?highlight=try%20 except#the-try-statement):“如果控制流离开,则执行可选的 else 子句try 套件中,没有引发异常,也没有执行 return、 continue 或 break 语句。” (2认同)