Timeout on subprocess readline in Python

后端 未结 6 2101
既然无缘
既然无缘 2020-12-12 22:18

I have a small issue that I\'m not quite sure how to solve. Here is a minimal example:

What I have

scan_process = subprocess.Popen(command, stdout=su         


        
6条回答
  •  無奈伤痛
    2020-12-12 22:59

    I used something a bit more general in Python (if I remember correctly, also pieced together from Stack Overflow questions, but I cannot recall which ones).

    import thread
    from threading import Timer
    
    def run_with_timeout(timeout, default, f, *args, **kwargs):
        if not timeout:
            return f(*args, **kwargs)
        try:
            timeout_timer = Timer(timeout, thread.interrupt_main)
            timeout_timer.start()
            result = f(*args, **kwargs)
            return result
        except KeyboardInterrupt:
            return default
        finally:
            timeout_timer.cancel()
    

    Be warned, though. This uses an interrupt to stop whatever function you give it. This might not be a good idea for all functions and it also prevents you from closing the program with Ctrl + C during the timeout (i.e. Ctrl + C will be handled as a timeout).

    You could use this and call it like:

    scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(some_criterium):
        line = run_with_timeout(timeout, None, scan_process.stdout.readline)
        if line is None:
            break
        else:
            some_criterium = do_something(line)
    

    It might be a bit overkill, though. I suspect there is a simpler option for your case that I don't know.

提交回复
热议问题