【问题标题】:How to get battery percentage of MacOS laptop using python script?如何使用 python 脚本获取 MacOS 笔记本电脑的电池百分比?
【发布时间】:2018-11-17 22:17:39
【问题描述】:

我们可以使用shell命令pmset来获取Mac电脑的电源管理设置。

例如查找电池百分比:

pmset -g batt | grep -Eo "\d+%" | cut -d% -f1

给出笔记本电脑的电池百分比。

当我在 python 中使用os.system 命令运行相同的命令时,它运行良好并打印电池百分比。问题是我们无法从终端获取输出。

# This runs fine
os.system('pmset -g batt | grep -Eo "\d+%" | cut -d% -f1')

当我使用 subprocess.check_output 时,相同的命令会失败:

# This fails
subprocess.check_output('pmset -g batt | grep -Eo "\d+%" | cut -d% -f1')

这是我的尝试:

#!python
import subprocess
import os

# This runs fine.
cmd = "date"
returned_output = subprocess.check_output(cmd).decode("utf-8")
# print('Current date is:', returned_output)

# This runs fine.
cmd = 'pmset -g batt | grep -Eo "\d+%" | cut -d% -f1'
os.system(cmd)

# This fails
cmd = 'pmset -g batt | grep -Eo "\d+%" | cut -d% -f1'
returned_output = subprocess.check_output(cmd)
print('Battery percentage:', returned_output.decode("utf-8"))

错误日志

FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/pmset -g batt': '/usr/bin/pmset -g batt'

问题如何使这条线工作?

subprocess.check_output('pmset -g batt | grep -Eo "\d+%" | cut -d% -f1')

【问题讨论】:

  • 从您的 bash 终端运行 which pmset,这将输出二进制文件的完整路径。然后在 python 脚本中使用这个路径。类似/path/to/pmset -g batt...
  • 或者您可以使用标榜为跨平台的power 包。
  • subprocess.check_output('/usr/bin/pmset -g batt') 也会出错。我正在使用 python 2.7.14。
  • FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/pmset -g batt': '/usr/bin/pmset -g batt'
  • 也许这会有所帮助:stackoverflow.com/questions/13332268/…

标签: python subprocess


【解决方案1】:

我找到了一种使用shell=True方法的方法,由于安全原因,这不是很好。

#!python
import subprocess


cmd = 'pmset -g batt | grep -Eo "\d+%" | cut -d% -f1'
ps = subprocess.Popen(
    cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多