Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import readline
- import asyncio
- import threading
- from threading import Thread
- import sys
- #from asyncio.subprocess import PIPE, STDOUT
- streaming_queue = asyncio.Queue()
- def stderr_print(*args, **kwargs):
- print(*args, file=sys.stderr, **kwargs)
- async def handle_console_input(loop, running):
- while running.is_set():
- chunk = await streaming_queue.get()
- if chunk == 'quit':
- stderr_print("quit detected!")
- running.clear()
- stderr_print("got chunk: \"%s\"" % chunk)
- if not running.is_set():
- print("clear handle_console_input")
- def command_console(loop, running):
- try:
- loop.run_until_complete(handle_console_input(loop, running))
- stderr_print("completed")
- running.clear()
- if not running.is_set():
- print("clear_command_console")
- exit
- except asyncio.CancelledError:
- loop.close()
- stderr_print("loop closed")
- running.clear()
- if not running.is_set():
- print("clear_command_console exception")
- exit
- def queue_console_input(chunk):
- streaming_queue.put_nowait(chunk)
- def shutdown_threads():
- for task in asyncio.all_tasks():
- task.cancel()
- if __name__ == "__main__":
- loop = asyncio.get_event_loop()
- thread_running = threading.Event()
- thread_running.set()
- event_thread = Thread(target=command_console, args=(loop,thread_running))
- event_thread.start()
- try:
- while thread_running.is_set():
- if not thread_running.is_set():
- print("clear main")
- else:
- print("set main")
- chunk = input('console> ')
- loop.call_soon_threadsafe(queue_console_input, chunk)
- if not thread_running.is_set():
- print("clear main outside")
- stderr_print("cancelling all tasks")
- loop.call_soon_threadsafe(shutdown_threads)
- stderr_print("joining thread")
- event_thread.join()
- stderr_print("done")
- except KeyboardInterrupt:
- stderr_print("Got INTERRUPT!")
- stderr_print("cancelling all tasks")
- loop.call_soon_threadsafe(shutdown_threads)
- stderr_print("joining thread")
- event_thread.join()
- stderr_print("done")
- # wiley@lenin:~/WileyP$ ./readline_example.py
- # set main
- # console> foo
- # set main
- # console> got chunk: "foo"
- # bar
- # set main
- # console> got chunk: "bar"
- # quit
- # set main
- # console> quit detected!
- # got chunk: "quit"
- # clear handle_console_input
- # completed
- # clear_command_console
- #
- # clear main outside
- # cancelling all tasks
- # joining thread
- # done
- # From what I can tell, the above code is NOT calling input() an extra time, yet for some reason we
- # do not progress past the while loop until I hit return again. So, despite the loop.call_soon calling
- # a function that says not to wait, it still seems to be waiting for the (now dead) loop to empty the
- # message queue???
Advertisement
Add Comment
Please, Sign In to add comment