AnswerBun.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!

Related Questions

Appending a list in a list using a for loop

2  Asked on November 22, 2021 by syed-ahmed

 

Regular expression to find Specific character in a string

4  Asked on November 22, 2021 by user3061338

       

laravel count records based on each single date

1  Asked on November 22, 2021 by gulzar-ali

       

Change one property in CSS

2  Asked on November 22, 2021 by darek

 

Splitting values in a list and making variables of them

1  Asked on November 22, 2021 by premier12

     

JSX fragment has no corresponding closing tag

1  Asked on November 22, 2021 by chinwe-watkins

   

How to slow down window.location.href on AJAX request

3  Asked on November 22, 2021 by agiftel-longwave

     

Why list initialization disallow narrowing?

0  Asked on November 22, 2021 by alan-jian

   

How can i remove object from nested array?

2  Asked on November 22, 2021 by trajce12

 

How to save model architecture in PyTorch?

3  Asked on November 22, 2021

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir