How to skip lines of command into variable in Python

378 Views Asked by At

I want to use the command:

subprocess.check_output(["powercfg", "-list"])

which gives me:

Existing Power Schemes (* Active)

-----------------------------------

Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (Balanced)

Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (High performance)

Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (Power saver) *

which is good. But, I only want the variables in the middle to go into their own variables without all the extra text. The problem is that the command comes out in multiple lines so I can't use (list[19:55]). I also need to do this with each of the strings inside the parentheses into their own variables but I think I can figure that out. I'm new to Python so I'm open to whatever.

3

There are 3 best solutions below

0
On BEST ANSWER

Found the answer, even though my title is poorly worded I hope someone finds this because it was hell trying to figure it out. All you have to do is change the number at the end to go down lines:

firstplan = subprocess.check_output(["powercfg", "-list"], shell=True ).split('\n')[3]

secondplan = subprocess.check_output(["powercfg", "-list"], shell=True ).split('\n')[4]

etc.

I then went on to "parse" the ID strings out (if that's the right word) with this:

firstplanID = ((firstplan.split(": "))[1].split(" (")[0])

and then manually set a variable for each plan.

0
On

you may try this:

data = '''Existing Power Schemes (* Active)

-----------------------------------

Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (Balanced)

Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (High performance)

Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (Power saver) *'''

values = [i.split()[3] for i in data.splitlines() if i.startswith('Power')]

the results:

>>> values
[
    'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
]
0
On

You can try using regex.

import re

pattern = "Power Scheme GUID: ([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})\s+\(([a-zA-Z ]+)\)"
mystr = "Existing Power Schemes (* Active)\n-----------------------------------\nPower Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (Balanced)\nPower Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (High performance)\nPower Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx  (Power saver) *"

re.findall(pattern, mystr)
# results: [('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Balanced'), ('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'High performance'), ('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Power saver')]

Given a string and a pattern, you can find all the parts of the string that match your pattern. In this case, I created a pattern, and grouped (using paranthesis) the id part and the type part. The result is a list of tuples. Each tuple is a pattern match.