How to Kill a While Loop With a Keystroke

How to kill a while loop with a keystroke?

The easiest way is to just interrupt it with the usual Ctrl-C (SIGINT).

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

Since Ctrl-C causes KeyboardInterrupt to be raised, just catch it outside the loop and ignore it.

How to use Esc to stop a while loop?

Update your stop_loop method like this:

def stop_loop():
global stop
stop = 1
return stop

If you don't declare global stop then instead of updating stop variable you defined at the beginning of the file you'll create a new local stop variable inside stop_loop method.

Probably read this for better understanding: https://realpython.com/python-scope-legb-rule/

How do I exit a while loop from a keypress without using KeyboardInterrupt? [python]

Here is the example I promised you.

I did not need to import any mods for this program, but I believe the msvcrt mod that I use to control keyboard input is Windows specific. Be that as it may; even though we use different methods to control keyboard input, I hope you will see how your stopwatch can be controlled by key presses while a main program repeatedly loops and handles keyboard input.

import time     # Contains the time.time() method.
import winsound # Handle sounds.
import msvcrt # Has Terminal Window Input methods
# ===========================================
# -------------------------------------------
# -- Kbfunc() --
# Returns ascii values for those keys that
# have values, or zero if not.
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
# -------------------------------------------
# -- Get_Duration() --
# Gets the time duration for the stopwatch.
def get_duration():
value = input("\n How long do you want the timer to run? ")
try:
value = float(value)
except:
print("\n\t** Fatal Error: **\n Float or Integer Value Expected.\n")
exit()
return value
# ===========================================
# Body
# ===========================================
# To keep the program as simple as possible, we will only use
# standard ascii characters. All special keys and non-printable
# keys will be ignored. The one exception will be the
# carriage return key, chr(13).
# Because we are not trapping special keys such as the
# function keys, many will produce output that looks like
# standard ascii characters. (The [F1] key, for example,
# shares a base character code with the simicolon.)

valid_keys = [] # Declare our valid key list.
for char in range(32,127): # Create a list of acceptable characters that
valid_keys.append(char) # the user can type on the keyboard.
valid_keys.append(13) # Include the carriage return.

# ------------------------------------------
duration = 0
duration = get_duration()

print("="*60)
print(" Stopwatch will beep every",duration,"seconds.")
print(" Press [!] to turn Stopwatch OFF.")
print(" Press [,] to turn Stopwatch ON.")
print(" Press [@] to quit program.")
print("="*60)
print("\n Type Something:")
print("\n >> ",end="",flush = True)

run_cycle = True # Run the program until user says quit.
stopwatch = True # Turn the stopwatch ON.
T0 = time.time() # Get the time the stopwatch started running.

while run_cycle == True:
# ------
if stopwatch == True and time.time()-T0 > duration: # When the duration
winsound.Beep(700,300) # is over, sound the beep and then
T0 = time.time() # reset the timer.
# -----
key = kbfunc()
if key == 0:continue # If no key was pressed, go back to start of loop.

if key in valid_keys: # If the user's key press is in our list..

if key == ord(","): # A comma means to restart the timer.
duration = get_duration() # Comment line to use old duration.
print(" >> ",end="",flush = True) # Comment line to use old duration.
t0 = time.time()
stopwatch = True
continue # Remove if you want the ',' char to be printed.

elif key == ord("!"): # An exclamation mark means to stop the timer.")
stopwatch = False
continue # Remove if you want the "!" to print.

elif key == ord("@"): # An At sign means to quit the program.
print("\n\n Program Ended at User's Request.\n ",end="")
run_cycle = False # This will cause our main loop to exit.
continue # Loop back to beginning so that the at sign
# is not printed after user said to quit.

elif key == 13: # The carriage return means to drop down to a new line.
print("\n >> ",end="",flush = True)
continue

print(chr(key),end="",flush = True) # Print the (valid) character.
# Keys that are not in our list are simply ignored.

How to break this loop in Python by detecting key press

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.

Restart While Loop With Keypress

keyboard module has more features allowing different hooks/blockers.

Just use keyboard.wait(key) to block the control flow until key is pressed:

import keyboard
from time import sleep

key = "right shift"

while True:
print("Running")
sleep(0.5)
if keyboard.is_pressed(key):
print('waiting for `shift` press ...')
keyboard.wait(key)

Sample interactive output:

Running
Running
Running
waiting for `shift` press ...
Running
Running
Running
Running
Running
waiting for `shift` press ...
Running
Running
Running
...

How to exit a while loop with a keystroke in C?

I think you mean the following as long as a spacebar followed by the enter key is acceptable given your comments above.

char input = 0;
while( input != ' ' )
{
printf("Press space bar to continue...\n");
scanf("%c",&input);
}

Or if you prefer, without hitting the enter key:

#include <stdio.h>

int main(int argc, char **argv)
{
char input = 0;
while( input != ' ' )
{
printf("Press space bar to continue...\n");
input = getch();
}
}

This worked on my msysgit bash shell. BUT, some people will insist that it work on Linux as well. Which is fine I guess, I love Linux, but I said the above solution worked on msysgit. The following works on my, let me be specific, Oracle VM for Ubuntu 10.10.

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int main(int argc, char **argv)
{
char input = 0;
while( input != ' ' )
{
printf("Press space bar to continue...\n");
input = mygetch();
}
}

int mygetch(void)
{
struct termios oldt, newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}

The mygetch came from here.



Related Topics



Leave a reply



Submit