How can I use python's telnetlib to fetch data from a device for a fixed period of time?

时间秒杀一切 提交于 2019-12-04 16:42:59

From your description I'm not clear if you're using telnetlib because the device you're connecting to requires terminal setup provided by telnet or because it seemed like the right thing to do.

If the device is as simple as you describe--i.e. not negotiating terminal options on connection--have you considered the asynchat module? It would be appropriate for the "send command, read lines" sort of IO pattern you are describing.

Alternatively, for something lower-level, you could use the socket module to open the connection to the device and then sit in a timed loop and read() the incoming data. If the lines are newline-terminated it should be simple for you to identify each individual number. If you are concerned with blocking, stick this loop in its own thread.

It sounds like blocking isn't really your problem, since you know that you'll only be blocking for a second. Why not do something like:

lines_to_read = 10
for i in range(lines_to_read):
    line = tel.read_until("\n")

In my experience, most such devices use some prompt, in which case Telnet.read_until() is appropriate:

Telnet.read_until(expected[, timeout])

Read until a given string, expected, is encountered or until timeout seconds have passed. When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available.

If no usable (repetitive) prompt is presented by the device, try Telnet.read_very_eager(), or Telnet.read_very_lazy():

Telnet.read_very_eager()

Read everything that can be without blocking in I/O (eager).

Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.

Read lines in a loop until you have either read the required number of lines or the time limit has been reached. However, it doesn't sound like you actual need a telnet library. Why not just use a simple TCP socket for the connection?

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