【发布时间】:2019-02-20 12:33:42
【问题描述】:
我面临的问题是:
- 我有一个异步方法
- 调用我无法更改的普通 Python 代码
- 回调一个普通的 Python 方法
- 需要使用
await调用异步代码
我有一个基于Python's Cmd class 构建的自定义命令解释器。我为它提供了自定义标准输入和标准输出。对于这个问题,它看起来像这样:
import cmd
import sys
class CustomStream(object):
def readline(self):
return sys.stdin.readline()
def write(self, msg):
sys.stdout.write(msg)
def flush(self):
pass
class MyShell(cmd.Cmd):
def do_stuff(self, args):
print("Getting things done...")
def do_exit(self, args):
return True
stream = CustomStream()
shell = MyShell(stdin=stream, stdout=stream)
shell.use_rawinput = False
shell.cmdloop()
当Cmd需要从用户那里读取时,它会这样做:
line = self.stdin.readline()
我想使用基于asyncio 的 AsyncSSH 库为我的自定义解释器提供 SSH 接口。我的 SSH 代码很像 Simple Server sample,它读取类似 stdin 的接口(注意 await 关键字):
line_from_client = (await self._process.stdin.readline()).rstrip('\n')
我尝试了很多方法,但我无法将 SSH 代码输入 Cmd 对标准输入的期望。我必须怎么做才能让我的 CustomStream 对象在内部使用 asyncio/coroutines,同时为 MyShell 提供老式的单线程接口?
【问题讨论】:
-
这个 reddit 线程总结了我迄今为止尝试的所有内容...reddit.com/r/Python/comments/6m826s/…
标签: python ssh async-await stdin