python中的len(list)返回1而不是0

2024-09-26 22:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我们正在尝试计算glassfish中的实例。当使用len()函数时,它总是返回1而不是0。也许它会在列表[0]中填充一个空白或其他内容。这是我们的代码。在

    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')

Tags: instancesselfparamikogetlenreturnstdoutok
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:28

str.split的结果不能是空的list

>>> ''.split(';')
['']

如果要检查获得的列表是否包含any非空字符串,请使用any

^{pr2}$

如果要filter出空字符串,请使用filter

>>> filter(None, ';'.split(';'))
[]

或列表理解:

>>> [s for s in ';'.split(';') if s]
[]

我刚刚意识到str.split可以返回一个空列表。但是只有在没有参数的情况下调用时:

>>> ''.split()
[]
>>> '    '.split()   #white space string
[]

文档中有解释:

S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

相关问题 更多 >

    热门问题