We can use the shell command pmset
to get the power management settings of a Mac computer.
For example to find the battery percentage:
pmset -g batt | grep -Eo "\d+%" | cut -d% -f1
Gives battery percentage of the laptop.
When I ran the same command in python using os.system
command it runs fine and prints the battery percentage. The problem is we can not get the output from the terminal.
# This runs fine
os.system('pmset -g batt | grep -Eo "\d+%" | cut -d% -f1')
When I use subprocess.check_output
it fails for the same command:
# This fails
subprocess.check_output('pmset -g batt | grep -Eo "\d+%" | cut -d% -f1')
Here is my attempt:
#!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"))
Error log
FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/pmset -g batt': '/usr/bin/pmset -g batt'
Question How to make this line working?
subprocess.check_output('pmset -g batt | grep -Eo "\d+%" | cut -d% -f1')