如何在try/catch block python中捕获所有例外



我正在编写python代码以安装我程序在Linux环境中要求的所有库软件包。因此,Linux可能包含Python 2.7或2.6,或者两者都可以尝试,因此我已经开发了一个尝试和尝试将在Linux中安装PIP软件包的块代码。尝试块代码由Python 2.7版本PIP安装和Catch Block包含Python 2.6版本PIP安装。我的问题是,当我试图在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]

您可以使用一个块捕获几个异常。让我们使用异常和算术。

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)

如果您需要捕获几个例外并独自处理每个例外,则为每个例外都编写一个异常语句。

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. 内置异常
  2. 错误和异常
  3. 复合语句

最新更新