【问题标题】:Python async: Waiting for stdin input while doing other stuffPython异步:在做其他事情时等待标准输入输入
【发布时间】:2020-02-15 15:32:57
【问题描述】:

我正在尝试创建一个 WebSocket 命令行客户端,它等待来自 WebSocket 服务器的消息,但同时等待用户输入。

每秒定期轮询多个在线资源在服务器上运行良好,(在此示例中运行在 localhost:6789 的那个),但不是使用 Python 的正常 sleep() 方法,而是使用 asyncio.sleep(),这是有道理的,因为睡眠和异步睡眠不是一回事,至少在引擎盖下不是。

同样,等待用户输入和异步等待用户输入不是一回事,但我不知道如何异步等待用户输入,就像我可以异步等待任意数量的秒,以便客户端可以在等待用户输入的同时处理来自 WebSocket 服务器的传入消息。

monitor_cmd()else 子句中的以下评论希望能解释我的意思:

import asyncio
import json
import websockets

async def monitor_ws():
    uri = 'ws://localhost:6789'
    async with websockets.connect(uri) as websocket:
        async for message in websocket:
            print(json.dumps(json.loads(message), indent=2, sort_keys=True))

async def monitor_cmd():
    while True:

        sleep_instead = False

        if sleep_instead:
            await asyncio.sleep(1)
            print('Sleeping works fine.')
        else:
            # Seems like I need the equivalent of:
            # line = await asyncio.input('Is this your line? ')
            line = input('Is this your line? ')
            print(line)
try:
    asyncio.get_event_loop().run_until_complete(asyncio.wait([
        monitor_ws(),
        monitor_cmd()
    ]))
except KeyboardInterrupt:
    quit()

这段代码只是无限期地等待输入,在此期间什么也不做,我明白为什么。我不明白的是如何解决它。 :)

当然,如果我以错误的方式思考这个问题,我也很乐意学习如何解决这个问题。

【问题讨论】:

  • aioconsole 可能是您需要的。
  • @user4815162342:是的!实际上,这正是我所需要的! :) 文档不是太好,但是导入了 aioconsole,这正是行之有效的行:line = await aioconsole.ainput('这是你的行吗?') 如果你把那行作为答案,我'将其标记为正确的。

标签: python-3.x python-asyncio


【解决方案1】:

您可以使用aioconsole 第三方包以异步友好的方式与标准输入进行交互:

line = await aioconsole.ainput('Is this your line? ')

【讨论】:

    【解决方案2】:

    大量借鉴aioconsole,如果您不想使用外部库,您可以定义自己的异步输入函数:

    async def ainput(string: str) -> str:
        await asyncio.get_event_loop().run_in_executor(
                None, lambda s=string: sys.stdout.write(s+' '))
        return await asyncio.get_event_loop().run_in_executor(
                None, sys.stdin.readline)
    

    【讨论】:

    • 很高兴知道!谢谢!
    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多