return value from python script to shell script

2020-06-08 03:16发布

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') 

2条回答
爷的心禁止访问
2楼-- · 2020-06-08 04:04

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

python script.py $1 $2 $3

Print the return code like this:

echo $?
查看更多
地球回转人心会变
3楼-- · 2020-06-08 04:11

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
查看更多
登录 后发表回答