在 Python 中,如何检测计算机是否使用电池供电? [英] In Python, how can I detect whether the computer is on battery power?

查看:107
本文介绍了在 Python 中,如何检测计算机是否使用电池供电?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩 pygame,我想做的一件事是在计算机使用电池供电时减少每秒帧数(以降低 CPU 使用率并延长电池寿命).

I'm playing around with pygame, and one thing I'd like to do is reduce the number of frames per second when the computer is on battery power (to lower the CPU usage and extend battery life).

如何从 Python 中检测计算机当前是否使用电池供电?

How can I detect, from Python, whether the computer is currently on battery power?

我在 Windows 上使用 Python 3.1.

I'm using Python 3.1 on Windows.

推荐答案

如果你想不用 win32api 来做,你可以使用内置的 ctypes 模块.我通常在没有 win32api 的情况下运行 CPython,所以我有点喜欢这些解决方案.

If you want to do it without win32api, you can use the built-in ctypes module. I usually run CPython without win32api, so I kinda like these solutions.

GetSystemPowerStatus() 的工作稍微多一些,因为您必须定义 SYSTEM_POWER_STATUS 结构,但还不错.

It's a tiny bit more work for GetSystemPowerStatus() because you have to define the SYSTEM_POWER_STATUS structure, but not bad.

# 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)

在我打印此内容的系统上(基本上意思是桌面,已插入"):

On my system that prints this (basically meaning "desktop, plugged in"):

ACLineStatus 1
BatteryFlag -128
BatteryLifePercent -1
BatteryLifeTime 4294967295
BatteryFullLifeTime 4294967295

这篇关于在 Python 中,如何检测计算机是否使用电池供电?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆