A small example of a Python command line non blocking input
- 2020-04-02 13:10:02
- OfStack
With Google, we basically used select to implement non-blocking listening, but the problem is that after using select to listen is not like getchar(), immediately received a single character of the input, must wait for the return.
After trying not to Google... [well, Google. Nothing can be done without Google.]
Finally, a large number of English data into the surface, put together the following available code, to achieve a single character non - blocking input.
Show the code below.
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" python non blocking input
"""
__author__ = 'Zagfai'
__version__= '2013-09-13'
import sys
import select
from time import sleep
import termios
import tty
old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
while True:
sleep(.001)
if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
c = sys.stdin.read(1)
if c == 'x1b': break
sys.stdout.write(c)
sys.stdout.flush()
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
print raw_input('123:')
Two modules, termios and tty, are used to control the input mode of tty, changing from line input to single character.
The END.