Using module 'subprocess' with timeout

后端 未结 29 2436
旧巷少年郎
旧巷少年郎 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:54

    timeout is now supported by call() and communicate() in the subprocess module (as of Python3.3):

    import subprocess
    
    subprocess.call("command", timeout=20, shell=True)
    

    This will call the command and raise the exception

    subprocess.TimeoutExpired
    

    if the command doesn't finish after 20 seconds.

    You can then handle the exception to continue your code, something like:

    try:
        subprocess.call("command", timeout=20, shell=True)
    except subprocess.TimeoutExpired:
        # insert code here
    

    Hope this helps.

提交回复
热议问题