如何防止Python脚本从离开时,命中[错误32]破管

问题描述:

我有一个python脚本和我使用的是while loop到永远循环下去,我的剧本是这样的:如何防止Python脚本从离开时,命中[错误32]破管

#!/usr/bin/python 

import socket,select,time,base64,os,sys,re,datetime 

def on_outbounddata(self): 
     print "ON_OUTBOUNDDATA" 
     netdata = self.netdata 
     if netdata.find('HTTP/1.') ==0: 
      ms = re.search(r"\^s(\d+)\^", payload) 
      if ms: 
       print "Sleeping for " + ms.group(1) + "ms" 
       dec = int(ms.group(1))/float(1000) 
       time.sleep(dec) 
       print self.request[self.s] 
       try: 
        self.channel_[self.s].send(self.request[self.s]) 
        self.request[self.s]='' 
       except ValueError: 
        print "self.s is not in the list (on_outbounddata)" 
        pass 
      netdata='HTTP/1.1 200 Connection established\r\n\r\n' 
     try: 
      self.channel[self.s].send(netdata) 
     except Exception, e: 
      print e 
def main_loop(self): 
    while 1: 
     # Do stuff 
     self.on_outbounddata() 
     # Do stuff 

if __name__ == '__main__': 
    server = TheServer('0.0.0.0', listen) 
    try: 
     server.main_loop() 
    except KeyboardInterrupt: 
     print "Ctrl C - Stopping server" 

问题是,即使我有一个while循环,有时脚本将自行退出,当它遇到以下异常:

Traceback (most recent call last): 
    File "/usr/bin/socks", line 206, in <module> 
    server.main_loop() 
    File "/usr/bin/socks", line 121, in main_loop 
    self.on_outbounddata() 
    File "/usr/bin/socks", line 190, in on_outbounddata 
    self.channel_[self.s].send(self.request[self.s]) 
socket.error: [Errno 32] Broken pipe 

我想我的剧本继续即使excounters此异常socket.error: [Errno 32] Broken pipe。我怎样才能做到这一点?

+0

的可能的复制[如何处理在Python破裂的管道(SIGPIPE)? ](http://*.com/questions/180095/how-to-handle-a-broken-pipe-sigpipe-in​​-python) – quamrana

可能使用一个空白,但政策,但这是一个不好的做法通常。它看起来像'

try: 
    self.channel[self.s].send(netdata) 
except Exception, e: 
    print e 
except: 
    code for blanket exception 

`检查出How to handle a broken pipe (SIGPIPE) in python?它似乎是一个非常类似于你的问题。

+0

如果这是不好的做法,为什么把它作为解决方案吗? – marcusshep

+0

它会阻止他的程序抛出异常,但这样做可能会导致其他异常。在我发布的链接中有一个更优雅的解决方案,但是如果OP正在尝试做一些快速而肮脏的事情,OP可能不需要该解决方案。不过,我想确保他知道这两种方式。 –

+0

他/她清楚地知道。他们在脚本中使用try/except几次。 – marcusshep

你没有提供一个工作的例子,所以答案只能是一点理论。 尝试对发生异常的每个点进行异常处理。

E.g.

while 1: 
    # Do stuff 
    self.on_outbounddata() 

这里没有异常处理。只是部分在函数内部。

而且在这里你不处理错误:

try: 
     server.main_loop() 
    except KeyboardInterrupt: 
     print "Ctrl C - Stopping server" 

在这里你只处理一个类型的异常:

 try: 
      self.channel_[self.s].send(self.request[self.s]) 
      self.request[self.s]='' 
     except ValueError: 
      print "self.s is not in the list (on_outbounddata)" 
      pass 
+0

如何处理任何类型的异常?所以它不只是一个 – hillz

+0

使用多行,除了行。来自python文档的简单示例(查看具有多行除外的示例):https://docs.python.org/2.7/tutorial/errors.html#handling-exceptions – quantummind