2

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')
  • From your bash terminal, run `which pmset`, this will output the full qualified path to the binary. Then use this path in the python script. Something like `/path/to/pmset -g batt...` – Matt Clark Jun 07 '18 at 22:01
  • 2
    Or you can use the [power](https://github.com/Kentzo/Power) package which is advertised as being cross-platform. – Matt Clark Jun 07 '18 at 22:02
  • `subprocess.check_output('/usr/bin/pmset -g batt')` also gives error. I am using python 2.7.14. –  Jun 07 '18 at 22:09
  • `FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/pmset -g batt': '/usr/bin/pmset -g batt'` –  Jun 07 '18 at 22:10
  • 2
    maybe this will help: https://stackoverflow.com/questions/13332268/python-subprocess-command-with-pipe – JeffCharter Jun 07 '18 at 22:11

1 Answers1

0

I found a way using shell=True method, which is not a great due to security reasons.

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