python之计算系统空闲内存
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time : 2017/11/30 14:25
# @Author : hantong
# @File : count_free_memory.py
#统计linux系统空闲内存和所有内存
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
#startswith是以。。。开头的字符串,上面表示以MemTotal开头的字符串
total = line.split()[1]
#split切片,上面表示下标1的字符串
continue
if line.startswith('MemFree'):
free = line.split()[1]
break
TotalMem = int(total)/1024000.0
#此处除以1024000,换算下来是GB
FreeMem = int(free)/1024000.0
print('Free Memory = '+"%.2f" % FreeMem +'G')
#%.2f表示保留两位小数
print('Total Memory = '+"%.2f" % TotalMem +'G')
执行结果:
Free Memory = 2.20G
Total Memory = 3.83G
字典与列表相互转换
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/12/1 13:52 # @Author : hantong # @File : fffffff.py #dict与list相互转换 dict = {'name':"hanson",'age':"31"} print(list(dict)) #把字典转换为列表 print(tuple(dict)) #把字典转换为元祖 # l = tuple(dict) # print(str(l)) # print(type(dict)) #第二种字典转换为list的转换方式 f = dict.items() print(f) print(type(f)) #可以看到f的类型是list,此时dict已经被转换为list #list转换为dict new_dict= {} for i in f: new_dict[i[0]] = i[1] #此处是给字典赋值,左边为key,右边是value print(new_dict) print(type(new_dict)) #类型为dict执行结果:
['age', 'name']
('age', 'name')
[('age', '31'), ('name', 'hanson')]
<type 'list'>
{'age': '31'}
<type 'dict'>
{'age': '31', 'name': 'hanson'}
<type 'dict'>