Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Try/catch块Python中捕获所有异常?_Python_Python 3.x_Python 2.7_Exception_Subprocess - Fatal编程技术网

如何在Try/catch块Python中捕获所有异常?

如何在Try/catch块Python中捕获所有异常?,python,python-3.x,python-2.7,exception,subprocess,Python,Python 3.x,Python 2.7,Exception,Subprocess,我正在编写python代码,以便在linux环境中安装我的程序所需的所有库软件包。因此linux可能包含python 2.7或2.6或两者,因此我开发了一个try and Exception块代码,用于在linux中安装pip软件包。Try块代码由python2.7版本的pip安装组成,Catch块包含python2.6版本的pip安装。我的问题是,代码的和平运行得很好,当我试图在python 2.6中安装pandas时,它给我带来了一些错误。我想抓住那个例外。你能告诉我如何改进我的try-ex

我正在编写python代码,以便在linux环境中安装我的程序所需的所有库软件包。因此linux可能包含python 2.7或2.6或两者,因此我开发了一个try and Exception块代码,用于在linux中安装pip软件包。Try块代码由python2.7版本的pip安装组成,Catch块包含python2.6版本的pip安装。我的问题是,代码的和平运行得很好,当我试图在python 2.6中安装pandas时,它给我带来了一些错误。我想抓住那个例外。你能告诉我如何改进我的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]

您可以使用一个块捕获多个异常。让我们对异常使用异常和算术错误

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
注意:我没有测试这个,我也不是专家,所以我希望我能帮上忙

有用链接:


  • 再试一次:除了:块内除了你已经有了吗?@ChrisCharles刚才我也试过了。还是没赶上火车exception@ChrisCharles除了:try: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])用于所需的_库中的i],例外情况除外,如e:logging.info(“pip_安装函数'%s'%e中的错误”),非常感谢您的回复。我会检查哪一个最适合代码。@Rahul如果我的建议有效,请接受答案!祝你好运@当然我会这么做,第二个代码块中关于try-except-else块中“else”用途的注释“If is-exception,but's none of the over”是不正确的。事实上,“else”套件中的代码只有在“try”中没有引发任何异常时才会执行。请参阅:“如果控制流离开try套件,则执行可选的else子句,没有引发异常,也没有执行return、continue或break语句。”@MattP感谢您的澄清,更新了我的帖子