Python Tutorial
This program is used to find the physical memory size in the machine and converts size into KB.
#!/usr/bin/python import subprocess def get_physical_memory_in_kb(): mem_total_kb = 0 cmd = "sudo dmidecode --type memory | grep 'Size' | grep '[0-9]'" output = subprocess.check_output(cmd,shell=True) for line in output.split('\n'): if line: mem_info = line.split(':')[1].strip() mem_val = mem_info.split(' ') mem_unit = mem_val[1].strip(' ').lower() if mem_unit == 'kb': memory_kb = int(mem_val[0].strip(' ')) elif mem_unit == 'mb': memory_kb = (int(mem_val[0].strip(' ')) * 1024) elif mem_unit == 'gb': memory_kb = (int(mem_val[0].strip(' ')) * 1024 * 1024) mem_total_kb += memory_kb return mem_total_kb if __name__ == '__main__': memory_mb = get_physical_memory_in_kb() print("Memory: "+str(memory_mb)+ " KB")
Output:
$ python memory-unit-converter.py Memory: 16777216 KB
This program is used to find the physical memory size in the machine and converts size into KB and then converts to MB by dividing with 1024.
#!/usr/bin/python import subprocess def get_physical_memory_in_mb(): mem_total_kb = 0 cmd = "sudo dmidecode --type memory | grep 'Size' | grep '[0-9]'" output = subprocess.check_output(cmd,shell=True) for line in output.split('\n'): if line: mem_info = line.split(':')[1].strip() mem_val = mem_info.split(' ') mem_unit = mem_val[1].strip(' ').lower() if mem_unit == 'kb': memory_kb = int(mem_val[0].strip(' ')) elif mem_unit == 'mb': memory_kb = (int(mem_val[0].strip(' ')) * 1024) elif mem_unit == 'gb': memory_kb = (int(mem_val[0].strip(' ')) * 1024 * 1024) mem_total_kb += memory_kb return mem_total_kb/1024 if __name__ == '__main__': memory_mb = get_physical_memory_in_mb() print("Memory: "+str(memory_mb)+ " MB")
Output:
$ python memory-unit-converter.py Memory: 16384 MB
Above program is also rewritten using list comprehension into only two lines of python code as below,
#!/usr/bin/python import subprocess def get_physical_memory_in_mb(): mem_total_kb = 0 cmd = "sudo dmidecode --type memory | grep 'Size' | grep '[0-9]'" output = subprocess.check_output(cmd,shell=True) mem_info = [ line.split(':')[1].strip() for line in output.split('\n') if line ] mem_total_kb = sum ( [ int(line.split(' ')[0])*1024 if line.split(' ')[1].lower() == 'mb' else int(line.split(' ')[0])*1024*1024 for line in mem_info ] ) return mem_total_kb/1024 if __name__ == '__main__': memory_mb = get_physical_memory_in_mb() print("Memory: "+str(memory_mb)+ " MB")
Output:
$ python memory-unit-converter.py Memory: 16384 MB
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page