telnet - 使用 asyncio 与守护进程对话
问题描述
我有一个 python 模块,它使用 Telnetlib 打开与守护程序的连接,并且能够发送命令并获取解析响应。这用于测试目的。然而,有时守护进程也会发送异步消息。我目前的解决方案是有一个“wait_for_message”方法,它将启动一个线程来监听 telnet 套接字。同时,在主线程中,我发送了一个我知道会触发守护进程发送特定异步消息的命令。然后我只需执行 thread.join() 并等待它完成。
import telnetlib
class Client():
def __init__(self, host, port):
self.connection = telnetlib.Telnet(host, port)
def get_info(self):
self.connection.write('getstate\r')
idx, _, _ = self.connection.expect(['good','bad','ugly'], timeout=1)
return idx
def wait_for_unexpected_message(self):
idx, _, _ = self.connection.expect(['error'])
然后当我编写测试时,我可以将该模块用作自动化系统的一部分。
client = Client()
client.connect('192.168.0.45', 6000)
if client.get_info() != 0:
# do stuff
else:
# do other stuff
在我想处理传入的异步消息之前,它工作得非常好。我一直在阅读 Python 的新 asyncio 库,但我还没有完全弄清楚如何做我需要它做的事情,或者即使我的用例会受益于 asyncio。
所以我的问题是:有没有更好的方法来用 asyncio 更好地处理这个问题?我喜欢使用 telnetlib,因为它具有 expect() 功能。使用简单的 TCP 套接字对我来说并不能做到这一点。
解决方案
推荐阅读
- javascript - 存储在字符串中的 ejs 代码不会在前端执行
- javascript - 角度日期管道显示的日期不正确
- python - 如何设置 python 日志记录以使用多个模块和函数调用中指定的输出文件
- python - 如何在 Python 中对列表列表进行选择性笛卡尔积
- json - 如何在 Go 中编组嵌入式结构?
- java - 获取身份验证值
- java - 我想使用@JoinColumns 从不同的表中获取数据 - 如何创建一个可以传递参数的条件?
- windows - 从提升的脚本访问用户环境变量?
- c# - Windows 桌面 (5) 在 .net 5 的上下文中是什么意思?
- xamarin.forms - Xamarin Forms Shell 选项卡栏 - 加载该选项卡的默认视图