如何通过检测按键来打破 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
How to break this loop in Python by detecting key press
提问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
回答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()

