capturing error code from os commands

This is the place for queries that don't fit in any of the other categories.

capturing error code from os commands

Postby alex55555 » Fri Sep 27, 2013 8:56 pm

I'm completely new to Python. How would I capture the error code from OS commands? For example I'm running the following.

import subprocess
output = subprocess.call(["ls", "-l"])
connect = cx_Oracle.Connection( mode = cx_Oracle.SYSDBA)
alex55555
 
Posts: 7
Joined: Fri Sep 27, 2013 6:21 pm

Re: capturing error code from os commands

Postby micseydel » Fri Sep 27, 2013 8:58 pm

Do you mean the error code of ls here? "output" is the return code, which should be 0 here but if there were an error that's where it'd end up. Could you describe what you're trying to do in more details?

Also, in the future, even if it's just 3 lines, please put all code in code tags.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1356
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: capturing error code from os commands

Postby alex55555 » Fri Sep 27, 2013 11:43 pm

I just want to work with the return code of any OS command that I issue from python using the subprocess module. Similarly in shell, I would do the following:

`ls /etc/fstab`
if [ $? != 0 ]; then
echo "ERROR!"
exit
fi
alex55555
 
Posts: 7
Joined: Fri Sep 27, 2013 6:21 pm

Re: capturing error code from os commands

Postby stranac » Sat Sep 28, 2013 10:20 am

Well, subprocess.call() returns the exit code of the process. So you could just check the return value and take the appropriate action.

If you just want to raise an exception if the return code is not 0, subprocess.check_call() does that.

However, if you want both the output of the command and the return code, you'll need to use subprocess.Popen directly.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1144
Joined: Thu Feb 07, 2013 3:42 pm

Re: capturing error code from os commands

Postby alex55555 » Tue Oct 01, 2013 6:06 pm

I found that subprocess can be used to check the error code, but I'm not exactly certain how to use it. Could you provide an example?

Thank you
alex55555
 
Posts: 7
Joined: Fri Sep 27, 2013 6:21 pm

Re: capturing error code from os commands

Postby ochichinyezaboombwa » Tue Oct 01, 2013 7:03 pm

The same way you do it in shell: it it's != 0 then there was an error.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm


Return to General Coding Help

Who is online

Users browsing this forum: heman, micseydel and 4 guests