shell脚本中执行python脚本并接收其返回值的例子

Posted ExplorerMan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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


就可以判断了

 

sh脚本中执行了python脚本,如mysh.sh文件:

python "mypy.py"

result = $?

 

result就是调用python执行的结果。

 

以上是关于shell脚本中执行python脚本并接收其返回值的例子的主要内容,如果未能解决你的问题,请参考以下文章