MentalCombination
MentalCombination

Reputation: 63

How to pause and resume a while loop in Python?

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?

Upvotes: 1

Views: 5838

Answers (6)

E.MRZ
E.MRZ

Reputation: 91

import keyboard

running = True
display = True
block = False

while running:
    if keyboard.is_pressed("space"):
        if block == False:
            display = not display
            block = True
    else:
        block = False
    if display:
        print("hello")
    else:
        input("Press Enter to continue...")
        if block == False:
            display = not display
            block = True

You can use this to stop and start again.

Upvotes: 0

rouhollah ghasempour
rouhollah ghasempour

Reputation: 124

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

Upvotes: 0

alani
alani

Reputation: 13079

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')

Upvotes: 2

IzZy
IzZy

Reputation: 394

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")

Upvotes: 2

ThRnk
ThRnk

Reputation: 595

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")

Upvotes: 1

MercifulSory
MercifulSory

Reputation: 333

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

Upvotes: 0

Related Questions