如何防止python脚本在命中[Errno 32]断管时退出

时间:2016-11-17 17:34:22

标签: python

我有一个python脚本,我使用while loop永远循环,我的脚本看起来像这样:

#!/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

我希望我的脚本能够继续,即使它解除了这个异常socket.error: [Errno 32] Broken pipe。我怎么能做到这一点?

2 个答案:

答案 0 :(得分: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?它似乎与您的问题非常相似。

答案 1 :(得分: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