【问题标题】:Last for iteration produce "None" output最后一次迭代产生“无”输出
【发布时间】:2019-03-13 12:45:48
【问题描述】:

我正在编写一个脚本来使用Pexpect 和正则表达式来测试输出开关和公共 IP 之间的延迟。

这是一个示例:

# Connect to a cisco system just before and going enable
for key in nodes:
    ipaddr_node = nodes[key]["IP Address"]
    print ('[|] Ping de %s en cours ...' % ipaddr_node)
    p.sendline("ping %s repeat 20" % ipaddr_node) #ping of the ip 20 times on cisco
    p.expect('#')
    ping = p.before #get the output before '#'
    print ('[+] Ping de %s reussi' % ipaddr_node)
    place = ping.find('min') #get the position of 'min' in output
    regex = ping.replace(ping[:place],"")
    output = re.search(r'\s=\s(?P<min>\d{1,4}.\d{0,3})\/(?P<avg>\d{1,4}.\d{0,3})\/(?P<max>\d{1,4}.\d{0,3})', regex) #regex to get min, avg and max
    print(output) #Print regex object
    avg = output.group('avg') #get value of group "avg" in regex
    print('[+] Average time : ' + avg) #print it

这是一个输出示例:

('min/avg/max = 33/44/51 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea11f8>, '<= Regex object')
[+] Temps moyen : 44
('min/avg/max = 41/46/59 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea1290>, '<= Regex object')
[+] Temps moyen : 46
('min/avg/max = 41/41/42 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea11f8>, '<= Regex object')
[+] Temps moyen : 41
('min/avg/max = 1/3/9 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(None, '<= Regex object')
Traceback (most recent call last):
  File "EssaiPexpect.py", line 95, in <module>
    avg = output.group('avg')
AttributeError: 'NoneType' object has no attribute 'group'

包含要测试的 IP 的字典包含 4 个 IP。

我的node 是一个包含 IP 和其他信息的字典,但这肯定有效。

我的regex 变量每次看起来都是这样(即使在最后一次迭代中):min/avg/max = 1/3/9 ms

我确信这是一件简单的事情,但我无法理解它。

【问题讨论】:

  • 输出似乎与代码不符。代码中的print消息不同。
  • 你打算用\d{1,4}.\d{0,3}这个模式表达什么?你能用你自己的话解释一下这是什么意思吗?
  • 这是一个简单的正则表达式,可以从 ping 命令中获取输出时间。
  • 是的,打印代码不同,但这只是显示,代码保持不变

标签: python pexpect


【解决方案1】:

找到解决方案!

这是我的正则表达式搜索中的一个简单错误。 这是旧的:Output of Regex101 of old regex

这是新的:Ouput of Regex 101 of new regex

为了简化,我的第一个请求找不到最后一行,因为我的 . 没有正确转义。 我只是在两种可能性之间添加了一个很好的转义和or

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多