python捕捉异常

2024-06-26 13:23:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行curl命令来检查网站的状态:

try:
    connectionTest = subprocess.Popen([r"curl --interface xx.xx.xx.xx http://www.yahoo.com"], shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    cstdout,cstderr = connectionTest.communicate()
    if cstdout:
        #print cstdout
        status = "OK"
    elif cstderr:
        #print cstderr
        status = "PROBLEM"
except:
    e = sys.exc_info()[1]
    print "Error: %s" % e

除了try:except语句由于没有正确捕捉异常,下面是接口关闭时脚本的输出,现在我想捕捉except语句中的第一行。。。相反,它正在繁殖…这可能吗??在

^{pr2}$

Tags: 命令网站状态status语句curlsubprocessprint
3条回答

没有抛出异常。 您可以检查返回代码,并在不为零时引发异常:

import sys, subprocess
try:
    connectionTest = subprocess.Popen([r"curl  interface 1.1.1.1 http://www.yahoo.com"], shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    cstdout,cstderr = connectionTest.communicate()
    if connectionTest.returncode:
        raise Exception("Curl returned %s"%connectionTest.returncode)
    if cstdout:
        #print cstdout
        status = "OK"
    elif cstderr:
        #print cstderr
        status = "PROBLEM"
except:
    e = sys.exc_info()[1]
    print "Error: %s" % e

如果子进程中发生任何异常,则不会引发异常。 检查stderr并引发适当的异常

try:
    connectionTest = subprocess.Popen([r"curl  interface xx.xx.xx.xx http://www.yahoo.com"], shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    cstdout,cstderr = connectionTest.communicate()
    if cstdout:
        #print cstdout
        status = "OK"
    elif cstderr:
        #print cstderr
        status = "PROBLEM"
        raise some exception
except:
    e = sys.exc_info()[1]
    print "Error: %s" % e

你确定你需要叫柯尔吗?在

import urllib2
try:
    urllib2.urlopen("http://www.yahoo.com")
except urllib2.URLError as err:
    print(err)
except urllib2.HTTPError as err:
    print(err)

其次,听起来你的接口地址不可靠,而不是你的代码。检查 interface标志参数的正确性(即:在python之外运行curl命令,并检查它是否按预期工作。

一般来说,您永远无法捕获python程序中的子进程错误(我想这正是您所要求的)。您将不得不依赖于退出代码和stdout/err输出,这就是为什么依赖Python的included batteries的解决方案会更加健壮。在

如果需要手动指定接口,则可以使用其他几个选项:

  1. PyCurl

    import pycurl
    import StringIO
    c = pycurl.Curl()
    c.setopt(pycurl.URL, "http://www.python.org/")
    c.setopt(pycurl.CURLOPT_INTERFACE, "eth0")
    # [...]
    try:
        c.perform()
    except: # Handle errors here.
      pass 
    
  2. Change the source interface manually in python for urllib2

相关问题 更多 >