I am using the subprocess
module and check_output()
to create a virtual shell in my Python script, and it works fine for commands that return a zero exit status, however for ones that don't it returns an exception without printing the error that would have been displayed in the output on a normal shell.
For instance, I would expect something to work like this:
>>> shell('cat non-existing-file')
cat: non-existing-file: No such file or directory
But instead, this happens:
>>> shell('cat non-existing-file')
CalledProcessError: Command 'cat non-existing-file' returned non-zero exit status 1 (file "/usr/lib/python2.7/subprocess.py", line 544, in check_output)
Even though I could remove the Python exception message using try
and except
, I still want the cat: non-existing-file: No such file or directory
to display to the user.
How would I go about doing this?
shell()
:
def shell(command):
output = subprocess.check_output(command, shell=True)
finished = output.split('\n')
for line in finished:
print line
return