我想使用命令:
subprocess.check_output(["powercfg", "-list"])
这给了我:
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) *
这很好。但是,我只希望中间的变量进入它们自己的变量,而不需要所有额外的文本。问题是这个命令有多行,所以我不能使用(list[19:55])
。我还需要将括号内的每个字符串放入它们自己的变量中,但我想我可以解决这个问题。我是Python的新手,所以我对任何东西都持开放态度。
找到了答案,尽管我的标题措辞很糟糕,但我希望有人能找到这个,因为想弄清楚它真是太麻烦了。你所要做的就是更改末尾的数字以下行:
firstplan = subprocess.check_output(["powercfg", "-list"], shell=True ).split('n')[3]
secondplan = subprocess.check_output(["powercfg", "-list"], shell=True ).split('n')[4]
等等。
然后,我用这个词"解析"出ID字符串(如果这个词正确的话(:
firstplanID = ((firstplan.split(": "))[1].split(" (")[0])
然后手动为每个计划设置一个变量。
你可以试试这个:
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')]
结果:
>>> values
[
'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
]
您可以尝试使用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')]
给定一个字符串和一个模式,您可以找到字符串中与您的模式匹配的所有部分。在这种情况下,我创建了一个模式,并对id部分和type部分进行分组(使用paransition(。结果是一个元组列表。每个元组都是一个模式匹配。