Last active
March 10, 2021 20:11
-
-
Save QuiteClose/ce9ebc5b9c345cca36a1f93150c2d4a7 to your computer and use it in GitHub Desktop.
Checking whether a read will block and then learning stdin
This file contains 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
''' | |
Basic functions for clearing stdin by checking whether a | |
read will block. | |
''' | |
import select | |
import sys | |
def has_unread_input(stream=sys.stdin, timeout=0): | |
''' | |
Where stream is a readable file-descriptor, returns | |
True if the given stream has input waiting to be read. | |
Otherwise returns False. | |
The default timeout of zero indicates that the given | |
stream should be polled for input and the function | |
returns immediately. Increasing the timeout will cause | |
the function to wait that many seconds for the poll to | |
succeed. Setting timeout to None will cause the function | |
to block until it can return True. | |
''' | |
return stream in select.select([stream], [], [], timeout)[0] | |
def discard_input(stream=sys.stdin): | |
''' | |
Where stream is a readable file-descriptor, reads | |
all available data and returns any bytes read. If no | |
data is available, then an empty set of bytes is | |
returned. | |
''' | |
data = bytearray() | |
while has_unread_input(stream): | |
data.extend(stream.readline()) | |
return bytes(data) | |
def refreshed_input(prompt=''): | |
''' | |
Clears stdin before writing the given prompt and | |
waiting for input from stdin. Returns the given | |
input as a string with the trailing-newline removed. | |
''' | |
discard_input(sys.stdin) | |
try: | |
return raw_input(prompt) | |
except NameError: | |
return input(prompt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment