简体   繁体   中英

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?

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

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

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

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: 在此处输入图像描述 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: 在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM