How to make a subprocess.call timeout using python 2.7.6?

后端 未结 5 1961
暗喜
暗喜 2020-12-15 23:31

This has probably been asked but I cannot find anything regarding a subprocess.call timeout when using python 2.7

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 00:04

    You can use subprocess32 mentioned by @gps, which is backport of the subprocess standard library module from Python 3.2 - 3.5 for use on Python 2.

    Firstly, install the subprocess32 module:

    pip install subprocess32
    

    Here's a code snippet:

    >>> import subprocess32
    >>> print subprocess32.check_output(["python", "--version"])
    Python 2.7.12
    
    >>> subprocess32.check_output(["sleep", "infinity"], timeout=3)
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/local/lib/python2.7/dist-packages/subprocess32.py", line 340, in check_output
        raise TimeoutExpired(process.args, timeout, output=output)
    subprocess32.TimeoutExpired: Command '['sleep', 'infinity']' timed out after 3 seconds
    

    Notice, default timeout=None, which means never timeout.

提交回复
热议问题