Last active
October 20, 2024 13:48
-
-
Save pbk20191/1f4269b21c20b8018a6cdfbe90991677 to your computer and use it in GitHub Desktop.
python async console inputs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import os | |
import sys | |
from typing import AsyncGenerator | |
from contextlib import closing | |
async def console_input() -> AsyncGenerator[str, None]: | |
loop = asyncio.get_event_loop() | |
reader = asyncio.StreamReader(loop=loop) | |
with os.fdopen(os.dup(sys.stdin.fileno()), mode='rt+') as file_ref: | |
transport, reader_protocol = await loop.connect_read_pipe( | |
protocol_factory=lambda : asyncio.StreamReaderProtocol(stream_reader=reader, loop=loop), | |
pipe=file_ref | |
) | |
with closing(transport): | |
async for buffer in reader: | |
yield buffer.decode() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import asyncio.windows_utils | |
import msvcrt | |
import os | |
import sys | |
from ctypes import WinError, windll | |
from typing import AsyncGenerator | |
kernel32 = windll.kernel32 | |
async def console_input() -> AsyncGenerator[str, None]: | |
loop = asyncio.get_event_loop() | |
running = False | |
with os.fdopen(fd=os.dup(sys.stdin.fileno()), mode='rt+') as reader: | |
try: | |
while reader.readable(): | |
running = True | |
next_line = await loop.run_in_executor(None, reader.readline, -1) | |
running = False | |
if next_line is None or next_line == '': | |
return | |
yield next_line.rstrip() | |
finally: | |
result = -1 | |
if running: | |
result = kernel32.CancelIoEx(msvcrt.get_osfhandle(reader.fileno()), None) | |
if result == 0: | |
raise WinError() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment