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中关于py文件之间相互import的问题及解决方法
这篇文章主要介绍了python中关于py文件之间相互import的问题,本文用一个例子演示下如何解决python中循环引用的问题,需要的朋友可以参考下2022-02-02
Python批量处理PDF图片的操作指南(插入、压缩、提取、替换、分页、旋转、删除)
图片是 PDF 文档的核心元素之一,它们不仅能够增强文档的视觉吸引力,还能有效传达信息,帮助读者更好地理解内容和主题,在实际操作中,我们常需要对PDF中的图片进行多种处理,这篇文章将详细介绍如何使用Python在PDF中实现图片插入、提取、替换、压缩等操作2025-04-04


最新评论