简体   繁体   中英

Capture return value from python script into shell script

I have a shell script inside of which I am calling a python script say new.py :

#!/usr/bin/ksh

python new.py

Now this new.py is something like -

if not os.path.exists('/tmp/filename'):
    print "file does not exist"
    sys.exit(0)

If the file does not exits then the python script returns but the shell script continue execution. I want the shell script also to stop at that point if the file does nt exits and my python script exits.

Please suggest how can I capture the return in shell script to stop its execution further.

You need to return something other than zero from the exit function.

if os.path.exists("/tmp/filename"):
    sys.exit(0)
else:
    sys.exit(1)

The error value is only 8 bits, so only the lower 8 bits of the integer is returned to the shell. If you supply a negative number, the lower 8 bits of the twos complement representation will be returned, which is probably not what you want. You usually don't return negative numbers.

if ! python new.py
then
  echo "Script failed"
  exit
fi

This assumes that the Python script uses sys.exit(0) when your shell script should continue and sys.exit(1) (or some other non-zero value) when it should stop (it's customary to return a non-zero exit code when an error occurs).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM