Skip to main content
 首页 » 编程设计

Python之如何正确设置函数超时

2025年02月15日15cloudgamer

我有 2 个函数,分别称为 on_outbounddata() 和 on_execute 我希望这些函数的超时时间为 3 秒,如果它们花费的时间超过 3 秒,则退出函数并继续运行其他的。这是我的代码:

import socket,select,time,base64,os,sys,re,datetime, signal 
 
class TheServer: 
    input_list = [] 
    channel = {} 
    channel_ = {} 
    request = {} 
 
    def handler(self, signum, frame): 
        print "Time is up (3 sec)" 
        raise Exception("end of time") 
 
    def main_loop(self): 
        self.input_list.append(self.server) 
        while 1: 
            ss = select.select 
            inputready, outputready, exceptready = ss(self.input_list, [], []) 
            for self.s in inputready: 
                if self.s == self.server: 
                    self.on_accept() 
                    break 
                try: 
                    self.netdata = self.s.recv(buffer_size) 
                except Exception, e: 
                    self.netdata ='' 
                if len(self.netdata) == 0: 
                    self.on_close() 
                else: 
                    signal.signal(signal.SIGALRM, self.handler) 
                    signal.alarm(3) 
                    try: 
                        if cmp(self.channel[self.s],self.channel_[self.s]): 
                            self.on_outbounddata() # I want this function to have a timeout of 3 seconds 
                        else: 
                            self.on_execute() # I want this function to have a timeout of 3 seconds 
                    except Exception, exc:  
                        print exc 
 
        def on_execute(self): 
            print "ON_EXECUTE" 
            netdata = self.netdata 
    #----------------------------------------------------------- 
            if netdata.find("CONNECT") ==0: 
                req="CONNECT " + host + ":" + port 
                payloads=payload            
                payloads=payloads.replace('^request^',req) 
                ms = re.search(r"\^s(\d+)\^", payloads) 
                if ms: 
                  pay=payloads.split('^s'+ms.group(1)+'^') 
                  self.request[self.channel[self.s]]=pay[1]; 
                  netdata=pay[0] 
                else: 
                     netdata=payloads 
                #print netdata 
            try: 
                self.channel[self.s].send(netdata) 
            except Exception, e: 
                print e             
    #----------------------------------------------------------- 
        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 
            except: 
                pass 

请注意,我只想将超时应用到 on_outbounddata() 和 on_execute。当我运行该代码时,它不会继续运行其他函数,而是会中断 while 循环。我该如何解决?

这是错误输出:

ON_EXECUTE 
ON_EXECUTE 
ON_OUTBOUNDDATA 
ON_OUTBOUNDDATA 
ON_CLOSE 
ON_CLOSE 
Time is up (3 sec) 
Traceback (most recent call last): 
  File "/usr/bin/socks", line 278, in <module> 
    server.main_loop() 
  File "/usr/bin/socks", line 159, in main_loop 
    inputready, outputready, exceptready = ss(self.input_list, [], []) 
  File "/usr/bin/socks", line 152, in handler 
    raise Exception("end of time") 
Exception: end of time 

请您参考如下方法:

你的问题是因为你之后没有取消设置警报,所以它会继续并在 3 秒后触发,即使你不再在你想要超时的部分。 The documentation解释如何做到这一点:

signal.alarm(time) If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If time is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled. (See the Unix man page alarm(2).) Availability: Unix.