How can I use python's telnetlib to fetch data

2019-04-12 22:44发布

问题:

I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number.

So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)?

I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop.

(I'm running python 2.5 under Cygwin, btw).

Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?

回答1:

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.



回答2:

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


回答3:

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.



回答4:

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?



标签: python telnet