Advertisement
Guest User

stdin_asyncio

a guest
Jan 2nd, 2025
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. import asyncio
  2. import sys
  3.  
  4. async def read_stdin():
  5.     """Asynchronously reads lines from stdin."""
  6.     loop = asyncio.get_running_loop()
  7.     reader = asyncio.StreamReader()
  8.  
  9.     def stdin_reader():
  10.         """Callback to feed data from stdin to StreamReader."""
  11.         data = sys.stdin.read(1024)
  12.         if data:
  13.             reader.feed_data(data.encode())
  14.         else:
  15.             reader.feed_eof()
  16.  
  17.     loop.add_reader(sys.stdin, stdin_reader)
  18.  
  19.     try:
  20.         while not reader.at_eof():
  21.             line = await reader.readline()
  22.             if line:
  23.                 print(f"Got line: {line.decode().strip()}")
  24.             else:
  25.                 break
  26.     finally:
  27.         loop.remove_reader(sys.stdin)
  28.  
  29. async def main():
  30.     print("Type something (Ctrl+D to exit):")
  31.     await read_stdin()
  32.  
  33. asyncio.run(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement