如何在不使用raw_input或Ctrl-C的情况下中断无限循环? Python 2.7

时间:2018-05-22 07:51:13

标签: python

我已经看过其他帖子,并搜索了一段时间并阅读了文档。但我似乎无法理解答案。我得到的最近的是信号模块,但文档让我很生气。我需要从循环中断,不使用raw_input,Ctrl-C是完美的,除非我需要将其更改为激活,如果用户单击SPACE或ENTER。

from time import sleep
try:
while True:
    print "I'm looping!"
    sleep(1)
except KeyboardInterrupt:   
print "The loop has ended!"

这个循环是完美的如果我只能更改KeyboardInterrupt错误的键。

1 个答案:

答案 0 :(得分:1)

这是一个有趣且令人惊讶的复杂问题(不确定为什么会掉线...)你必须绕过标准"读到行尾#34;以及在正常阻塞读取时添加超时。这是我的答案(仅适用于linux / mac,但请参阅有关将其扩展到Windows的想法的链接):

import select
import sys, termios


def getchar():
    char = '_'
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~(termios.ECHO | termios.ICANON) # turn off echo and canonical mode which sends data on delimiters (new line or OEF, etc)
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new) # terminal is now 
        ready, steady, go = select.select([sys.stdin], [], [], 1)
        if ready:
            char = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return char


try:
    while True:
        print "I'm looping!"
        c = getchar()
        if c in ' \n':
            print "The loop has ended!"
            break
except KeyboardInterrupt:
    print "The loop has ended!"

它是this answerthis answer的组合。显然,readchar library 建议this answer也是如此。