I am trying to iterate a list with for loop and build a second list through regex capture group. I looked through documentation related to the re module but for some reason, the regex always return one result. The regex was tested so I am certain that is works.
Any thoughts?
Edited
#! /usr/bin/python
import re
import subprocess
try:
cmd = "ps aux|grep -i \'zabbi[x]\'"
cmd_stdout = subprocess.check_output(cmd, shell=True).split('\n')
cmd_stdout_lst = []
ps_re = re.compile(r'^(\S+)\s+(\d+)\s+\d+\.\d+\s+\d+\.\d+\s+(\d+)\s+(\d+).+')
for line in cmd_stdout:
match = ps_re.findall(line)
if match:
print match
cmd_stdout_lst.append('\n\t\t{"{#USER}":'+'"' + match[0][0] + ',"{#PID}":'+'"'+match[0][1]+'"}'+',"{#PID}":'+'"'+match [0][2]+'"}'+',"{#PID}":'+'"'+match[0][3]+'"}')
print '{\n\t"data":['+','.join(cmd_stdout_lst)+']\n}'
except:
raise
$ python proc_discovery.py
[('zabbix', '14479', '96784', '680')]
{"data":[{"{#USER}":"zabbix"},{"{#PID}":"14479"},{"{#VSZ}":"96784"},{"{#RSS}":"680"}]}except: exit(1)toexcept: raise(or just remove it entirely) so you aren't hiding the exception you're getting. That is your problem. You're probably getting list index out of range exceptions.$ python proc_discovery.py [('zabbix', '14479', '96784', '680')] Traceback (most recent call last): File "proc_discovery.py", line 15, in <module> print match[2] IndexError: list index out of rangeexcept:is almost never a good idea.