How to hide output of subprocess
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 How To Hide Output Of Subprocess
00:37 Accepted Answer Score 600
01:06 Answer 2 Score 106
01:26 Answer 3 Score 36
02:16 Answer 4 Score 33
02:31 Thank you
--
Full question
https://stackoverflow.com/questions/1126...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #subprocess #espeak
#avk47
ACCEPTED ANSWER
Score 600
For python >= 3.3, Redirect the output to DEVNULL:
import os
import subprocess
retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL,
    stderr=subprocess.STDOUT)
For python <3.3, including 2.7 use:
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")
ANSWER 2
Score 106
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
ANSWER 3
Score 36
Use subprocess.check_output (new in python 2.7).  It will captures stdout as the return value of the function, which both prevents it from being sent to standard out and makes it availalbe for you to use programmatically.  Like subprocess.check_call, this raises an exception if the command fails, which is generally what you want from a control-flow perspective.  Example:
import subprocess
try:
    output = subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
    # Handle failed call
You can also suppress stderr with:
    output = subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)
For earlier than 2.7, use
import os
import subprocess
with open(os.devnull, 'w')  as FNULL:
    try:
        output = subprocess._check_call(['espeak', text], stdout=FNULL)
    except subprocess.CalledProcessError:
        # Handle failed call
Here, you can suppress stderr with
        output = subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)
ANSWER 4
Score 33
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)