Python使用指定的字符串获取变量输出到另一个变量

时间:2017-09-07 06:17:55

标签: python python-2.7

variable1有:

 Server: Server1
 Power State: Faulty
 Power load: 120
 CPU State: Critical
 CPU Usage: 97%
 Mem State: Normal
 Mem Usage: 10%

我想要variable2 = Critical
这是cpu状态输出和cpu状态旁边的任何值。

我不想打印到文件并grep它。

variable1输出来自命令输出

3 个答案:

答案 0 :(得分:0)

考虑variable1是字符串数据类型

variable1 = " Server: Server1\n\
 Power State: Faulty\n\
 Power load: 120\n\
 CPU State: Critical\n\
 CPU Usage: 97%\n\
 Mem State: Normal\n\
 Mem Usage: 10%"
print variable1

match = re.search("CPU State:(.+)",variable1)
if(match):
        variable2 = match.group(1).strip()
        print variable2
else:   
        print "match not find"

答案 1 :(得分:0)

您可以按拆分每一行,并将键值放入字典中。 而不是仅仅提取您需要的变量,为什么不将所有值存储在字典中。您将能够通过密钥访问任何值。

def extract_values(string):
    string = string.strip()
    data = {}
    lines = string.split("\n")
    for line in lines:
        line = line.strip()
        key, value = line.split(":")
        data[key.strip()] = value.strip()
    return data

string = """
    Server: Server1
    Power State: Faulty
    Power load: 120
    CPU State: Critical
    CPU Usage: 97%
    Mem State: Normal
    Mem Usage: 10%
"""

data = extract_values(string)
print(data)
variable2 = data['CPU State']

数据将是:

>>> data
{'Power load': '120', 'Power State': 'Faulty', 'CPU Usage': '97%', 'Mem State': 'Normal', 'CPU State': 'Critical', 'Mem Usage': '10%', 'Server': 'Server1'}

答案 2 :(得分:0)

假设variable1是一个字符串,最基本和非动态的方法是

lines = variable1.splitlines()  # returns a list containing lines of variable1
for line in lines:
    if "CPU State" in line:
        # split the string by : and get the second item in list
        # and strip it to avoid any unwanted spaces before or after it
        variable2 = line.split(":")[1].strip()
print variable2

,输出将是

Critical