首页 > 解决方案 > 使用 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 套接字对我来说并不能做到这一点。

标签: telnetpython-asyncio

解决方案


推荐阅读