Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring CalledProcessError

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
like image 634
user1447941 Avatar asked Aug 18 '12 04:08

user1447941


People also ask

How can we avoid shell true in subprocess?

From the docs: args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

How do I get output to run from subprocess?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

What is Popen in Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.

What is subprocess Check_output in Python?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.


1 Answers

Something like this perhaps?

def shell(command):
    try:
        output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
    except Exception, e:
        output = str(e.output)
    finished = output.split('\n')
    for line in finished:
        print line
    return
like image 163
smang Avatar answered Oct 17 '22 19:10

smang