Python 命令行非阻塞输入的小例子

yipeiwu_com6年前Python基础

 随手google咗一下,基本上都用select实现非阻塞监听,但问题是,监听的是用select之后是不能像getchar()那样,即时收到单个字符的输入,必须要等待回车。

    经过努力不怠咁google... [好吧,还是google。没有google什么也做不了。]

    最后系一大堆英文资料入面,拼凑出如下可用的代码,实现了单个字符非阻塞输入。

    show 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:')


其中用到两个模块,分别系termios、tty,用来控制tty的输入模式,由行输入变为单字符。

    END.

相关文章

Python语言的变量认识及操作方法

今天我给大家介绍的是python中的Number变量,与c++,java有些不同,下面让来为大家介绍: 在python中是不用声明变量类型的,不过在使用变量前需要对其赋值,没有值得变量是...

Python实现的金山快盘的签到程序

复制代码 代码如下:__author__ = 'clownfish'#coding:utf-8import urllib2,urllib,cookielib,json username...

Python贪吃蛇游戏编写代码

Python贪吃蛇游戏编写代码

最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。 由于Python监听键盘很麻烦,没有C语言的kbhi...

python_opencv用线段画封闭矩形的实例

如下所示: def draw_circle(event,x,y,flags,param): global ix,iy,drawing,mode,start_x,start_y...

python操作MySQL数据库具体方法

复制代码 代码如下: import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',user='r...