This has probably been asked but I cannot find anything regarding a subprocess.call timeout when using python 2.7
The timeout argument is passed to Popen.communicate() . If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.
The subprocess module provides a function named call. This function allows you to call another program, wait for the command to complete and then return the return code.
To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.
The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.
A simple way I've always done timeouts with 2.7 is utilizing subprocess.poll()
alongside time.sleep()
with a delay. Here's a very basic example:
import subprocess
import time
x = #some amount of seconds
delay = 1.0
timeout = int(x / delay)
args = #a string or array of arguments
task = subprocess.Popen(args)
#while the process is still executing and we haven't timed-out yet
while task.poll() is None and timeout > 0:
#do other things too if necessary e.g. print, check resources, etc.
time.sleep(delay)
timeout -= delay
If you set x = 600
, then your timeout would amount to 10 minutes. While task.poll()
will query whether or not the process has terminated. time.sleep(delay)
will sleep for 1 second in this case, and then decrement the timeout by 1 second. You can play around with that part to your heart's content, but the basic concept is the same throughout.
Hope this helps!
subprocess.poll()
https://docs.python.org/2/library/subprocess.html#popen-objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With