容量装换工具
1 import sys
2
3 import socket
4
5 import psutil
6
7 def bytes2human(n):
8 """
9 字节转换工具
10 http://code.activestate.com/recipes/578019
11 #bytes2human(10000)
12 '9.8K'
13 #>>> bytes2human(100001221)
14 '95.4M'
15 :param n:
16 :return:
17 """
18
19 symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
20 prefix = {}
21 for i, s in enumerate(symbols):
22 # 0 K
23 # 1 M
24 prefix[s] = 1 << (i + 1) * 10
25 # {"K": 1024,
26 # "M": 1048576,
27 # "Y": ... }
28 for s in reversed(symbols):
29 if n >= prefix[s]:
30 value = float(n) / prefix[s]
31 return '{:.1f}{}'.format(value, s)
32 return "%sB" % n
获取 CPU 数据信息
35 # ======================== 获取CPU信息 ======================================
36 def get_cpu():
37 # cpu 实例数
38 cpu_count = len(psutil.Process().cpu_affinity())
39
40 # 每颗 cpu 的物理核心数
41 cpu_py_count = psutil.cpu_count(logical=False)
42
43 # cpu 信息
44 cpu_info = psutil.cpu_times_percent(interval=0.1)
45
46 return cpu_count, cpu_py_count, cpu_info
打印 CPU数据信息
48 # ======================== 打印CPU信息 =======================================
49 def display_cpu():
50 cpu_tpl = """
51 ***************************** CPU 信息 ******************************
52 CPU 棵数:{cpu_count} | CPU 物理核心数:{cpu_py_count}
53 CPU 信息:{cpu_info}
54 """
55 cpu_count, cpu_py_count, cpu_info = get_cpu()
56 import sys
57 plf = sys.platform
58 print(cpu_tpl.format(
59 cpu_count=cpu_count,
60 cpu_py_count=cpu_py_count,
61 cpu_info=cpu_info
获取 打印 内存信息
64 # ======================== 打印内存信息 ======================================
65 def display_mem():
66 mem_info = psutil.virtual_memory()
67 print("*" * 30, "内存信息","*" * 30)
68 fileds = ['total', 'free', 'used']
69 for name in mem_info._fields:
70 if name in fileds:
71 val = getattr(mem_info, name)
72 val = bytes2human(val)
73 print("{:<10s} : {}".format(name.capitalize(),val))
获取 打印 网卡信息
75 # ======================== 打印网卡信息 ======================================
76 def display_net():
77 net_ip_dic = psutil.net_if_addrs()
78 net_stat_dic = psutil.net_if_stats()
79
80 for net_name, net_info in net_ip_dic.items():
81 if net_name == 'lo':
82 continue
83 net_stat = net_stat_dic[net_name]
84 print("*" * 30,"网卡信息","*" * 30)
85 print(f"网络{net_name}的状态是:{net_stat.isup}")
86 for addr in net_info:
87 if addr.family == socket.AF_INET:
88 print("IPV4: ",addr.address,f" NETMASK: {addr.netmask}")
89 elif addr.family == socket.AF_PACKET:
90 print(f"MAC: {addr.address}")
获取 打印 磁盘信息
93 # ======================== 打印磁盘信息 ======================================
94 def display_disk():
95
96 disk = psutil.disk_partitions(all=False)
97
98 print("*" * 30,"磁盘信息","*" * 30)
99 for part in disk:
100 usage = psutil.disk_usage(part.mountpoint)
101
102 print("设备:{}\n总共:{}\n已使用:{}\n剩余:{}".format(
103 part.device,
104 bytes2human(usage.total),
105 bytes2human(usage.used),
106 bytes2human(usage.free)))
主逻辑函数
108 # ======================== 信息收集 ==========================================
109 mem_dic = {
110 '1':{'tital':"CPU信息", 'func': display_cpu },
111 '2':{'tital':"内存信息", 'func': display_mem },
112 '3':{'tital':"网卡信息", 'func':display_net },
113 '4':{'tital':"磁盘信息", 'func':display_disk }
114 }
115
116 def display_M():
117 for k, item in mem_dic.items():
118 print(k, item['tital'])
119 # =================================================================
120 display_M()
121 while True:
122 inp = input(">>>>>>>>>请输入序号(q-退出)>>>>>>>>>>>:")
123 if inp == 'q':
124 sys.exit("退出程序")
125 mem = mem_dic.get(inp,"None")
126 if inp in ('1','2','3','4'):
127 if mem:
128 func = mem['func']
129 display_M()
130 func()
131 else:
132 print("请输入正确的序号")
------------效果展示------------------
image.png
image.png