一,shell调用python
1,shell直接调用python
shell调用python是比较简单的,直接在.sh脚本中输入执行命令即可,跟在linux环境下没有什么两样:
加上“python”是具有软连接的;
2,shell传参到python的函数并得到返回数据
使用sys来接收参数。使用python -c来调用python的函数。
python端接收为: - import sys
- def function1():
- #print('参数个数为:', len(sys.argv), '个参数。')
- #print('参数列表:', str(sys.argv))
- inputarg=sys.argv[1]
- return inputarg+"Back"
复制代码
shell端调用python函数为: - arg="FromShell"
- RESULT_FOO=`python3 -c 'import table_monitor_util;print(table_monitor_util.function1())' $arg`
- echo "RESULT_FOO is:"$RESULT_FOO
复制代码
这样就可以在shell端,把形参直接传到python的函数中,并得到该函数处理完的结果数据。
输出为: - RESULT_FOO is:FromShellBack
复制代码
二,Python调用shell
Python根据版本的不同需要使用不同的Python库,Python2的话是使用"commands"的库,执行起来非常简单: - exe2_sql = 'ls -l'
- # 分别接收执行后的状态以及返回结果
- (status, output) = commands.getstatusoutput(exe2_sql)
复制代码
Python3没有commands,据说可以用subprocess库代替,暂时还没用过。
最简单的可以用os.popen,如下所示: - import os
- temp = os.popen("ls")
- for line in temp.readlines():
- line=line.strip()
- print(line)
复制代码
subprocess库的用法:python3- subprocess模块. 学习记录_superwshu-CSDN博客_python3 subprocess |