I could not comment because of reputation, but you absolutely could use the code from nephim comment.
1) just put the first of nephim's code in test.py
(chmod 700 test.py)
2) this ksh script run test.py :
#!/usr/bin/ksh
./test.py
exit $?
3) And this is example from command line
> ./test.ksh
> echo $?
5
P.S.: You should chmod 700 test.ksh as well.
P.P.S : Probably I misunderstood your question.
If your python script exits before it reach the end (and so it don't execute sys.exit(codeRet) command), in this case you should use try..execpt construction.
try :
<some code>
except <Error to Catch>:
sys.exit(codeRet)
As explained here : Python: about catching ANY exception you could even catch all of exceptions :
try:
do_something()
except:
print "Caught it!"
But as explained : "You can but you shouldn't"
Update:
@AlexKinman
I think there is some problem with your python... as mentioned by tripleee could it be some wrapper?
Could you give a return of which python2.7
Here my tests :
$# cat wrong_test.ksh
#!/bin/ksh
log_file=log.txt
python -c 'raise Exception("foo")' >> ${log_file} 2>&1
exit_code=$?
if [ ${exit_code} -ne 0 ]
then
echo "Python script failed" >> ${log_file}
fi
$# cat log.txt
Traceback (most recent call last):
File "", line 1, in
Exception: foo
Python script failed
$# cat good_test.ksh
#!/bin/ksh
log_file=log1.txt
python -c 'print "Hello"' >> ${log_file} 2>&1
exit_code=$?
if [ ${exit_code} -ne 0 ]
then
echo "Python script failed" >> ${log_file}
fi
$# cat log1.txt
Hello
echo "Returncode=$?"python2.7 python_script.pywithpython2.7 -c 'raise Exception("foo")'-- if your shell script suddenly sees a nonzero exit status, you know it's the Python code that's masking the true exit status.if ! python2.7 python_script.py ...; then echo "Python script failed"; fi, not capturing$?at all. But if the Python script is masking its exit status, that won't work either.python -c 'raise ValueError("boom"); echo $?prints1andpython -c 'import time; time.sleep(3600)'when interrupted by ctrl-C likewise returns an exit status of1. Perhaps yourpython2.7command is an incompetently written wrapper which discards the exit status.