隨手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.
新聞熱點
疑難解答