Using module 'subprocess' with timeout

后端 未结 29 2401
旧巷少年郎
旧巷少年郎 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 15:59

    In Python 3.3+:

    from subprocess import STDOUT, check_output
    
    output = check_output(cmd, stderr=STDOUT, timeout=seconds)
    

    output is a byte string that contains command's merged stdout, stderr data.

    check_output raises CalledProcessError on non-zero exit status as specified in the question's text unlike proc.communicate() method.

    I've removed shell=True because it is often used unnecessarily. You can always add it back if cmd indeed requires it. If you add shell=True i.e., if the child process spawns its own descendants; check_output() can return much later than the timeout indicates, see Subprocess timeout failure.

    The timeout feature is available on Python 2.x via the subprocess32 backport of the 3.2+ subprocess module.

提交回复
热议问题