Python Telnetlib read_until '#' or '>', multiple string determination?

瘦欲@ 提交于 2019-12-13 13:45:16

问题


if (tn.read_until('>')):
    action1
else:
    action2

or

if (tn.read_until() == '>'):
    action1
else:
    action2

I just want the read_until() to check which desired String comes first, and do different actions. Or is there any equivalent ways?


回答1:


Look at the docs. Read until wants the expected string as a positional argument and an optional timeout. I would do it like this:

>>> try:
...     response = tn.read_until(">", timeout=120) #or whatever timeout you choose.
... except EOFError as e:
...     print "Connection closed: %s" % e

>>> if ">" in response:
...    action1
... else:
...    action2

If you want multiple different characters you can use read_some()

>>> while True: #really you should set some sort of a timeout here.
...    r = tn.read_some()
...    if any(x in r for x in ["#", ">"]):
...        break



回答2:


Better yet just use:

buff_tpl = tn.expect(["#", ">"])

This will return a tuple with three items, the first (index of 0) is the index of the list item matched, the second is and object matched, and the third is the output text.

You can print the buffer output using buff_tpl[2], and know which item matched using buff_tpl[0]



来源:https://stackoverflow.com/questions/22074909/python-telnetlib-read-until-or-multiple-string-determination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!