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实现基于二叉树存储结构的堆排序算法。分享给大家供大家参考,具体如下: 既然用Python实现了二叉树,当然要写点东西练练手。 网络上堆排序的教程很多,但是却几乎...

python实现textrank关键词提取

用python写了一个简单版本的textrank,实现提取关键词的功能。 import numpy as np import jieba import jieba.posseg...

如何安装2019Pycharm最新版本(详细教程)

如何安装2019Pycharm最新版本(详细教程)

1下载安装 1.1打开官网 http://www.jetbrains.com/pycharm/download/ 耐心等待,大概200M,几分钟左右 1.2.双击下载好的exe,得到如...

Python走楼梯问题解决方法示例

本文实例讲述了Python走楼梯问题解决方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 ''' 下楼问题。从楼上走到楼下共有...

django 连接数据库 sqlite的例子

Aphorism the fight is worth it. django models 连接 sqlite 数据库 django 版本为 1.11.7 在 blog 项目下创建一个...