return value from python script to shell script

2020-06-08 03:57发布

问题:

am new in python. am create a python script that return a string hello world. and am create a shell script. add a call from shell to python script.

  1. i need to pass arguments from shell to python.
  2. i need to print the value return from python in the shell script.

this is my code

shellscript1.sh

#!/bin/bash
# script for tesing
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') 

回答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


回答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 $?