python的popen
函数的使用,主要是用来执行linux命令。
这种调用方式是通过管道的方式来实现,函数返回一个file-like的对象,里面的内容是脚本输出的内容(可简单理解为echo输出的内容)
使用介绍
import os
cmd="ls -la"
result_list=os.popen(cmd)#查看当前目录下文件列表
print result_list
read() 读取整个文件,并将整个文件放入一个字符串变量中
readline() 每次读取一行,返回一个字符串对象并保留当前行的内存
readlines() 读取整个文件,并将整个文件按行解析成列表
复杂的命令往往需要通过解析获取的数据来得到需要的部分值。通常使用正则匹配,字符过滤等方式。下面介绍几种常用方法:
"""
去除空字符串
"""
def not_empty(s):
return s and s.strip()
"""
在shell终端每行数据中查找固定的字符返回行号
"""
def shellfindstrline(cmd,starval):
lineNum = 0
try:
x = os.popen(cmd).readlines()
if x == "" or x == " " or x.isspace() != False:
print("popen read is null")
return lineNum
result = []
for i in range(0, len(x) - 1):# 由于原始结果需要转换编码,所以循环转为utf8编码并且去除\n换行
res = x[i].strip("\n")
if starval in res: #在每行中查找固定的字符 i为行号
lineNum = i
except:
print("get shell lineNum error")
return lineNum