Home >Backend Development >Python Tutorial >How Can I Suppress Verbose Output from Subprocesses in Python?
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.
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)
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)
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!