We are trying to count the instances in glassfish. When using the len() function this always returns 1 instead of 0. Maybe it fills the list[0] with an empty space or something. This is our code.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.get('hostname'),int(self.get('port')),self.get('username'),allow_agent=True)
#try:
stdin, stdout, stderr = ssh.exec_command('~/glassfish3/glassfish/bin/asadmin list-instances')
result = stdout.readlines()
#except Exception, e:
# return MonitoringResult(MonitoringResult.OK,'all instances up!')
result = "".join(result)
#line = re.compile(r'\bnot\s\D*\n')
#rline = "".join(line.findall((result)))
line2=re.compile(r'\bnot')
rline2 = ";".join(line2.findall((result)))
print(rline2)
i = 0
listr = rline2.split(";")
while(i < (len(listr)):
i+=1
print(i)
if rline2:
return MonitoringResult(MonitoringResult.CRITICAL,'instance down')
else:
return MonitoringResult(MonitoringResult.OK, 'All instances are up')
The result of str.split
cannot be an empty list
:
>>> ''.split(';')
['']
If you want to check whether the list obtained contains any
non-empty string, use any
:
>>> any(''.split(';'))
False
>>> any('a;'.split(';'))
True
>>> ';'.split(';')
['', '']
>>> any(';'.split(';'))
False
If you want to filter
out the empty strings, use filter
:
>>> filter(None, ';'.split(';'))
[]
Or a list-comprehension:
>>> [s for s in ';'.split(';') if s]
[]
I just realized that str.split
can return an empty list. But only when called without an argument:
>>> ''.split()
[]
>>> ' '.split() #white space string
[]
The explanation is in the documentation:
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string
S
, usingsep
as the delimiter string. Ifmaxsplit
is given, at mostmaxsplit
splits are done. Ifsep
is not specified or isNone
, any whitespace string is a separator and empty strings are removed from the result.