2016-11-17 49 views
0

我有一個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://stackoverflow.com/questions/180095/how-to-handle-a-broken-pipe-sigpipe-in​​-python) – quamrana

回答

0

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

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

0

你沒有提供一個工作的例子,所以答案只能是一點理論。 嘗試對發生異常的每個點進行異常處理。

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