您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中,如何检测计算机是否由电池供电?

在Python中,如何检测计算机是否由电池供电?

如果您不希望这样做,则win32api可以使用内置ctypes模块。我通常在不使用cpython的情况下运行cpythonwin32api,因此我很喜欢这些解决方案。

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

在打印此内容的系统上(基本上是指“台式机,已插入”):

ACLineStatus 1
BatteryFlag -128
BatteryLifePercent -1
BatteryLifeTime 4294967295
BatteryFullLifeTime 4294967295
python 2022/1/1 18:43:40 有321人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶