Home >Backend Development >Python Tutorial >How Can I Suppress Verbose Output from Subprocesses in Python?

How Can I Suppress Verbose Output from Subprocesses in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 00:33:111017browse

How Can I Suppress Verbose Output from Subprocesses in Python?

Muffling Excessive Output from Subprocesses

Many command-line tools, such as eSpeak, display verbose output along with their intended actions. This can clutter the shell, making it difficult to read previous output or interact with the prompt.

For Python scripts that invoke such tools using the subprocess module, silencing their output can enhance readability and usability. One effective method is to redirect standard output (STDOUT) and standard error (STDERR) to a null device.

Redirecting Output for Python 3.3

For Python versions 3.3 and above, the subprocess module provides the DEVNULL constant as a null device. By passing DEVNULL to the stdout and stderr arguments of subprocess.call(), the output of the subprocess is effectively suppressed.

import subprocess

subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL,
    stderr=subprocess.STDOUT)

Redirecting Output for Python 2 and Lower

In earlier versions of Python, including 2.7, the DEVNULL constant is not available. Instead, one can manually open a null device and redirect to it.

import os

FNULL = open(os.devnull, 'w')
subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

Shell Script Equivalent

The command-line equivalent of the above Python code is:

retcode = os.system("echo 'foo' >& /dev/null")

By utilizing these techniques, you can silence verbose subprocess output from your Python scripts, keeping the shell clean and improving readability for further interaction.

The above is the detailed content of How Can I Suppress Verbose Output from Subprocesses in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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