Utilizing Subprocess Module with Timeout Functionality
The necessity for a subprocess to complete its execution within a predefined time frame often arises in programming. While the subprocess module offers a robust mechanism for executing commands, it inherently lacks timeout capabilities.
To address this limitation, Python 3.3 onwards provides the check_output function within the subprocess module. This function not only fetches the stdout data from the command but also raises an exception when the process exceeds the specified timeout.
from subprocess import STDOUT, check_output # Set the timeout in seconds timeout = 5 try: # Execute the command with the specified timeout output = check_output(cmd, stderr=STDOUT, timeout=timeout) except CalledProcessError as e: # Handle the error if the process fails with a non-zero exit status pass # Process the merged stdout/stderr data contained in the output variable
In this code, the timeout variable determines the maximum permissible execution time for the command. check_output ensures that the process terminates and returns the combined stdout/stderr output within the specified timeframe.
Alternatively, for Python 2.x users, the subprocess32 backport of the subprocess module offers the same functionality. This backport provides a solution equivalent to check_output, allowing for timeout-aware command execution under Python 2.x.
The above is the detailed content of How Can I Add a Timeout to Subprocess Calls in Python?. For more information, please follow other related articles on the PHP Chinese website!