简体   繁体   English

从 python 脚本返回值到 shell 脚本

[英]return value from python script to shell script

I am new in Python.我是 Python 新手。 I am creating a Python script that returns a string "hello world."我正在创建一个返回字符串“hello world”的 Python 脚本。 And I am creating a shell script.我正在创建一个shell脚本。 I am adding a call from the shell to a Python script.我正在添加从 shell 到 Python 脚本的调用。

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

This is my code:这是我的代码:

shellscript1.sh shellscript1.sh

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

You can't return message as exit code, only numbers.您不能将消息作为退出代码返回,只能返回数字。 In bash it can accessible via $?在 bash 中,它可以通过$? . . Also you can use sys.argv to access code parameters:您也可以使用sys.argv访问代码参数:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM