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

yipeiwu_com5年前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实现画一颗树和一片森林

本文实例为大家分享了python画一颗树和一片森林的具体代码,供大家参考,具体内容如下 实现效果 代码在这里 from turtle import Turtle def tree...

python使用PyQt5的简单方法

python使用PyQt5的简单方法

一:安装PyQt5 pip install pyqt5 二:PyQt5简单使用 1:使用PyQt5创建一个简单窗口 import sys from PyQt5 import...

Sublime开发python程序的示例代码

本文介绍了Sublime开发python程序的示例代码,分享给大家,具体如下: 下载、安装Python程序 https://www.python.org/downloads/ 下载、安...

Python统计python文件中代码,注释及空白对应的行数示例【测试可用】

本文实例讲述了Python实现统计python文件中代码,注释及空白对应的行数。分享给大家供大家参考,具体如下: 其实代码和空白行很好统计,难点是注释行 python中的注释分为以#开头...

Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法

废话不多说,直接上代码吧! import threading import os class Find(threading.Thread): #搜索数据的线程类 def __i...