TransWikia.com

How to pause and resume a while loop in Python?

Stack Overflow Asked by MentalCombination on November 11, 2020

I want to have a loop running that will print "Hello" and when I press "K" it stops printing but it doesn’t end the program, then when I press "K" again it starts printing again.

I tried this(using the keyboard module):

import keyboard

running = True

while running == True:
    print("hello")
    if keyboard.is_pressed("k"):
        if running == True:
            running = False
        else:
            running = True

but when I press the button it just ends the program and that’s not what I’m trying to do. I understand why it ends but I don’t know how to make it not end. How can I do that?

5 Answers

import keyboard

running = True
display = True
block = False

while running:
    if keyboard.is_pressed("k"):
        if block == False:
            display = not display
            block = True
    else:
        block = False
    if display:
        print("hello")
    else:
        print("not")

Correct answer by IzZy on November 11, 2020

I think the right way is flushing the buffer, because the previous solutions may print more. This works for windows, for Linux, you should refer to Python read a single character from the user


import time
import subprocess
import sys
import msvcrt

printing = True
while (1):
    # Try to flush the buffer
    while not msvcrt.kbhit() and printing:
        print("hello")

    doit = msvcrt.getch().decode('utf-8')
    if doit=="k":
        printing = not printing
        print("stop/start")
    if doit == 'q':
        break

This is the output of this code: enter image description here Please note that, if you add print("stop/start") in Adrian Melon's program, you can see his program prints several time "hello" after 'k' is pressed until the buffer will be empty.

    import keyboard

    running = True
    display = True
    block = False

    while running:
        if keyboard.is_pressed("k"):
            print("stop/start")
            if block == False:
                display = not display
                block = True
        else:
            block = False
        if display:
            print("hello")
        else:
            pass

This is the output of @Adrian-Melon program: enter image description here

Answered by rouhollah ghasempour on November 11, 2020

You could use a handler for the keypress, which sets an event that the main thread can then test for periodically, and wait if required.

(Note that there are two types of events here, the keypress event and the setting of the running, so these should not be confused.)

from threading import Event
from time import sleep
import keyboard

hotkey = 'k'

running = Event()
running.set()  # at the start, it is running

def handle_key_event(event):
    if event.event_type == 'down':
        # toggle value of 'running'
        if running.is_set():
            running.clear()
        else:
            running.set()

# make it so that handle_key_event is called when k is pressed; this will 
# be in a separate thread from the main execution
keyboard.hook_key(hotkey, handle_key_event)

while True:
    if not running.is_set():
        running.wait()  # wait until running is set
    sleep(0.1)        
    print('hello')

Answered by alani on November 11, 2020

Maybe something like that:

import keyboard

running = True
stop = False

while !stop:

    if keyboard.is_pressed("k"):
        running = !running          # Stops "hello" while
    if keyboard.is_pressed("q"):
        stop = !stop                # Stops general while

    if running:

        print("hello")

Answered by ThRnk on November 11, 2020

import sys
import keyboard
from time import sleep

running = True

while running:
    if keyboard.is_pressed("k"):
        sleep(1)
    elif keyboard.is_presed('Esc'):
        sys.exit()
    else:
        print("hello")

I didnt test it, so please give me feedback

Answered by MercifulSory on November 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP