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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22183115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:26:50  来源:igfitidea点击:

How to break this loop in Python by detecting key press

pythonpython-2.7raspberry-pi

提问by VaFancy

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

I plan to make it breaking loop while I am pressing anybutton. However I tried lots of methods to break the and none of them worked.

我打算在按下任何按钮时让它中断循环。但是,我尝试了很多方法来破解它,但都没有奏效。

采纳答案by Alex Thornton

You want your code to be more like this:

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

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!

You breaka loop exactly how you would expect.

break完全按照您的预期进行循环。

回答by Adrian B

try this:

尝试这个:

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

回答by ederollora

You could try this:

你可以试试这个:

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

Taken from: here

取自:这里

回答by nvd

Use a different thread to listen for a "ch".

使用不同的线程来监听“ch”。

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!"

回答by Berni Gf

This is the solution I found with threads and standard libraries

Loop keeps going on until one key is pressed
Returns the key pressed as a single character string

Works in Python 2.7 and 3

这是我在线程和标准库中找到的解决方案

循环一直进行,直到按下一个键 将按下
的键作为单个字符串返回

在 Python 2.7 和 3 中有效

import thread
import sys

def getch():
    import termios
    import sys, tty
    def _getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
    return _getch()

def input_thread(char):
    char.append(getch())

def do_stuff():
    char = []
    thread.start_new_thread(input_thread, (char,))
    i = 0
    while not char :
        i += 1

    print "i = " + str(i) + " char : " + str(char[0])

do_stuff()