怎么在shell脚本中执行python脚本并接收其返回值

2024-03-14,

这篇文章主要介绍“怎么在shell脚本中执行python脚本并接收其返回值”,在日常操作中,相信很多人在怎么在shell脚本中执行python脚本并接收其返回值问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么在shell脚本中执行python脚本并接收其返回值”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1.在shell脚本执行python脚本时,需要通过python脚本的返回值来判断后面程序要执行的命令

例:有两个py程序  hello.py

代码如下:

def main():
    print "Hello"

if __name__=='__main__':
    main()
world.py

def main():
    print "Hello"

if __name__=='__main__':
    main()

shell 脚本 test.sh

代码如下:

python hello.py
python world.py

执行sh test.sh 打印结果为

代码如下:

  hello
  world

在hello.py中通过返回值  让shell脚本通过参数来判断,

hello.py这样写

代码如下:

import sys

def main():
    try:
        print "hello"
        sys.exit(0)
    except:
        sys.exit(1)

if __name__=='__main__':
    main()

shell 脚本改为

代码如下:

python hello.py
if [ $?==0 ];then
    exit
else
        python world.py       
fi

到此,关于“怎么在shell脚本中执行python脚本并接收其返回值”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注本站网站,小编会继续努力为大家带来更多实用的文章!

《怎么在shell脚本中执行python脚本并接收其返回值.doc》

下载本文的Word格式文档,以方便收藏与打印。