Suppress output in Python calls to executables Suppress output in Python calls to executables python python

Suppress output in Python calls to executables


import osimport subprocesscommand = ["executable", "argument_1", "argument_2"]with open(os.devnull, "w") as fnull:    result = subprocess.call(command, stdout = fnull, stderr = fnull)

If the command doesn't have any arguments, you can just provide it as a simple string.

If your command relies on shell features like wildcards, pipes, or environment variables, you'll need to provide the whole command as a string, and also specify shell = True. This should be avoided, though, since it represents a security hazard if the contents of the string aren't carefully validated.


If you have Python 2.4, you can use the subprocess module:

>>> import subprocess>>> s = subprocess.Popen(['cowsay', 'hello'], \      stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]>>> print s _______ < hello > -------         \   ^__^         \  (oo)\_______            (__)\       )\/\                ||----w |                ||     ||


In Python 3.3 and higher, subprocess supports an option for redirecting to /dev/null. To use it, when calling .Popen and friends, specify stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, as keyword arguments.

So DNS's answer, rewritten for Python 3.3+, becomes

import subprocesscommand = ["executable", "argument_1", "argument_2"]result = subprocess.call(command,                         stdout=subprocess.DEVNULL,                         stderr=subprocess.DEVNULL)

From the documentation:

subprocess.DEVNULL¶

Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used.

New in version 3.3.

For Python 3.0 to 3.2, you have to manually open the null device using open(os.devnull), as DNS wrote.