python - 在 Linux 上使用特定键中断 python 脚本

标签 python linux python-2.7

我正在尝试创建一个递增并打印值的循环。当它运行时,我想按下一个键(例如空格或shift)并让它打印出该键被按下。下面是我想要的示例代码。

def space():
    print 'You pressed space'    

def shift():
    print 'You pressed shift'

x = 0
while True:    
    print(x)
    #if space is pressed
    space()
    #if shift is pressed    
    shift()
    x = x + 1;
    time.sleep(1)

编辑:这是一个示例输出

0
1
2
You pressed shift
3
4
5
You pressed space
6
7
.
.
.

最佳答案

我可以在这里帮助您修改答案表:

https://stackoverflow.com/questions/11918999/key-listeners-in-python

只为空格输入:

import contextlib
import sys
import termios
import time


@contextlib.contextmanager
def raw_mode(file):
    old_attrs = termios.tcgetattr(file.fileno())
    new_attrs = old_attrs[:]
    new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
    try:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
        yield
    finally:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)


def space(ch):
    if ord(ch) == 32:
        print 'You pressed space'

def enter(ch):
    if ord(ch) == 10:
        print 'You pressed enter'


def main():
    print 'exit with ^C or ^D'
    with raw_mode(sys.stdin):
        try:
            x = 0
            while True:
                print(x)
                ch = sys.stdin.read(1)
                space(ch)
                enter(ch)
                x = x + 1;
                time.sleep(1)
        except (KeyboardInterrupt, EOFError):
            pass

if __name__ == '__main__':
    main()

关于python - 在 Linux 上使用特定键中断 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39085169/

相关文章:

python - Pyplot投影不承认数据: numpy. float64错误

python - ruby 相当于 python izip_longest

linux - 以编程方式确定 Ubuntu 发行版和体系结构?

python - Flask/WTForms - 发布请求不发送输入

linux - 无法找到错误的位置

linux - 用于查找和替换并进行确认的 Shell 脚本

Python - 将 PDF 文件保存到磁盘中

python-2.7 - Docker for nltk的HOME目录?

python - requirements.txt 波形符等于 (~=) 与波形符大于 (~>)

python - 你如何使用 easy_install 安装 django 旧版本?