python执行shell脚本_Python 调用 Shell脚本的方法

Python 调用 Shell脚本的方法

1.os模块的popen方法 通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。

>>> os.popen('date -u |wc')

>>> os.popen('date -u |wc').read()'1 6 43\n'

2.利用commands模块 这个模块有个非常好用的方法可以直接读取程序执行的返回值 通过 commands.getstatusoutput() 一个方法就可以获得到返回值和输出

>>> importcommands>>> commands.getstatusoutput('ls /bin/ls')

(0,'/bin/ls')>>> commands.getstatusoutput('cat /bin/junk')

(256, 'cat: /bin/junk: No such file or directory')>>> commands.getstatusoutput('/bin/junk')

(256, 'sh: /bin/junk: not found')>>> commands.getoutput('ls /bin/ls')'/bin/ls'

>>> commands.getstatus('/bin/ls')'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

3.利用subprocess模块 subprocess模块用来启动可终止其它程序,创建多个进程.想要shell中运行其它程序并获取它的输出,可以使用check_output()方法,它接受一个命令和参数列表

>>> subprocess.check_output(["echo", "Hello World!"])'Hello World!\n'

>>> ret = subprocess.check_output(['date','-u'])>>>ret'2016\xe5\xb9\xb4 05\xe6\x9c\x88 20\xe6\x97\xa5 \xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x94 09:48:44 UTC\n'

本文转载自:https://blog.csdn.net/u010786109/article/details/51463598

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值