Python's subprocess Module and Timeouts
The subprocess module offers a convenient way to execute external commands, capturing their outputs and managing their lifecycles. However, by default, its communicate() method does not support timeouts. This poses a challenge when executing long-running commands that could potentially deadlock the calling process.
Implementing Timeouts with check_output
Python 3.3 and later provides check_output() as a more efficient alternative to Popen() and communicate(). This function evaluates a command, merges its stdout and stderr outputs into a byte string, and raises a CalledProcessError if the command exits with a non-zero status. Crucially, it also supports timeouts, allowing you to specify a maximum execution time for the command.
from subprocess import STDOUT, check_output seconds = 10 # Timeout in seconds output = check_output(cmd, stderr=STDOUT, timeout=seconds)
In this example, the check_output() function will execute the command specified in cmd and wait for it to complete within 10 seconds. If the command takes longer than 10 seconds, a TimeoutExpired error will be raised.
Using subprocess32 for Timeouts in Python 2.x
For Python 2.x, the subprocess32 backport provides the same timeout functionality as check_output() in Python 3.3 . To install subprocess32, use pip:
pip install subprocess32
Once installed, you can use subprocess32's call() function to execute commands with timeouts:
import subprocess32 seconds = 10 # Timeout in seconds subprocess32.call(cmd, timeout=seconds)
Additional Considerations
The above is the detailed content of How Can I Implement Timeouts When Using Python's `subprocess` Module?. For more information, please follow other related articles on the PHP Chinese website!