在python中的任意时间捕获用户输入 [英] Capturing user input at arbitrary times in python

查看:105
本文介绍了在python中的任意时间捕获用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在控制台中输入内容时,是否可以将中断发送到python模块?例如,如果我正在运行一个无限的while循环,我可以用try/except代替KeyboardInterrupt围绕它,然后在except块中执行我需要做的事情.

Is there a way to send an interrupt to a python module when the user inputs something in the console? For example, if I'm running an infinite while loop, i can surround it with a try/except for KeyboardInterrupt and then do what I need to do in the except block.

是否可以使用任意输入来复制此功能?是控制序列还是标准字符?

Is there a way to duplicate this functionality with any arbitrary input? Either a control sequence or a standard character?

对不起,这是在Linux上

Sorry, this is on linux

推荐答案

取决于操作系统和可用的库,有不同的实现方法. 此答案提供了其中的一些.

Dependent on the operating system and the libraries available, there are different ways of achieving that. This answer provides a few of them.

这里是从那里复制的Linux/OS X部件,无限循环使用转义字符终止.对于Windows解决方案,您可以检查答案本身.

Here is the Linux/OS X part copied from there, with in infinite loop terminated using the escape character. For the Windows solution you can check the answer itself.

import sys
import select
import tty
import termios

from curses import ascii

def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())

    i = 0
    while 1:
        print i
        i += 1

        if isData():
            c = sys.stdin.read(1)
            if c == chr(ascii.ESC):
                break

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

编辑:由于Daenyth对我共享的魔术值不满意,因此将字符检测更改为使用curses.ascii定义的字符.

Edit: Changed the character detection to use characters as defined by curses.ascii, thanks to Daenyth's unhappiness with magic values which I share.

这篇关于在python中的任意时间捕获用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆