In Python, the subprocess
module provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. One useful feature of subprocess
is the ability to set a timeout for a process, ensuring that it doesn’t run indefinitely.
Understanding subprocess.timeout
The subprocess
module has a TimeoutExpired
exception class that can be used to handle timeout situations. This exception is raised when a subprocess takes longer than a specified timeout to complete.
To set a timeout for a subprocess using subprocess
, you need to utilize the timeout
parameter available in certain subprocess
functions. The timeout
value represents the maximum number of seconds the subprocess is allowed to run before timing out.
Example Usage
Let’s take a look at an example that demonstrates how to set a timeout for a subprocess in Python:
import subprocess
try:
# Run the command and set a timeout of 5 seconds
completed_process = subprocess.run(["ping", "-c", "5", "google.com"], timeout=5)
# Print the output of the command
print(completed_process.stdout)
except subprocess.TimeoutExpired:
print("Timeout occurred! The subprocess took longer than the specified timeout.")
except subprocess.CalledProcessError as e:
print(f"Command returned a non-zero exit status: {e.returncode}")
In the above example, we use the subprocess.run()
function to execute the ping
command with a timeout of 5 seconds. If the command completes within the specified timeout, the output of the command is printed. If the timeout is exceeded, a TimeoutExpired
exception is raised and we handle it by printing a timeout message.
Conclusion
Setting a timeout for subprocesses is an essential feature when dealing with potentially long-running processes in Python. With the timeout
parameter provided by the subprocess
module, you can efficiently control the maximum execution time of subprocesses and handle timeout situations accordingly.