Using module 'subprocess' with timeout

后端 未结 29 2404
旧巷少年郎
旧巷少年郎 2020-11-21 15:15

Here\'s the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:

proc = subprocess.P         


        
29条回答
  •  悲&欢浪女
    2020-11-21 16:05

    Another option is to write to a temporary file to prevent the stdout blocking instead of needing to poll with communicate(). This worked for me where the other answers did not; for example on windows.

        outFile =  tempfile.SpooledTemporaryFile() 
        errFile =   tempfile.SpooledTemporaryFile() 
        proc = subprocess.Popen(args, stderr=errFile, stdout=outFile, universal_newlines=False)
        wait_remaining_sec = timeout
    
        while proc.poll() is None and wait_remaining_sec > 0:
            time.sleep(1)
            wait_remaining_sec -= 1
    
        if wait_remaining_sec <= 0:
            killProc(proc.pid)
            raise ProcessIncompleteError(proc, timeout)
    
        # read temp streams from start
        outFile.seek(0);
        errFile.seek(0);
        out = outFile.read()
        err = errFile.read()
        outFile.close()
        errFile.close()
    

提交回复
热议问题