Ignoring CalledProcessError

I use the subprocess module and check_output() to create a virtual shell in my Python script, and it works great for commands that return a zero exit status, but for those that don't return an exception without printing an error that would be displayed on the output in normal shell.

For example, I expect something to work as follows:

 >>> 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) 

Although I could remove the Python exception message using try and except , I still want cat: non-existing-file: No such file or directory be displayed to the user.

How can I do it?

shell() :

 def shell(command): output = subprocess.check_output(command, shell=True) finished = output.split('\n') for line in finished: print line return 
+6
source share
1 answer

Is something like this possible?

 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 
+2
source

Source: https://habr.com/ru/post/923165/


All Articles