从这个剧本
items = items[0].split()
for emailid in items:
resp, data = conn.uid("fetch",emailid, "(RFC822)")
if resp == 'OK':
email_body = data[0][1].decode('utf-8')
mail = email.message_from_string(email_body)
#print email_body
if mail["Subject"].find("PA1") > 0 or mail["Subject"].find("PA2") > 0:
regex1 = r'(?<!^)JOB:\s*(\S+)'
#regex2 = r'Job finished'
#c=re.findall(regex2, email_body, re.IGNORECASE)
a=re.findall(regex1 ,email_body) #re.IGNORECASE)
if a:
b=set(a)
seen = set()
result = []
for item in a:
if item not in seen:
seen.add(item)
result.append(item)
output = " ".join(result)我得到了:
example_job_1
example_job_2
example_job_3
example_job_4
我希望从上面的输出中创建如下格式的JSON输出。从这个输出中,我尝试创建Zabbix外部脚本
期望输出
{
"data": [
{
"{#job}": "example_job_1"
},
{
"{#job}": "example_job_2"
},
{
"{#job}": "example_job_3"
},
{
"{#job}": "example_job_3"
},
{
"{#job}": "example_job_4"
}
]
} 我修改了上面的脚本:
items = items[0].split()
for emailid in items:
resp, data = conn.uid("fetch",emailid, "(RFC822)")
if resp == 'OK':
email_body = data[0][1].decode('utf-8')
mail = email.message_from_string(email_body)
#print email_body
if mail["Subject"].find("PA1") > 0 or mail["Subject"].find("PA2") > 0:
regex1 = r'(?<!^)JOB:\s*(\S+)'
#regex2 = r'Job finished'
#c=re.findall(regex2, email_body, re.IGNORECASE)
a=re.findall(regex1 ,email_body) #re.IGNORECASE)
if a:
b=set(a)
seen = set()
result = []
for item in a:
if item not in seen:
seen.add(item)
result.append(item)
output = " ".join(result)
data = [{"{#job}": output}]
print json.dumps({"data": data}, indent=4)并得到的实际输出
{
"data": [
{
"{#job}": "example_job_1"
}
]
}
{
"data": [
{
"{#job}": "example_job_2"
}
]
}
{
"data": [
{
"{#job}": "example_job_3"
}
]
}
{
"data": [
{
"{#job}": "example_job_4"
}
]
}发布于 2018-12-28 12:19:03
解决:“忘记”在"for循环“之前初始化空列表,因此每次迭代时都会重置列表。
tdata=[]
items = items[0].split()
for emailid in items:
resp, data = conn.uid("fetch",emailid, "(RFC822)")
if resp == 'OK':
email_body = data[0][1].decode('utf-8')
mail = email.message_from_string(email_body)
if mail["Subject"].find("PA1") > 0 or mail["Subject"].find("PA2") > 0:
regex1 = r'(?<!^)JOB:\s*(\S+)'
#regex2 = r'Job finished'
#c=re.findall(regex2, email_body, re.IGNORECASE)
a=re.findall(regex1 ,email_body) #re.IGNORECASE)
if a:
b=set(a)
seen = set()
result = []
for item in a:
if item not in seen:
seen.add(item)
result.append(item)
output = " ".join(result)
tdata.append({'#job':output})
print json.dumps({"data": tdata}, indent=4)https://stackoverflow.com/questions/53956666
复制相似问题