Reputation: 16305
I need to use os.system() a few times in my script, but I don't want errors from the shell to appear in my script's window. Is there a way to do this? I guess it's sort of like silent commands, running to their full extent, but not returning any text. I can't use 'try', because it's not a Python error.
Upvotes: 1
Views: 12385
Reputation: 94575
The recommended way to call a subprocess and manipulate its standard output and standard error is to use the subprocess module. Here is how you can suppress both the standard output and the standard output:
import subprocess
# New process, connected to the Python interpreter through pipes:
prog = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prog.communicate() # Returns (stdoutdata, stderrdata): stdout and stderr are ignored, here
if prog.returncode:
raise Exception('program returned error code {0}'.format(prog.returncode))
If you want the subprocess to print to standard output, you can simply remove the stdout=…
.
Upvotes: 2
Reputation: 500773
You could redirect the command's standard error away from the terminal. For example:
# without redirect
In [2]: os.system('ls xyz')
ls: cannot access xyz: No such file or directory
Out[2]: 512
# with redirect
In [3]: os.system('ls xyz 2> /dev/null')
Out[3]: 512
P.S. As pointed out by @Spencer Rathbun, the subprocess
module should be preferred over os.system()
. Among other things, it gives you direct control over the subprocess's stdout and stderr.
Upvotes: 4