python - 在python中任意时间捕获用户输入

标签 python linux input interrupt

当用户在控制台中输入内容时,有没有办法向 python 模块发送中断?例如,如果我正在运行一个无限 while 循环,我可以用 try/except for KeyboardInterrupt 包围它,然后在 except block 中执行我需要执行的操作。

有没有办法用任意输入复制这个功能?是控制序列还是标准字符?

编辑:抱歉,这是在 linux 上

最佳答案

根据操作系统和可用的库,有不同的方法可以实现这一点。 This answer提供了其中的一些。

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

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)

编辑:将字符检测更改为使用 curses.ascii 定义的字符,这要归功于 Daenyth 对我分享的魔法值的不满。

关于python - 在python中任意时间捕获用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3731681/

相关文章:

python - Pandas 绘制一个重复的数据框

python - 如何删除 numpy.ndarray 中包含非数字值的所有行

linux - 在 32 位操作系统上运行 64 位 jvm

jquery - 如何使用 jQuery 取消按钮的提交

python - 是否可以使用 getch() 获取不同长度的输入?

python - Django 中的元素计数

python - id() 的含义以及为什么来自 Process fork 的不同对象具有相同的 id() 值?

linux - dlopen/dlclose 与几个 so,在 dlopen 上被阻止

c++ - 在 Ruby 中调用 C++ 共享库

安卓 : Keep track of total keystroke while application running in background?