【发布时间】: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'
标签: python subprocess