0

I have python program, which is running from shell. When there is an error in python, it will exit with exit(1) or something else, and I need shell program to get that answer, if there is error, run this program again.

4
  • Are you writing a shell script? Commented Jan 10, 2014 at 9:06
  • both, python program and shell script Commented Jan 10, 2014 at 9:52
  • Yes, but the real question is about shell scripting. Commented Jan 10, 2014 at 10:01
  • @glglgl yes, but i mentioned python because there can be something special for python. Commented Jan 10, 2014 at 13:26

2 Answers 2

2

There is nothing special about Python in this case. You capture the exit code as with any other program:

  • either you evaluate $? where you have this code directly, as in sanyi's answer, or
  • you embed the program call in an if or while condition, where its non-zero-ness is checked:

    if ! python yourprogram.py; then 
       dosomething
    fi
    
Sign up to request clarification or add additional context in comments.

1 Comment

When i searched for this, in most places they called shell script from python, and its not good solution for my project. And I don't have a lot experience with shell scripts.
1

The exit code can be found in the $? See the example:

python yourprogram.py
if [[ $? != 0 ]] ; then 
   dosomething
fi

3 Comments

Thanks a lot. So, shell script automatically gets exit number, i used it with while $? = 1 and it works now very good.
@EminMastizada I would work close to the standard and not check for == 1, but for != 0 indeed. Usually, an exit code of 0 means success, any other value means failure or a special condition, where the meaning of each value is defined by the called program. So if you just want to check for failure, do that. Only check for = 1 if the 1 has another meaning than 2 would have.
(Especially as the OP says "or something else", so the exit code isn't limited to 1, it can also have other values.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.