Suppress output in Python calls to executables

Solution 1:

import os
import subprocess

command = ["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.

Solution 2:

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