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

How Can I Suppress Unwanted Output from Subprocesses in Python?

Linda Hamilton
Release: 2024-12-16 04:42:16
Original
390 people have browsed it

How Can I Suppress Unwanted Output from Subprocesses in Python?

Suppression of Subprocess Output in Python

In Python, subprocesses can be employed to execute various system commands. While such subprocesses may provide necessary functionality, their inherent verbosity can clutter output and hamper readability. In particular, consider the example provided by the user:

import subprocess
text = 'Hello World.'
print text
subprocess.call(['espeak', text])
Copy after login

In this instance, eSpeak generates the desired audio output but also produces unwanted error messages. This cluttering of the shell can make it challenging to access or interpret printed text. Unfortunately, there is no documented option to disable eSpeak's verbosity.

To address this issue, Python offers a convenient solution for suppressing subprocess output, allowing users to maintain a clean and clutter-free shell:

Solution:

Redirect the subprocess output to DEVNULL using the following code for Python >= 3.3:

import os
import subprocess

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

For Python versions below 3.3, including 2.7, utilize the code below:

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

This technique effectively mirrors the following shell command:

retcode = os.system("echo 'foo' > /dev/null")
Copy after login

The above is the detailed content of How Can I Suppress Unwanted Output from Subprocesses 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template