Python subprocess timeout?

后端 未结 10 2122
旧时难觅i
旧时难觅i 2020-12-09 04:06

Is there any argument or options to setup a timeout for Python\'s subprocess.Popen method?

Something like this:

subprocess.Popen([\'..\'], ..., timeout

10条回答
  •  伪装坚强ぢ
    2020-12-09 04:35

    For Linux, you can use a signal. This is platform dependent so another solution is required for Windows. It may work with Mac though.

    def launch_cmd(cmd, timeout=0):
        '''Launch an external command
    
        It launchs the program redirecting the program's STDIO
        to a communication pipe, and appends those responses to
        a list.  Waits for the program to exit, then returns the
        ouput lines.
    
        Args:
            cmd: command Line of the external program to launch
            time: time to wait for the command to complete, 0 for indefinitely
        Returns:
            A list of the response lines from the program    
        '''
    
        import subprocess
        import signal
    
        class Alarm(Exception):
            pass
    
        def alarm_handler(signum, frame):
            raise Alarm
    
        lines = []
    
        if not launch_cmd.init:
            launch_cmd.init = True
            signal.signal(signal.SIGALRM, alarm_handler)
    
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        signal.alarm(timeout)  # timeout sec
    
        try:
            for line in p.stdout:
                lines.append(line.rstrip())
            p.wait()
            signal.alarm(0)  # disable alarm
        except:
            print "launch_cmd taking too long!"
            p.kill()
    
        return lines        
    launch_cmd.init = False
    

提交回复
热议问题