如何通过检测按键来中断Python中的循环
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
这是我用线程和标准库找到的解决方案。
这个循环会一直运行,直到你按下一个键。
它会把你按下的键作为一个单字符的字符串返回。
这个方法在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()
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
2
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!"
8
你希望你的代码看起来更像这样:
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
来结束一个循环。