1

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.

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@lucase.62 no- Use subprocess.Popen
2

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=….

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.