Timeout on subprocess readline in Python

后端 未结 6 2100
既然无缘
既然无缘 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:57

    Try using signal.alarm:

    #timeout.py
    import signal, sys
    
    def timeout(sig, frm):
      print "This is taking too long..."
      sys.exit(1)
    
    signal.signal(signal.SIGALRM, timeout)
    signal.alarm(10)
    byte = 0
    
    while 'IT' not in open('/dev/urandom').read(2):
      byte += 2
    print "I got IT in %s byte(s)!" % byte
    

    A couple of runs to show it works:

    $ python timeout.py 
    This is taking too long...
    $ python timeout.py 
    I got IT in 4672 byte(s)!
    

    For a more detailed example, see pGuides.

提交回复
热议问题