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.

相关文章

flask 实现token机制的示例代码

token 的生成 用token校验身份,是前后端交互的常用方式。 它有以下特性: 会失效 加密 可以根据它拿到用户的信息 生成方式( 内部配置的私钥+有效期+用户的...

利用Python暴力破解zip文件口令的方法详解

利用Python暴力破解zip文件口令的方法详解

前言 通过Python内置的zipfile模块实现对zip文件的解压,加点料完成口令破解 zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的cla...

学习python的几条建议分享

熟悉python语言,以及学会python的编码方式。熟悉python库,遇到开发任务的时候知道如何去找对应的模块。知道如何查找和获取第三方的python库,以应付开发任务。 安装开发...

pygame游戏之旅 添加游戏介绍

pygame游戏之旅 添加游戏介绍

本文为大家分享了pygame游戏之旅的第9篇,供大家参考,具体内容如下 在游戏开始之前定义一个函数,用来显示游戏介绍: def game_intro(): intro = Tru...

Python random模块常用方法

复制代码 代码如下: import random print random.random() 获取一个小于1的浮点数 复制代码 代码如下: import random random.r...