方法一:
import psutil
python
import psutil
battery = psutil.sensors_battery()
if battery is None:
print("No battery is found.")
exit()
print (battery)
percentage=battery.percent
print(f"Battery Percentage: {percentage}%")
Battery的信息中包含电池的电量,剩余时间,和当前状态。
方法二:
import wmi
python
def Power():
c = wmi.WMI()
t = wmi.WMI(moniker="//./root/wmi")
batts2 = t.ExecQuery('Select * from BatteryStatus where Voltage > 0')
for i, b in enumerate(batts2):
# print ('PowerOnline: ' + str(b.PowerOnline))
z = str(b.PowerOnline)
if z=='True':
print(r'Now PC in AC')
else:
print(r'Now PC in DC')
return z
Power()返回值是True是AC状态,False是DC状态。