您的位置:首页 > 运维架构 > Shell

每天一篇python:执行shell命令

2016-04-19 23:05 344 查看

今天学习一下如何使用python执行shell命令。

#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
Created on 2016年4月19日

@author: liujicheng
@title:  Python下调用Linux的Shell命令
'''
import os
import commands
#第一种方法使用os.system 方法
'''
分析:
需要手动处理shell字符的转义,比如空格等。此外,这也只能运行简单的shell命令而且不能运行外部程序。
'''
def method_1():
os.system("ls")

#使用val接受返回值,如果返回值上0 表示执行成功,如果返回值上256 表示命令没有返回值
def  method_11():
val=os.system("ls -al | grep \"log1\"")
print val

#第二种方法os模块的popen方法
#要得到命令的输出内容,只需再调用下read()或readlines()等 如a=os.popen(cmd).read()
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
# 第四种方法subprocess模块
def method_4():
code=call(["ls", "-l"])
print code
if __name__ == '__main__':
method_4()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: