Python 命令行非阻塞输入
2013-09-25 14:27
323 查看
很久很久以前,系windows平台下,用C语言写过一款贪食蛇游戏,cmd界面,用kbhit()函数实现非阻塞输入。系windows平台下用python依然可以调用msvcrt.khbit实现非阻塞监听。但系喺linux下面就冇呢支歌仔唱。
随手google咗一下,基本上都用select实现非阻塞监听,但问题是,监听的是用select之后是不能像getchar()那样,即时收到单个字符的输入,必须要等待回车。
经过努力不怠咁google... [好吧,还是google。没有google什么也做不了。]
最后系一大堆英文资料入面,拼凑出如下可用的代码,实现了单个字符非阻塞输入。
show code below.
其中用到两个模块,分别系termios、tty,用来控制tty的输入模式,由行输入变为单字符。
END.
随手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获取命令行输入参数列表
- python 命令行输入参数介绍
- python入门 - 获取命令行输入
- python_getopt解析命令行输入参数的使用
- python获取命令行输入参数列表的实例代码
- python 预设命令行变量代替raw_input 二次输入的方法
- [Python基础] 命令行输入Python3的各参数含义
- python_getopt解析命令行输入参数的使用
- python获取从命令行输入数字的方法
- python采用getopt解析命令行输入参数实例
- win10设置环境变量,命令行下输入python,pip可运行
- Python optparse 解析命令行输入
- Python从命令行获得输入
- python关于利用Windows命令行输入参数的注意事项
- python采用getopt解析命令行输入参数实例
- Python脚本:命令行输入GeoTiff文件做运算