Get exit(1) from Python in shell

2019-12-16 21:05发布

问题:

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.

回答1:

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

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


回答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
    


标签: python shell