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】str与json类型转换

在写接口测试框架时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型 str转json python字符串转json对象,需要使用json模块的loads函数...

黑科技 Python脚本帮你找出微信上删除你好友的人

黑科技 Python脚本帮你找出微信上删除你好友的人

相信大家在微信上一定被上面的这段话刷过屏,群发消息应该算是微信上流传最广的找到删除好友的方法了。但群发消息不仅仅会把通讯录里面所有的好友骚扰一遍,而且你还得挨个删除好几百个聊天记录,回复...

python实现月食效果实例代码

python实现月食效果实例代码

我们在学习Python当中的pygame模块时,我们都知道我们可以通过使用 pygame模块实现很多功能性的东西,但是很多人应该不知道怎么通过使用pygame实现月食的效果吧,接下来我就...

Python中os和shutil模块实用方法集锦

复制代码 代码如下:# os 模块os.sep 可以取代操作系统特定的路径分隔符。windows下为 '\\'os.name 字符串指示你正在使用的平台。比如对于Wi...

python requests指定出口ip的例子

爬虫需要,一个机器多个口,一个口多个ip,为轮询这些ip demo #coding=utf-8 import requests,sys,socket from requests_to...