Skip to content

Instantly share code, notes, and snippets.

@jdowner
Last active September 9, 2022 15:33
Show Gist options
  • Save jdowner/d4b4079678ed7ce39212 to your computer and use it in GitHub Desktop.
Save jdowner/d4b4079678ed7ce39212 to your computer and use it in GitHub Desktop.
asyncio timed input
#!/usr/bin/env python3
"""
The MIT License (MIT)
Copyright (c) 2016 Joshua Downer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import asyncio
import sys
@asyncio.coroutine
def timed_input(prompt, timeout=0):
"""Wait for input from the user
Note that user input is not available until the user pressed the enter or
return key.
Arguments:
prompt - text that is used to prompt the users response
timeout - the number of seconds to wait for input
Raises:
An asyncio.futures.TimeoutError is raised if the user does not provide
input within the specified timeout period.
Returns:
A string containing the users response
"""
# Write the prompt to stdout
sys.stdout.write(prompt)
sys.stdout.flush()
loop = asyncio.get_event_loop()
queue = asyncio.Queue()
# The response callback will receive the users input and put it onto the
# queue in an independent task.
def response():
loop.create_task(queue.put(sys.stdin.readline()))
# Create a reader so that the response callback is invoked if the user
# provides input on stdin.
loop.add_reader(sys.stdin.fileno(), response)
try:
# Wait for an item to be placed on the queue. The only way this can
# happen is if the reader callback is invoked.
return (yield from asyncio.wait_for(queue.get(), timeout=timeout))
except asyncio.futures.TimeoutError:
# Make sure that any output to stdout or stderr that happens following
# this coroutine, happens on a new line.
sys.stdout.write('\n')
sys.stdout.flush()
raise
finally:
# Whatever happens, we should remove the reader so that the callback
# never gets called.
loop.remove_reader(sys.stdin.fileno())
@asyncio.coroutine
def greet():
try:
name = yield from timed_input("What is your name? ", 5)
print("Hello, " + name)
except asyncio.futures.TimeoutError:
print("What is the matter? Are you shy?")
loop = asyncio.get_event_loop()
loop.run_until_complete(greet())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment