如何防止python脚本在遇到[Errno 32]损坏的pip时退出

2024-10-02 08:14:19 发布

您现在位置: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循环,有时脚本在遇到以下异常时会自行退出:

^{pr2}$

我希望我的脚本继续运行,即使它取消了这个异常socket.error: [Errno 32] Broken pipe。我怎样才能做到这一点?在


Tags: self脚本loopifservermainonrequest
2条回答

您可以使用blank except策略,但这通常是一种不好的做法。它看起来像

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

‘Check out How to handle a broken pipe (SIGPIPE) in python?这似乎和你的问题很相似。在

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

例如

while 1:
    # Do stuff
    self.on_outbounddata()

这里没有异常处理。仅部分位于函数内部。在

此外,您不处理错误:

^{pr2}$

这里只处理一种类型的异常:

        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

相关问题 更多 >

    热门问题