Python将变量输出到具有指定字符串的另一个变量
变量1具有:Python将变量输出到具有指定字符串的另一个变量,python,python-2.7,Python,Python 2.7,变量1具有: 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输出是从命令输出中获取的,因为variable1是字符串数据类型 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输出是从命令输出中获取的,因为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"
您可以将每一行拆分为:,并将键、值放入字典。 与其提取所需的变量,不如将所有值存储在字典中。您将能够通过键访问任何值
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'}
假设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
variable1
是字典吗?类实例?还有别的吗?您有一些代码演示如何创建variable1
吗?variable1不是字典。variable1输出来自命令output,您一定会设法将该字符串拆分成行,然后在冒号处拆分每一行:并找到以“CPU状态”开头的行?是的,我需要,CPU状态:CriticalGetting AttributeError:“非类型”对象没有属性“组”您能打印类型(变量1)吗?如果它不是字符串,它将无法工作