VaFancy VaFancy - 2 months ago 8
Python Question

How to break this loop in Python by detecting key press

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 any button. However I tried lots of methods to break the and none of them worked.

Answer

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 break a loop exactly how you would expect.

Comments