每天一篇python:执行shell命令

今天学习一下如何使用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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值