Python 命令行非阻塞输入 Python 命令行非阻塞输入的小例子

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python 命令行非阻塞输入 Python 命令行非阻塞输入的小例子

  2021-03-20 我要评论
想了解Python 命令行非阻塞输入的小例子的相关内容吗,在本文为您仔细讲解Python 命令行非阻塞输入的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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.

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们