2

我正在通过 telnet 连接到硬件设备。该设备在 I/O 方面非常简单。所以我向它提交了一个命令,然后设备一次输出一条数据,每秒一次。每行只包含一个数字。

所以我的问题是:如果我使用 python 的 telnetlib 连接到这个设备,我如何在固定的时间段(或固定数量的数据行)内获取数据?

我已经尝试使用所有各种 read_ 命令,但它们似乎都无限期地阻塞,除了 read_until,我不能使用它,因为输出不能用于确定何时停止。

(我在 Cygwin 下运行 python 2.5,顺便说一句)。

编辑:也许真正的问题是,我应该为此使用 telnetlib,还是应该只使用 socket 模块?

4

4 回答 4

5

根据您的描述,我不清楚您是否正在使用 telnetlib,因为您要连接的设备需要 telnet 提供的终端设置,或者因为这似乎是正确的做法。

如果设备像您描述的那样简单——即不协商连接的终端选项——您是否考虑过asynchat模块?它适用于您描述的“发送命令,读取行”类型的 IO 模式。

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.

于 2009-03-10T13:51:22.000 回答
2

以我的经验,大多数此类设备都使用一些提示符,在这种情况下Telnet.read_until()是合适的:

Telnet.read_until(expected[, timeout])

读取直到遇到预期的给定字符串或直到超时秒数过去。如果找不到匹配项,则返回可用的任何内容,可能是空字符串。如果连接已关闭且没有可用的熟数据,则引发 EOFError。

如果设备没有提供可用(重复)提示,请尝试Telnet.read_very_eager()Telnet.read_very_lazy()

Telnet.read_very_eager()

阅读所有可以在 I/O 中不阻塞的内容(渴望)。

如果连接关闭且没有可用的熟数据,则引发 EOFError。如果没有可用的熟数据,则返回 ''。除非在 IAC 序列中,否则不要阻塞。

于 2009-03-10T13:50:50.597 回答
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")
于 2009-03-10T13:52:11.717 回答
1

循环读取行,直到您读取所需的行数或达到时间限制。但是,听起来您实际上并不需要 telnet 库。为什么不直接使用简单的 TCP套接字进行连接?

于 2009-03-10T13:49:49.787 回答