主要是通过os.popen读取命令输出实现的,os.popen启动新的进程,且将外部命令的输出作为文件类型对象返回。不能获得外部命令的返回值。既然是文件对象就可以直接用for in 来读取,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#!/usr/bin/python #fileName:getinfoinsh.py #get cpu,meminfo from top command. import
os
import
time
def
getinfointop():
topp = os.popen( "top -n1|grep -E ‘^Cpu|^Mem‘" )
toppstr = topp.read()
replacestr = [ "\x1b" , "[m" , "\x0f" , "[K" ]
# replace the str cannt be printed.
for
item in
replacestr:toppstr = toppstr.replace(item,‘‘)
splitstr = toppstr.split( "\n" )
cpuinfo = splitstr[ 0 ].split()
meminfo = splitstr[ 1 ].split()
info = (cpuinfo[ 1 ].strip( ‘,‘ ),cpuinfo[ 2 ].strip( ‘,‘ ),cpuinfo[ 4 ].strip( ‘,‘ ),meminfo[ 3 ],meminfo[ 5 ],meminfo[ 1 ])
return
info
def
getinfoindh():
dhplines = []
for
i in
os.popen( "df -h" ):
dhplines.append(i.strip())
return
dhplines
if
__name__ = = ‘__main__‘ :
info = getinfointop()
diskinfo = getinfoindh()
print
‘cpu info:‘
print
"user cpu used:" ,info[ 0 ]
print
"system cpu used:" ,info[ 1 ]
print
"free cpu:" ,info[ 2 ]
print
‘‘
print
‘Mem info:‘
print
"used mem:" ,info[ 3 ]
print
"free mem:" ,info[ 4 ]
print
"total mem:" ,info[ 5 ]
print
‘‘
print
‘disk info:‘
for
i in
diskinfo: print
i
print
‘‘
print
‘time:‘ , time.strftime( ‘%Y-%m-%d %H:%M‘ ,time.localtime(time.time()))
|
本来想加注释的,结果发现2.7版本的不支持中文注释,replacestr=["\x1b","[m","\x0f","[K"]这里可能不好理解,不知道为什么top命令会输
出一些没办法打印的字符,这个就是用来替换这些字符的。。我没找到更好的方法。
这应该是我写的第一个脚本吧。。。linux,python..i m coming....