如何使用 python 的 telnetlib 在固定时间段内从设备获取数据? [英] How can I use python's telnetlib to fetch data from a device for a fixed period of time?

查看:34
本文介绍了如何使用 python 的 telnetlib 在固定时间段内从设备获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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.

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

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

也许真正的问题是,我应该为此完全使用 telnetlib,还是应该只使用套接字模块?

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

推荐答案

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

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.

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

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.

或者,对于较低级别的内容,您可以使用 socket 模块打开连接到设备,然后进入定时循环并 read() 传入数据.如果这些行以换行符结尾,那么识别每个单独的数字应该很简单.如果您担心阻塞,请将这个循环放在它自己的线程中.

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.

这篇关于如何使用 python 的 telnetlib 在固定时间段内从设备获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆