1

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am returning sys.exit(-100) now but in shell echo $? gives 155 ...is it like this number is assigned for these kind of error and can I use it safely like if $? != 0 then exit from the shell
You could also do sys.exit(int(not os.path.exists("/tmp/filename"))), if you so desired
5
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).

Comments

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.