从python脚本返回值到shell脚本

时间:2022-05-23 01:14:02

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.

我是python的新手。我创建一个返回字符串hello世界的python脚本。并创建一个shell脚本。添加从shell到python脚本的调用。

  1. i need to pass arguments from shell to python.
  2. 我需要将参数从shell传递给python。
  3. i need to print the value return from python in the shell script.
  4. 我需要在shell脚本中打印python的返回值。

this is my code

这是我的代码

shellscript1.sh

shellscript1.sh

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

pythonScript1.py

pythonScript1.py

#!/usr/bin/python
import sys

print "Starting python script!"
try:
    sys.exit('helloWorld1') 
except:
     sys.exit('helloWorld2') 

2 个解决方案

#1


14  

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:

您不能将消息作为退出代码返回,只能返回数字。在bash中它可以通过$?访问。您还可以使用sys.argv访问代码参数:

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

in shell:

在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


1  

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

将shell脚本的命令行参数传递给Python,如下所示:

python script.py $1 $2 $3

Print the return code like this:

打印返回码如下:

echo $?

#1


14  

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:

您不能将消息作为退出代码返回,只能返回数字。在bash中它可以通过$?访问。您还可以使用sys.argv访问代码参数:

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

in shell:

在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


1  

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

将shell脚本的命令行参数传递给Python,如下所示:

python script.py $1 $2 $3

Print the return code like this:

打印返回码如下:

echo $?