Joe*_*ite 17 python windows pygame
我正在玩pygame,我想做的一件事就是当计算机使用电池供电时减少每秒的帧数(降低CPU使用率并延长电池寿命).
如何从Python中检测到计算机当前是否使用电池供电?
我在Windows上使用Python 3.1.
Ben*_*oyt 14
如果您不想这样做win32api
,可以使用内置ctypes
模块.我通常没有运行CPython win32api
,所以我有点喜欢这些解决方案.
这是一个更小的工作GetSystemPowerStatus()
因为你必须定义SYSTEM_POWER_STATUS
结构,但并不坏.
# Get power status of the system using ctypes to call GetSystemPowerStatus
import ctypes
from ctypes import wintypes
class SYSTEM_POWER_STATUS(ctypes.Structure):
_fields_ = [
('ACLineStatus', wintypes.BYTE),
('BatteryFlag', wintypes.BYTE),
('BatteryLifePercent', wintypes.BYTE),
('Reserved1', wintypes.BYTE),
('BatteryLifeTime', wintypes.DWORD),
('BatteryFullLifeTime', wintypes.DWORD),
]
SYSTEM_POWER_STATUS_P = ctypes.POINTER(SYSTEM_POWER_STATUS)
GetSystemPowerStatus = ctypes.windll.kernel32.GetSystemPowerStatus
GetSystemPowerStatus.argtypes = [SYSTEM_POWER_STATUS_P]
GetSystemPowerStatus.restype = wintypes.BOOL
status = SYSTEM_POWER_STATUS()
if not GetSystemPowerStatus(ctypes.pointer(status)):
raise ctypes.WinError()
print 'ACLineStatus', status.ACLineStatus
print 'BatteryFlag', status.BatteryFlag
print 'BatteryLifePercent', status.BatteryLifePercent
print 'BatteryLifeTime', status.BatteryLifeTime
print 'BatteryFullLifeTime', status.BatteryFullLifeTime
Run Code Online (Sandbox Code Playgroud)
在我打印它的系统上(基本上意思是"桌面,插入"):
ACLineStatus 1
BatteryFlag -128
BatteryLifePercent -1
BatteryLifeTime 4294967295
BatteryFullLifeTime 4294967295
Run Code Online (Sandbox Code Playgroud)
在 C 中检索此信息的最可靠方法是使用GetSystemPowerStatus。如果没有电池,ACLineStatus
将设置为128
。psutil在 Linux、Windows 和 FreeBSD 下公开此信息,因此要检查电池是否存在,您可以执行此操作
>>> import psutil
>>> has_battery = psutil.sensors_battery() is not None
Run Code Online (Sandbox Code Playgroud)
如果有电池并且您想知道电源线是否已插入,您可以执行以下操作:
>>> import psutil
>>> psutil.sensors_battery()
sbattery(percent=99, secsleft=20308, power_plugged=True)
>>> psutil.sensors_battery().power_plugged
True
>>>
Run Code Online (Sandbox Code Playgroud)