return value from python script to shell script

57,284

Solution 1

You can't return message as exit code, only numbers. In bash it can accessible via $?. Also you can use sys.argv to access code parameters:

import sys
if sys.argv[1]=='hi':
    print 'Salaam'
sys.exit(0)

in shell:

#!/bin/bash
# script for tesing
clear
echo "............script started............"
sleep 1
result=`python python/pythonScript1.py "hi"`
if [ "$result" == "Salaam" ]; then
    echo "script return correct response"
fi

Solution 2

Pass command line arguments to shell script to Python like this:

python script.py $1 $2 $3

Print the return code like this:

echo $?
Share:
57,284
Abdul Manaf
Author by

Abdul Manaf

open source programmer

Updated on August 18, 2020

Comments

  • Abdul Manaf
    Abdul Manaf over 3 years

    I am new in Python. I am creating a Python script that returns a string "hello world." And I am creating a shell script. I am adding a call from the shell to a Python script.

    1. i need to pass arguments from the shell to Python.
    2. i need to print the value returned from Python in the shell script.

    This is my code:

    shellscript1.sh

    #!/bin/bash
    # script for testing
    clear
    echo "............script started............"
    sleep 1
    python python/pythonScript1.py
    exit
    

    pythonScript1.py

    #!/usr/bin/python
    import sys
    
    print "Starting python script!"
    try:
        sys.exit('helloWorld1') 
    except:
         sys.exit('helloWorld2') 
    
  • Abdul Manaf
    Abdul Manaf over 8 years
    thanks ali. this code is working fine. but i need to return a string value. how it will be possible?
  • Ali Nikneshan
    Ali Nikneshan over 8 years
    you should capture python result: a=`python python/pythonScript1.py "test"``; echo $a will print what you print in python code
  • zhangboyu
    zhangboyu over 2 years
    In my case, sys.exit(0) doesn't return anything and the shell script stops as well. But print(0) works well. What happens in my case?
  • Ali Nikneshan
    Ali Nikneshan over 2 years
    @zhangboyu , I guess you use ' instead of `
  • zhangboyu
    zhangboyu over 2 years
    @AliNikneshan I really used `
  • zhangboyu
    zhangboyu over 2 years
    @AliNikneshan I noticed what happened. In shell script I set -e, so it stoped while exit(). Is there any other way to get the value while setting -e?