Subprocess timeout failure

前端 未结 2 1145
你的背包
你的背包 2020-11-30 05:53

I want to use a timeout on a subprocess

 from subprocess32 import check_output
 output = check_output(\"sleep 30\", shell=True, timeout=1)

2条回答
  •  离开以前
    2020-11-30 06:46

    Update for Python 3.6.

    This is still happening but I have tested a lot of combinations of check_output, communicate and run methods and now I have a clear knowledge about where is the bug and how to avoid it in a easy way on Python 3.5 and Python 3.6.

    My conclusion: It happens when you mix the use shell=True and any PIPE on stdout, stderr or stdin parameters (used in Popen and run methods).

    Be careful: check_output uses PIPE inside. If you look at the code inside on Python 3.6 it is basically a call to run with stdout=PIPE: https://github.com/python/cpython/blob/ae011e00189d9083dd84c357718264e24fe77314/Lib/subprocess.py#L335

    So, to solve @innisfree problem on Python 3.5 or 3.6 just do this:

    check_output(['sleep', '30'], timeout=1)
    

    And for other cases, just avoid mixing shell=True and PIPE, keeping in mind that check_output uses PIPE.

提交回复
热议问题