2012-03-26 93 views
-1

我运行一个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 

的代码工作正常,除了尝试:除了语句作为其不能正确捕捉异常,下面是输出当接口关闭的时候,现在我想要在except语句中捕捉第一行......而不是产生它......这是可能的吗?

SIOCSIFFLAGS: Cannot assign requested address 

PROBLEM 
+3

向我们展示了整个堆栈跟踪。是什么让你觉得有问题?如果您的除外条款没有被触发,则没有例外。 – Marcin 2012-03-26 11:34:51

+0

如果curl命令的输出中存在问题,则只会引发异常。 – 2012-03-26 11:38:01

回答

3

如果在子流程中发生任何异常,它将不会被抛出。 检查标准错误,并提高相应的异常

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 
5

没有抛出异常。 您可以检查返回代码,并抛出一个异常时,它不是零:

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 
0

您确实需要调用了卷曲?其次,它听起来像你的接口地址是不礼貌的,而不是你的代码。检查--interface标志参数的正确性(即:运行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