Home >Backend Development >Python Tutorial >How Can I Use Python's `subprocess` Module with a Timeout?
Using Module 'subprocess' with Timeout
In Python programming, it is often necessary to execute arbitrary commands and retrieve their output. The 'subprocess' module provides convenient functions for this purpose, but it lacks support for timeouts. This can be a significant limitation when the command is expected to run for an extended period.
The following code demonstrates a simple approach to implementing timeouts in Python:
from subprocess import check_output try: output = check_output(cmd, stderr=STDOUT, timeout=seconds) except CalledProcessError as e: handle_error(e)
The check_output function, introduced in Python 3.3 , allows the caller to specify a timeout in seconds. If the command exceeds the specified time, a CalledProcessError exception is raised. The output of the command is returned in the 'output' variable as a byte string.
For Python 2.x users, the subprocess32 backport module can be used to provide similar functionality.
The above solution eliminates the need for explicit communication with the process and provides a more straightforward mechanism for handling timeouts.
The above is the detailed content of How Can I Use Python's `subprocess` Module with a Timeout?. For more information, please follow other related articles on the PHP Chinese website!