aboutsummaryrefslogtreecommitdiff
blob: e8ad93805ecc9186697ee15a128e7c750ed1c105 (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Copyright 2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

import os
import platform
import subprocess

from portage import _unicode_decode

def get_vm_info():

	vm_info = {}

	if platform.system() == 'Linux':
		try:
			proc = subprocess.Popen(["free"],
				stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
		except OSError:
			pass
		else:
			output = _unicode_decode(proc.communicate()[0])
			if proc.wait() == os.EX_OK:
				for line in output.splitlines():
					line = line.split()
					if len(line) < 2:
						continue
					if line[0] == "Mem:":
						try:
							vm_info["ram.total"] = int(line[1]) * 1024
						except ValueError:
							pass
						if len(line) > 3:
							try:
								vm_info["ram.free"] = int(line[3]) * 1024
							except ValueError:
								pass
					elif line[0] == "Swap:":
						try:
							vm_info["swap.total"] = int(line[1]) * 1024
						except ValueError:
							pass
						if len(line) > 3:
							try:
								vm_info["swap.free"] = int(line[3]) * 1024
							except ValueError:
								pass

	else:

		try:
			proc = subprocess.Popen(["sysctl", "-a"],
				stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
		except OSError:
			pass
		else:
			output = _unicode_decode(proc.communicate()[0])
			if proc.wait() == os.EX_OK:
				for line in output.splitlines():
					line = line.split(":", 1)
					if len(line) != 2:
						continue
					line[1] = line[1].strip()
					if line[0] == "hw.physmem":
						try:
							vm_info["ram.total"] = int(line[1])
						except ValueError:
							pass
					elif line[0] == "vm.swap_total":
						try:
							vm_info["swap.total"] = int(line[1])
						except ValueError:
							pass
					elif line[0] == "Free Memory Pages":
						if line[1][-1] == "K":
							try:
								vm_info["ram.free"] = int(line[1][:-1]) * 1024
							except ValueError:
								pass

	return vm_info