今天学习一下如何使用python执行shell命令。
'''
Created on 2016年4月19日
@author: liujicheng
@title: Python下调用Linux的Shell命令
'''
import os
import commands
'''
分析:
需要手动处理shell字符的转义,比如空格等。此外,这也只能运行简单的shell命令而且不能运行外部程序。
'''
def method_1():
os.system("ls")
def method_11():
val=os.system("ls -al | grep \"log1\"")
print val
def method_2():
val=os.popen('ls -lt').read()
print val
'''
使用commands模块的getoutput方法,这种方法同popend的区别在于popen返回的是一个类文件对象,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。
主要方法:
* commands.getstatusoutput(cmd) 返回(status, output)
* commands.getoutput(cmd) 只返回输出结果
* commands.getstatus(file) 返回ls -ld file的执行结果字符串,调用了getoutput,不建议使用此方法
'''
def method_3():
val1=commands.getoutput("ls")
val2= commands.getstatusoutput('ls -lt')
print val1
print val2
from subprocess import call
def method_4():
code=call(["ls", "-l"])
print code
if __name__ == '__main__':
method_4()