导语:
获取linux系统内存的方法有很多种方法,这里总结如下
版本1
[root@master test]# cat freemem.py
1
2
3
4
5
6
7
8
9
10
|
#!/usr/bin/env python
memfile
=
open
(
'/proc/meminfo'
)
while
True
:
mem
=
memfile.readline()
if
'MemTotal'
in
mem:
print
'%s'
%
mem,
if
'MemFree'
in
mem:
print
'%s'
%
mem,
break
memfile.close()
|
版本2
[root@master test]# cat freemem.py
1
2
3
4
5
6
7
8
|
#!/usr/bin/env python
memfile
=
open
(
'/proc/meminfo'
)
i
=
0
while
i<
2
:
i
+
=
1
mem
=
memfile.readline()
print
"%s"
%
mem,
memfile.close()
|
版本3
[root@master test]# cat freemem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/usr/bin/env python
#coding=utf8
memfile
=
open
(
'/proc/meminfo'
)
i
=
0
while
i<
2
:
mem
=
memfile.readline()
memnum
=
mem.split()[
1
]
if
i
=
=
0
:
print
"内存总量为:%s"
%
memnum
else
:
print
"剩余内存为:%s"
%
memnum
i
+
=
1
memfile.close()
|
版本4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/usr/bin/env python
with
open
(
'/proc/meminfo'
) as fd:
for
line
in
fd:
if
line.startswith(
'MemTotal'
):
total
=
line.split()[
1
]
continue
if
line.startswith(
'MemFree'
):
free
=
line.split()[
1
]
break
FreeMem
=
int
(free)
/
1024.0
TotalMem
=
int
(total)
/
1024.0
print
"FreeMem:"
+
"%.2f"
%
FreeMem
+
'M'
print
"TotalMem:"
+
"%.2f"
%
TotalMem
+
'M'
print
"FreeMem/TotalMem:"
+
"%.2f"
%
((FreeMem
/
TotalMem)
*
100
)
+
'%'
|
版权声明:原创作品,如需转载,请与作者联系。否则将追究法律责任
本文转自 CrazyWing 51CTO博客,原文链接:http://blog.51cto.com/fklinux/1980629