0

while(True):

   print("Enter to the bucle")
   with open('the_file.txt', 'w') as f:
       f.write('Hello world!\n')
   f.close()

   #if at some point during the execution of this loop press the letter, for example the key q, that a break is set and the while () loop closes

The problem i found is that if i use an input () and save the key as a string, that would be stopping the loop at the keyboard input wait point, but what i was looking for is that it doesn't have a point where it stops for wait for the keyboard input but simply if at some point the q was pressed, the cycle would end and it would not be executed again

Matt095
  • 857
  • 3
  • 9
  • Does this answer your question? [How to detect key presses?](https://stackoverflow.com/questions/24072790/how-to-detect-key-presses) – Erik McKelvey Dec 16 '21 at 23:43
  • @ErikMcKelvey It could be a partial solution, but in that link what they do is cancel the loop if you hold down the key, here on the contrary I am looking for that if I press (and release) the key that runs the loop and enters the break. In other words, the goal is not to press the key but just to tap it once. – Matt095 Dec 16 '21 at 23:48
  • Remember that even a quick keystroke takes 50ms or 100ms. Unless you're going a long time between checks, you won't miss keystrokes. – Tim Roberts Dec 16 '21 at 23:51
  • If you are on Windows, you can use `msvcrt.kbhit()` to check for keys being queued. – Tim Roberts Dec 16 '21 at 23:53
  • @MatiasNicolasRodriguez You can use `event.type in pygame.KEYUP` to detect when a key is released. That's probably not what you want though because 99.9% of the time when you use a keyboard the event is triggered when the key is pushed down. – Erik McKelvey Dec 16 '21 at 23:53
  • @TimRoberts the while loop takes almost 3 minutes to complete so a solution that involves holding down the key is not a good idea in this case – Matt095 Dec 16 '21 at 23:57
  • @ErikMcKelvey the truth is that I never worked with pygame, but according to what you say it would serve as a temporary basis while I can think of a better solution. But it would be nice if it works with a simple input, since the user does not have to know what works by releasing the key and it is not intended that he is holding the key down for the approximate 1-3 minutes that the cycle will say. – Matt095 Dec 16 '21 at 23:59
  • @MatiasNicolasRodriguez, I am looking at the `title`, you want to interrupt the loop with key input `but without stopping the cycle`. What do you mean by cycle? – ferdy Dec 17 '21 at 00:10
  • @ferdy What I was referring to is that there is not a variable = input () that makes the process hang, but if you do not want to stop it, do nothing. The objective is that when you press the key, the loop is interrupted, but if you don't press it, the loop continues as if nothing had happened. I have tried to detail it in the description – Matt095 Dec 17 '21 at 00:55
  • @MatiasNicolasRodriguez, Do you also want to stop the task inside the loop when q is pressed or you want it to finished first? – ferdy Dec 17 '21 at 02:30
  • @ferdy if it is possible to interrupt the loop where it is, it would be better, but if the execution were to end there would not be too much problem – Matt095 Dec 17 '21 at 07:24

1 Answers1

0

Sample code using threading. We run task in the background and parse user input for key/enter in another thread.

is_interrupt_task = True will interrupt the task otherwise it will not even if main thread has already exited.

Code

import logging
import threading
import time

format = '%(asctime)s: %(message)s'
logging.basicConfig(format=format, level=logging.INFO, datefmt='%H:%M:%S')


def task(name):
    logging.info(f'Thread {name}: starting')
    for i in range(10):
        time.sleep(i)
        logging.info(f'Thread {name}: sleeps for {i}s')

    logging.info(f'Thread {name}: task is completed.')


if __name__ == "__main__":
    # Run task in the background.
    is_interrupt_task = True
    mytask = threading.Thread(target=task, args=(1,), daemon=is_interrupt_task)
    mytask.start()

    logging.info('starting main loop ...')
    while True:  
        userinput = input()
        command = userinput.strip()

        if command:  # almost all keys
            logging.info("main quits")
            break

        # if command == 'q':
            # logging.info("main quits")
            # break

Example task is interrupted

16:12:29: Thread 1: starting
16:12:29: starting main loop ...
16:12:29: Thread 1: sleeps for 0s
16:12:30: Thread 1: sleeps for 1s
16:12:32: Thread 1: sleeps for 2s
16:12:35: Thread 1: sleeps for 3s
q
16:12:36: main quits

Example task is allowed to finish

is_interrupt_task = False

16:11:12: Thread 1: starting
16:11:12: starting main loop ... 
16:11:12: Thread 1: sleeps for 0s
16:11:13: Thread 1: sleeps for 1s
16:11:15: Thread 1: sleeps for 2s
16:11:18: Thread 1: sleeps for 3s
q
16:11:22: main quits
16:11:22: Thread 1: sleeps for 4s
16:11:27: Thread 1: sleeps for 5s
16:11:33: Thread 1: sleeps for 6s
16:11:40: Thread 1: sleeps for 7s
16:11:48: Thread 1: sleeps for 8s
16:11:57: Thread 1: sleeps for 9s
16:11:57: Thread 1: task is completed.
ferdy
  • 4,396
  • 2
  • 4
  • 16