Home > Backend Development > Python Tutorial > How Can I Add a Timeout to Subprocess Calls in Python?

How Can I Add a Timeout to Subprocess Calls in Python?

DDD
Release: 2024-12-14 02:33:09
Original
176 people have browsed it

How Can I Add a Timeout to Subprocess Calls in Python?

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template