Python 异步:在做其他事情时等待 stdin 输入 [英] Python async: Waiting for stdin input while doing other stuff

查看:79
本文介绍了Python 异步:在做其他事情时等待 stdin 输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a WebSocket command line client that waits for messages from a WebSocket server but waits for user input at the same time.

每秒定期轮询多个在线资源在服务器上运行良好(在本例中运行在 localhost:6789 上),但不是使用 Python 的普通 sleep() 方法,它使用 asyncio.sleep(),这是有道理的,因为睡眠和异步睡眠不是一回事,至少不是在幕后.

Regularly polling multiple online sources every second works fine on the server, (the one running at localhost:6789 in this example), but instead of using Python's normal sleep() method, it uses asyncio.sleep(), which makes sense because sleeping and asynchronously sleeping aren't the same thing, at least not under the hood.

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

Similarly, waiting for user input and asynchronously waiting for user input aren't the same thing, but I can't figure out how to asynchronously wait for user input in the same way that I can asynchronously wait for an arbitrary amount of seconds, so that the client can deal with incoming messages from the WebSocket server while simultaneously waiting for user input.

monitor_cmd()else 子句中下面的注释希望能解释我的意思:

The comment below in the else-clause of monitor_cmd() hopefully explains what I'm getting at:

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

这段代码只是无限期地等待输入,同时什么都不做,我明白为什么.我不明白的是如何解决它.:)

This code just waits for input indefinitely and does nothing else in the meantime, and I understand why. What I don't understand, is how to fix it. :)

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

Of course, if I'm thinking about this problem in the wrong way, I'd be very happy to learn how to remedy that as well.

推荐答案

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

You can use the aioconsole third-party package to interact with stdin in an asyncio-friendly manner:

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

这篇关于Python 异步:在做其他事情时等待 stdin 输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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