A small example of non-blocking input in the Python command line

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.