python获取电脑状态
注意
素材说明: python获取电脑状态目前只在windows下验证过
注意
在windows下建议使用vscode运行,如果无法通讯时,建议使用管理员权限打开vscode再运行,由于pycharm需要配置虚拟环境,不建议在pycharm下运行,可能会导致无法通讯。
此例程属于python代码,仅提供参考,淘晶驰不提供python代码的技术支持。
python获取电脑状态代码
import time
import psutil
import serial
time.sleep(3)
# function of Get CPU State;
def getCPUstate(interval=1):
return (" CPU: " + str(psutil.cpu_percent(interval)) + "%")
# function of Get Memory
def getMemorystate():
phymem = psutil.virtual_memory()
line = "Memory: %5s%% %6s/%s" % (
phymem.percent,
str(int(phymem.used / 1024 / 1024)) + "M",
str(int(phymem.total / 1024 / 1024)) + "M"
)
return line
def bytes2human(n):
"""
>>> bytes2human(10000)
'9.8 K'
>>> bytes2human(100001221)
'95.4 M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s' % (value, s)
return '%.2f B' % (n)
def poll(interval):
"""Retrieve raw stats within an interval window."""
tot_before = psutil.net_io_counters()
pnic_before = psutil.net_io_counters(pernic=True)
# sleep some time
time.sleep(interval)
tot_after = psutil.net_io_counters()
pnic_after = psutil.net_io_counters(pernic=True)
# get cpu state
cpu_state = getCPUstate(interval)
# get memory
memory_state = getMemorystate()
return (tot_before, tot_after, pnic_before, pnic_after, cpu_state, memory_state)
def refresh_window(tot_before, tot_after, pnic_before, pnic_after, cpu_state, memory_state):
str = "t0.txt=\"" + time.asctime() + " | " + cpu_state + " | " + memory_state + "\""
serial.write(str.encode("GB2312"))
serial.write(bytes.fromhex('ff ff ff'))
nic_names = pnic_after.keys()
# nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
for name in nic_names:
# 有线一般是以太网,无线则是WLAN,具体请查看"控制面板\网络和 Internet\网络连接"
if name == "以太网":
stats_before = pnic_before[name]
stats_after = pnic_after[name]
templ = "%-15s %15s %15s"
str = "t1.txt=\"上传数据总量" + bytes2human(stats_after.bytes_sent) + " 上传速度:" + bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + '/s\"'
serial.write(str.encode("GB2312"))
serial.write(bytes.fromhex('ff ff ff'))
str = "t2.txt=\"下载数据总量" + bytes2human(stats_after.bytes_recv) + " 下载速度:" + bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + '/s\"'
serial.write(str.encode("GB2312"))
serial.write(bytes.fromhex('ff ff ff'))
try:
interval = 0
portx = "COM9"
bauds = 115200
timex = 5
serial = serial.Serial(port=portx,baudrate=bauds,timeout=timex)
while 1:
args = poll(interval)
refresh_window(*args)
interval = 1
except (KeyboardInterrupt, SystemExit):
pass