【python】Python与shell的交互

一,shell调用python

1,shell直接调用python

shell调用python是比较简单的,直接在.sh脚本中输入执行命令即可,跟在linux环境下没有什么两样:

加上“python”是具有软连接的;

python filename.py

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一杯拿铁go

你的打赏是我更新最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值