Python subprocess stdout to dev null

Stdout to dev/null not working with subprocess module in python3.6

Question: Using on I am trying to invoke a shell script through python script, and expect the stdout to be null i.e. I do not want console output. For example: will return a tuple of strings, one for stdout and another one for stderr output.

Stdout to dev/null not working with subprocess module in python3.6

Using Python 3.6.7 on Ubuntu 18.04.2 LTS

I am trying to invoke a shell script through python script, and expect the stdout to be null i.e. I do not want console output.

def command_execution(self, cmd, cwd=None): """ Execute the command cmd without console output and return the exitcode """ FNULL = open(os.devnull, 'w') # Method1 self.log.debug("Executing command " + cmd) exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True, stdout=subprocess.DEVNULL) # Method1 call exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True, stdout=FNULL) (_,_) = exec_cmd.communicate() exitcode = exec_cmd.returncode self.log.debug("Executed command with exitcode ".format(cmd, exitcode)) return exitcode 

As mentioned above, I tried both FNULL and subprocess.DEVNULL method. But, I still see the output on the console.

Am I missing anything here?

Is it possible that your cmd is outputting to stderr, not stdout?

You can test by doing something like this:

exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 

Python — Subprocess.call and —stdout, @sam btw, adding «2>/dev/null» isn’t the right way to cause call method redirect stderr to /dev/null. Please see how to do it right in my answer. – Samuel. Aug 7, 2016 at 11:25 | Show 2 more comments. Your Answer Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. …

How to hide output of subprocess

I’m using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message:

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

eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib. no socket connect) so i cannot easily read what was printed earlier. Exit code is 0.

Читайте также:  Php mysql connect к базе

Unfortunately there is no documented option to turn off its verbosity, so I’m looking for a way to only visually silence it and keep the open shell clean for further interaction.

For python >= 3.3, Redirect the output to DEVNULL:

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

It is effectively the same as running this shell command:

retcode = os.system("echo 'foo' &> /dev/null") 

Here’s a more portable version (just for fun, it is not necessary in your case):

#!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE, STDOUT try: from subprocess import DEVNULL # py3k except ImportError: import os DEVNULL = open(os.devnull, 'wb') text = u"René Descartes" p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT) p.communicate(text.encode('utf-8')) assert p.returncode == 0 # use appropriate for your program error handling here 

Use subprocess.check_output (new in python 2.7). It will suppress stdout and raise an exception if the command fails. (It actually returns the contents of stdout, so you can use that later in your program if you want.) Example:

import subprocess try: subprocess.check_output(['espeak', text]) except subprocess.CalledProcessError: # Do something 

You can also suppress stderr with:

 subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT) 
import os import subprocess with open(os.devnull, 'w') as FNULL: try: subprocess._check_call(['espeak', text], stdout=FNULL) except subprocess.CalledProcessError: # Do something 

Here, you can suppress stderr with

 subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL) 

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess text = 'Hello World.' print(text) subprocess.call(['espeak', text], stderr=subprocess.DEVNULL) 

Subprocess — Python os.system without the output, The subprocess module allows you to create an object which represents a running external process. You can read it from it’s stdout/stderr, write to it’s stdin, send it signals, terminate it etc. The main object in the module is Popen. There are a bunch of other convenience methods like call etc.

Читайте также:  Новое окно

How to pipe the output of a command to `/dev/null` in python

I am trying to pipe the output of the following command to /dev/null so that it doesn’t get printed for the user that is running the program.

import os os.system("ping -c 1 192.168.unknown.host > /dev/null") 
ping: unknown host 192.168.unknown.host 

The problem is that this message is produced by something other than stdout , probably stderr and I can easily redirect it to /dev/null using

ping -c 1 192.168.unknown.host >& /dev/null 

However, when I use that in python, I get the following error:

sh: 1: Syntax error: Bad fd number 

Is it possible to solve this? (I just don’t want that message to be printed).

import subprocess subprocess.Popen( ['ping', "-c", "192.168.unknown.host"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) 

As pointed out by Ashwini Chaudhary, for Python below 3.3 you have to manually open os.devnull :

import os import subprocess with open(os.devnull, 'w') as DEVNULL: subprocess.Popen( ['ping', "-c", "192.168.unknown.host"], stdout=DEVNULL, stderr=DEVNULL, ) 

You should take a look at the Python subprocess module. It offers several methods that can handle standard input, output and error.

import subprocess as sub import shlex cmd = "ping -c 1 myhost" cmdarg = shlex.split(cmd) p = sub.Popen(cmdarg,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() 

Python subprocess.run([‘diff’, path1, path2], cmd = subprocess.run([«diff», path1.csv, path2.csv], stdout=subprocess.DEVNULL) self.assertEqual(cmd.returncode, 0) Here, I get the error: AssertionError: 1 != 0 The subprocess command is intended to test the difference between the two files. It shows a difference even when there isn’t any …

Python subprocess hide stdout and wait it to complete

def method_a(self): command_line = 'somtoolbox GrowingSOM ' + som_prop_path subprocess.Popen(shlex.split(command_line)) . def method_b(self): . . 

and like you all see, method_a has a subprocess that is calling the somtoolbox program. But this program have a long stdout, and I want to hide it. I tried:

subprocess.Popen(shlex.split(command_line), stdout=subprocess.PIPE) 

But it returned this sentence:

cat: record error: Broked Pipe 

(this is a translation of the portuguese sentence: «cat: erro de gravação: Pipe quebrado») (I’m from brazil)

Читайте также:  Sign Up

Also, I have other methods (like method_b there), that are called after the method_a, and tis methods are running before the subprocess complete the process.

How I can hide the stdout at all (and don’t want it anywhere), and make the other code wait for the subprocess to finish the execution ?

Obs: The somtoolbox is a java program, that gives the long output to the terminal. Tried:

outputTuple = subprocess.Popen(shlex.split(command_line), stdout = subprocess.PIPE).communicate() 

but continuous returning output to the shell. Help!

The best way to do that is to redirect the output into /dev/null. You can do that like this:

devnull = open('/dev/null', 'w') subprocess.Popen(shlex.split(command_line), stdout=devnull) 

Then to wait until it’s done, you can use .wait() on the Popen object, getting you to this:

devnull = open('/dev/null', 'w') process = subprocess.Popen(shlex.split(command_line), stdout=devnull) retcode = process.wait() 

retcode will then contain the return code of the process.

ADDITIONAL: As mentioned in comments, this won’t hide stderr. To hide stderr as well you’d do it like so:

devnull = open('/dev/null', 'w') process = subprocess.Popen(shlex.split(command_line), stdout=devnull, stderr=devnull) retcode = process.wait() 

Popen.communicate is used to wait for the process to terminate. For example:

from subprocess import PIPE, Popen outputTuple = Popen(["gcc", "--version"], stdout = PIPE).communicate() 

will return a tuple of strings, one for stdout and another one for stderr output.

Python — Writing subprocess stdout to a file truncates to, There are no pipes here; Popen only creates them if you pass it subprocess.PIPE. Most programming languages have a standard library that buffers output to files, to reduce the number of system calls (which are expensive). 4096 bytes is a common default size for the buffer. If the process exits normally, …

Источник

Оцените статью