@@ -61,55 +61,62 @@ def fmt_timedelta(td: timedelta) -> str:
61
61
:param td: 时间差对象
62
62
:return:
63
63
"""
64
- total_seconds = round (td .total_seconds ())
65
- return ServerInfo .fmt_seconds (total_seconds )
64
+ return ServerInfo .fmt_seconds (round (td .total_seconds ()))
66
65
67
66
@staticmethod
68
67
def get_cpu_info () -> dict [str , float | int ]:
69
68
"""获取 CPU 信息"""
70
- cpu_info = {'usage' : round (psutil .cpu_percent (percpu = False ), 2 )} # %
69
+ cpu_info = {
70
+ 'usage' : round (psutil .cpu_percent (interval = 0.1 ), 2 ), # %
71
+ 'logical_num' : psutil .cpu_count (logical = True ) or 0 ,
72
+ 'physical_num' : psutil .cpu_count (logical = False ) or 0 ,
73
+ 'max_freq' : 0.0 ,
74
+ 'min_freq' : 0.0 ,
75
+ 'current_freq' : 0.0 ,
76
+ }
71
77
72
78
try :
73
- # CPU 频率信息,最大、最小和当前频率
74
- cpu_freq = psutil .cpu_freq ()
75
- cpu_info .update ({
76
- 'max_freq' : round (cpu_freq .max , 2 ), # MHz
77
- 'min_freq' : round (cpu_freq .min , 2 ), # MHz
78
- 'current_freq' : round (cpu_freq .current , 2 ), # MHz
79
- })
79
+ if hasattr (psutil , 'cpu_freq' ):
80
+ cpu_freq = psutil .cpu_freq ()
81
+ if cpu_freq : # Some systems return None
82
+ cpu_info .update ({
83
+ 'max_freq' : round (cpu_freq .max , 2 ),
84
+ 'min_freq' : round (cpu_freq .min , 2 ),
85
+ 'current_freq' : round (cpu_freq .current , 2 ),
86
+ })
80
87
except Exception :
81
- cpu_info . update ({ 'max_freq' : 0 , 'min_freq' : 0 , 'current_freq' : 0 })
88
+ pass
82
89
83
- # CPU 逻辑核心数,物理核心数
84
- cpu_info .update ({
85
- 'logical_num' : psutil .cpu_count (logical = True ),
86
- 'physical_num' : psutil .cpu_count (logical = False ),
87
- })
88
90
return cpu_info
89
91
90
92
@staticmethod
91
93
def get_mem_info () -> dict [str , float ]:
92
94
"""获取内存信息"""
93
95
mem = psutil .virtual_memory ()
96
+ gb_factor = 1024 ** 3
94
97
return {
95
- 'total' : round (mem .total / 1024 / 1024 / 1024 , 2 ), # GB
96
- 'used' : round (mem .used / 1024 / 1024 / 1024 , 2 ), # GB
97
- 'free' : round (mem .available / 1024 / 1024 / 1024 , 2 ), # GB
98
- 'usage' : round (mem .percent , 2 ), # %
98
+ 'total' : round (mem .total / gb_factor , 2 ),
99
+ 'used' : round (mem .used / gb_factor , 2 ),
100
+ 'free' : round (mem .available / gb_factor , 2 ),
101
+ 'usage' : round (mem .percent , 2 ),
99
102
}
100
103
101
104
@staticmethod
102
105
def get_sys_info () -> dict [str , str ]:
103
106
"""获取服务器信息"""
107
+ hostname = socket .gethostname ()
108
+ ip = '127.0.0.1'
109
+
104
110
try :
105
- with socket .socket (socket .AF_INET , socket .SOCK_DGRAM ) as sk :
106
- sk .connect (('8.8.8.8' , 80 ))
107
- ip = sk .getsockname ()[0 ]
108
- except socket .gaierror :
109
- ip = '127.0.0.1'
111
+ with socket .socket (socket .AF_INET , socket .SOCK_DGRAM ) as s :
112
+ s .settimeout (0.5 )
113
+ s .connect (('8.8.8.8' , 80 ))
114
+ ip = s .getsockname ()[0 ]
115
+ except (socket .gaierror , socket .timeout , OSError ):
116
+ pass
110
117
111
118
return {
112
- 'name' : socket . gethostname () ,
119
+ 'name' : hostname ,
113
120
'ip' : ip ,
114
121
'os' : platform .system (),
115
122
'arch' : platform .machine (),
@@ -119,36 +126,46 @@ def get_sys_info() -> dict[str, str]:
119
126
def get_disk_info () -> list [dict [str , str ]]:
120
127
"""获取磁盘信息"""
121
128
disk_info = []
122
- for disk in psutil .disk_partitions ():
123
- usage = psutil .disk_usage (disk .mountpoint )
124
- disk_info .append ({
125
- 'dir' : disk .mountpoint ,
126
- 'type' : disk .fstype ,
127
- 'device' : disk .device ,
128
- 'total' : ServerInfo .format_bytes (usage .total ),
129
- 'free' : ServerInfo .format_bytes (usage .free ),
130
- 'used' : ServerInfo .format_bytes (usage .used ),
131
- 'usage' : f'{ round (usage .percent , 2 )} %' ,
132
- })
129
+ for partition in psutil .disk_partitions (all = False ):
130
+ try :
131
+ usage = psutil .disk_usage (partition .mountpoint )
132
+ disk_info .append ({
133
+ 'dir' : partition .mountpoint ,
134
+ 'type' : partition .fstype ,
135
+ 'device' : partition .device ,
136
+ 'total' : ServerInfo .format_bytes (usage .total ),
137
+ 'free' : ServerInfo .format_bytes (usage .free ),
138
+ 'used' : ServerInfo .format_bytes (usage .used ),
139
+ 'usage' : f'{ usage .percent :.2f} %' ,
140
+ })
141
+ except (PermissionError , psutil .AccessDenied ):
142
+ continue
133
143
return disk_info
134
144
135
145
@staticmethod
136
146
def get_service_info () -> dict [str , str | datetime ]:
137
147
"""获取服务信息"""
138
148
process = psutil .Process (os .getpid ())
139
149
mem_info = process .memory_info ()
140
- start_time = timezone .f_datetime (datetime .utcfromtimestamp (process .create_time ()).replace (tzinfo = tz .utc ))
150
+
151
+ try :
152
+ create_time = datetime .fromtimestamp (process .create_time (), tz = tz .utc )
153
+ start_time = timezone .f_datetime (create_time )
154
+ except (psutil .NoSuchProcess , OSError ):
155
+ start_time = timezone .now ()
156
+
157
+ elapsed = ServerInfo .fmt_timedelta (timezone .now () - start_time )
141
158
142
159
return {
143
160
'name' : 'Python3' ,
144
161
'version' : platform .python_version (),
145
162
'home' : sys .executable ,
146
- 'cpu_usage' : f'{ round ( process .cpu_percent (interval = 1 ), 2 ) } %' ,
147
- 'mem_vms' : ServerInfo .format_bytes (mem_info .vms ), # 虚拟内存, 即当前进程申请的虚拟内存
148
- 'mem_rss' : ServerInfo .format_bytes (mem_info .rss ), # 常驻内存, 即当前进程实际使用的物理内存
149
- 'mem_free' : ServerInfo .format_bytes (mem_info .vms - mem_info .rss ), # 空闲内存
163
+ 'cpu_usage' : f'{ process .cpu_percent (interval = 0.1 ):.2f } %' ,
164
+ 'mem_vms' : ServerInfo .format_bytes (mem_info .vms ),
165
+ 'mem_rss' : ServerInfo .format_bytes (mem_info .rss ),
166
+ 'mem_free' : ServerInfo .format_bytes (mem_info .vms - mem_info .rss ),
150
167
'startup' : start_time ,
151
- 'elapsed' : ServerInfo . fmt_timedelta ( timezone . now () - start_time ) ,
168
+ 'elapsed' : elapsed ,
152
169
}
153
170
154
171
0 commit comments