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中最基本的 if 条件语句,这几乎是所有编程语言中都存在的语句,只是语法结构稍有不同。 程序之所以能自动处理很多的事情,if条件语句在这里...

matplotlib简介,安装和简单实例代码

matplotlib简介,安装和简单实例代码

官网介绍: Matplotlib is a Python 2D plotting library which produces publication quality figures i...

python中如何使用分步式进程计算详解

python中如何使用分步式进程计算详解

前言 在python中使用多进程和多线程都能达到同时运行多个任务,和多进程和多线程的选择上,应该优先选择多进程的方式,因为多进程更加稳定,且对于进程的操作管理也更加方便,但有一点是多进程...

python基于socket实现的UDP及TCP通讯功能示例

本文实例讲述了python基于socket实现的UDP及TCP通讯功能。分享给大家供大家参考,具体如下: Server: import socket address = ('127....

Python利用sqlacodegen自动生成ORM实体类示例

本文实例讲述了Python利用sqlacodegen自动生成ORM实体类。分享给大家供大家参考,具体如下: 在前面一篇《Python流行ORM框架sqlalchemy安装与使用》我们是手...