Using module 'subprocess' with timeout

后端 未结 29 2466
旧巷少年郎
旧巷少年郎 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条回答
  •  Happy的楠姐
    2020-11-21 15:58

    python 2.7

    import time
    import subprocess
    
    def run_command(cmd, timeout=0):
        start_time = time.time()
        df = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while timeout and df.poll() == None:
            if time.time()-start_time >= timeout:
                df.kill()
                return -1, ""
        output = '\n'.join(df.communicate()).strip()
        return df.returncode, output
    

提交回复
热议问题