[Tutor] Error Handling in python
Steven D'Aprano
steve at pearwood.info
Thu Jul 24 14:08:05 CEST 2014
On Thu, Jul 24, 2014 at 05:05:24PM +0530, jitendra gupta wrote:
> Hi All
>
> My shell script is not throwing any error when I am having some error in
> Python code.
This is a question about the shell, not about Python. I'm not an expert
on shell scripting, but I'll try to give an answer.
> ~~~~~ shellTest.sh ~~~~~~~
> python test.py
> python second.py
One fix is to check the return code of the first python process:
[steve at ando ~]$ python -c pass
[steve at ando ~]$ echo $?
0
[steve at ando ~]$ python -c "raise Exception"
Traceback (most recent call last):
File "<string>", line 1, in <module>
Exception
[steve at ando ~]$ echo $?
1
Remember that to the shell, 0 means "no error" and anything else is an
error. So your shell script could look like this:
python test.py
if [ "$?" -eq 0 ]
then
python second.py
fi
Another way (probably better) is to tell the shell to automatically exit
if any command fails:
set -e
python test.py
python second.py
Hope this helps,
--
Steven
More information about the Tutor
mailing list