python调shell命令_Python调用Shell命令

前言:在python程序里面难免会用到shell命令,在python调用shell脚本也不是很难,记录了一下!

****通过os模块****

system方法会创建子进程运行外部程序,方法只返回外部程序的运行结果

#os-One

#只返回结果

os.system(command)

sample

import os

print os.system("service apache2 status")

popen方不仅仅返回结果,还返回一个类文件对象,通过调用该对象的read()或readlines()方法可以读取输出内容

#os-Two

#返回结果与终端显示信息

os.popen(command,mode)

sample

import os

output = os.popen('service apache2 status', 'r')

print output.read()

****通过commands模块****

使用commands模块的getoutput方法,这种方法同popend的区别在于popen返回的是一个类文件对象,而本方法将外部程序的输出结果当作字符串返回

#返回(status, output)

commands.getstatusoutput(command)

#只返回输出结果

commands.getoutput(command)

#调用了getoutput,不建议使用此方法

commands.getstatus(file)

sample

import commonds

print commands.getstatusoutput("ls")

print commands.getoutput("ls")

****通过subprocess模块****

subprocess与system相比的优势是它更灵活

#只返回结果

subprocess.call("command", shell=True)

sample

import subprocess

print subprocess.call("service apache2 status", shell=True)

****价值源于技术,贡献源于分享****

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值