How to timeout when executing command line programs in Python?

前端 未结 3 1453
南笙
南笙 2021-01-25 21:21

I am executing Maple from Python and would like to stop the program if it exceeds a maximum time. If its a Python function this can be done by using a timeout-decorator. But I a

相关标签:
3条回答
  • 2021-01-25 21:48

    You can use subprocess.Popen to spawn a child process. Make sure to handle stdout and stderr properly. Then use Popen.wait(timeout) call and kill the process when TimeoutExpired arrive.

    0 讨论(0)
  • 2021-01-25 21:48

    I think you can use

    threading.Timer(TIME, function , args=(,))

    To execute function after a delay

    0 讨论(0)
  • 2021-01-25 22:00

    Use subprocess.Popen() to do your bidding, if you're using Python version prior to 3.3 you'll have to do handle the timeout yourself, tho:

    import subprocess
    import sys
    import time
    
    # multi-platform precision clock
    get_timer = time.clock if sys.platform == "win32" else time.time
    
    timeout = 10  # in seconds
    
    # don't forget to set STDIN/STDERR handling if you need them...
    process = subprocess.Popen(["maple", "args", "and", "such"])
    current_time = get_timer()
    while get_timer() < current_time + timeout and process.poll() is None:
        time.sleep(0.5)  # wait half a second, you can adjust the precision
    if process.poll() is None:  # timeout expired, if it's still running...
        process.terminate()  # TERMINATE IT! :D
    

    In Python 3.3+ it's as easy as calling: subprocess.run(["maple", "args", "and", "such"], timeout=10)

    0 讨论(0)
提交回复
热议问题