如何在 Python 中将命令行跳过到变量中

How to skip lines of command into variable in Python

我想使用命令:

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]

等等

然后我继续 "parse" 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'
]

您可以尝试使用正则表达式。

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 部分和类型部分分组(使用括号)。结果是一个元组列表。每个元组都是一个模式匹配。