首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过检测按键来中断Python中的这个循环

如何通过检测按键来中断Python中的这个循环
EN

Stack Overflow用户
提问于 2014-03-04 21:11:07
回答 4查看 37.6K关注 0票数 2
代码语言:javascript
复制
from subprocess import call
try:
    while True:
        call (["raspivid -n -b 2666666.67 -t 5000 -o test.mp4"],shell=True)
        call (["raspivid -n -b 2666666.67 -t 5000 -o test1.mp4"],shell=True)
except KeyboardInterrupt:
    pass

我计划让它打破循环,而我正在按任何按钮。然而,我尝试了很多方法来打破这些错误,但没有一种方法奏效。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-03-04 21:30:41

您希望您的代码更像这样:

代码语言:javascript
复制
from subprocess import call

while True:
    try:
        call(["raspivid -n -b 2666666.67 -t 5000 -o test.mp4"], shell=True)
        call(["raspivid -n -b 2666666.67 -t 5000 -o test1.mp4"], shell=True)
    except KeyboardInterrupt:
        break  # The answer was in the question!

您的break循环与您期望的完全一样。

票数 8
EN

Stack Overflow用户

发布于 2016-09-07 17:32:51

使用不同的线程来收听"ch“。

代码语言:javascript
复制
import sys
import thread
import tty
import termios
from time import sleep

breakNow = False

def getch():

    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)

    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

    return ch

def waitForKeyPress():

    global breakNow

    while True:
        ch = getch()

        if ch == "b": # Or skip this check and just break
            breakNow = True
            break

thread.start_new_thread(waitForKeyPress, ())

print "That moment when I will break away!"

while breakNow == False:
    sys.stdout.write("Do it now!\r\n")
    sleep(1)

print "Finally!"
票数 4
EN

Stack Overflow用户

发布于 2014-03-04 21:38:31

试试这个:

代码语言:javascript
复制
from subprocess import call
    while True:
        try:
            call (["raspivid -n -b 2666666.67 -t 5000 -o test.mp4"],shell=True)
            call (["raspivid -n -b 2666666.67 -t 5000 -o test1.mp4"],shell=True)
        except KeyboardInterrupt:
            break
        except:
            break
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22183115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档