A long time ago, on the windows platform, I wrote a snake game in C language. on the cmd interface, I used the kbhit () function to implement non-blocking input. In windows, you can still use python to call msvcrt. khbit for non-blocking listening. However, in the linux operating system, when the fans sing the song, google clicks it. basically, select is used to implement non-blocking listening, but the problem is, after the select statement is used, a single character input cannot be received in real time like getchar (). you must wait for the carriage return.
After hard work, I am not idle about google... [Okay, google. There is nothing google can do.]
Finally, a large amount of English data is written, and the following available code is pieced together to implement non-blocking input of a single character.
Show code below.
The code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
"Python non blocking input
"""
_ Author _ = 'zagfai'
_ Version __= '2017-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 ('2017 :')
Two modules are used, including termios and tty, to control the input mode of tty, from line input to single character.
END.