从 python 脚本返回值到 shell 脚本

新手上路,请多包涵

我是 Python 新手。我正在创建一个返回字符串“hello world”的 Python 脚本。我正在创建一个 shell 脚本。我正在添加从 shell 到 Python 脚本的调用。

  1. 我需要将参数从 shell 传递给 Python。
  2. 我需要在 shell 脚本中打印从 Python 返回的值。

这是我的代码:

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 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

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

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

在外壳中:

 #!/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

原文由 Ali Nikneshan 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 python script.py $1 $2 $3

像这样打印返回码:

 echo $?

原文由 coffee-converter 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏