Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress output in Python calls to executables

I have a binary named A that generates output when called. If I call it from a Bash shell, most of the output is suppressed by A > /dev/null. All of the output is suppressed by A &> /dev/null

I have a python script named B that needs to call A. I want to be able to generate output from B, while suppressing all the output from A.

From within B, I've tried os.system('A'), os.system('A > /dev/null'), and os.system('A &> /dev/null'), os.execvp('...'), etc. but none of those suppress all the output from A.

I could run B &> /dev/null, but that suppresses all of B's output too and I don't want that.

Anyone have suggestions?

like image 540
Lin Avatar asked Mar 30 '09 22:03

Lin


People also ask

How do you hide output in Python?

To hide output of subprocess with Python, we can set stdout to subprocess. DEVNULL`. to output the echo command's output to dev null by setting the stdout to subprocess. DEVNULL when we call subprocess.

How do you suppress a message in Python?

Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.


2 Answers

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.

like image 164
DNS Avatar answered Oct 01 '22 04:10

DNS


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 |                 ||     || 
like image 43
Manuel Avatar answered Oct 01 '22 05:10

Manuel