每天一篇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()
相关文章推荐
- shell env
- shell脚本
- shell编程——条件判断
- -bash: wget: command not found 解决方法
- Python执行shell脚本的几种方式(最好用subprocess.Popen来替代os.system)
- 关于shell脚本source ~/.bash_profile不起作用
- Linux Shell(初识)
- pod install 错误(-bash: pod: command not found)解决方案
- shell判断文件是否存在
- Linux下使用popen()执行shell命令
- shell正则
- linux shell 的here document 用法 (cat << EOF)
- Linux Shell 中的反引号,单引号,双引号
- Shell 脚本的小实战
- 使用Shell脚本查询服务器硬件信息
- linux load 监控,负载监控 ,shell 监控cpu,memory,load average,记录到log
- bash操作小结
- 已解决:登录Linux的 bash4.2$ 问题
- Android_adb shell am/pm使用
- shell 怎么删除文件的最后一行