Skip to content

Instantly share code, notes, and snippets.

@iTrooz
Created July 22, 2024 04:12
Show Gist options
  • Save iTrooz/0f63e9e1848d1696b148d69b2650104a to your computer and use it in GitHub Desktop.
Save iTrooz/0f63e9e1848d1696b148d69b2650104a to your computer and use it in GitHub Desktop.
Reads stdin from the user console and stops input with Ctrl+C
"""
Reads stdin from the user console and stops input with Ctrl+C. Also support piped stdin.
Works only on Linux (and maybe MacOS ?)
"""
import sys
import os
import time
import fcntl
def read_user_stdin() -> bytes:
os.system("stty cbreak") # Disable stdin buffering
# Actually read from stdin
BUFFER_SIZE=256
data = bytearray()
while True:
try:
chunk = sys.stdin.buffer.raw.read(BUFFER_SIZE)
except KeyboardInterrupt:
break
if chunk == None:
break
data += chunk
os.system("stty -cbreak") # Re-enable stdin buffering
return bytes(data)
def read_pipe_stdin() -> bytes:
return sys.stdin.read().encode()
def read_current_stdin() -> bytes:
if os.isatty(0):
return read_user_stdin()
else:
return read_pipe_stdin()
print(read_current_stdin())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment