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

时间:2014-03-04 21:11:08

标签: python python-2.7 raspberry-pi

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

我打算在按任何按钮时打破循环。但是我尝试了许多方法来打破它们,但没有一种方法可以解决。

5 个答案:

答案 0 :(得分:7)

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

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完全按照你期望的方式循环。

答案 1 :(得分:4)

使用其他线程来收听" 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!"

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

你可以试试这个:

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

取自:here

答案 4 :(得分:0)

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

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

适用于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()