Search code examples
pythonwhile-looppynput

How to print list elements one by one by keypress on python


I want to print on the console each word in a sentence, but only when the spacebar is pressed by the user, like this: at the begging nothing happens; then the user press the spacebar and the first word appears and stays there; then he/she presses the spacebar again and the second word appears; and so on:

<keypress> This <keypress> is <keypress> my <keypress> sentence.

I've written the code bellow, but I could only make all the words appear simultaneously.

import pynput
from pynput.keyboard import Key, Listener

sentence = 'This is my sentence'

def on_press(key):

    if key == Key.space:

        i = 0
        while True:

            print(sentence.split()[i])
            i = i + 1

            if i == len(sentence.split()):
                break

    elif key == Key.delete:  # Manually stop the process!
        return False

with Listener(on_press=on_press) as listener:
    listener.join()

Thank you for your help.


Solution

  • import time
    from pynput.keyboard import Key, Listener
    
    SENTENCE = 'This is my sentence'
    index = 0
    stop = False
    
    
    def on_press(key):
        global index, stop
        if key == Key.space:
            if index < len(SENTENCE.split()):
                print(SENTENCE.split()[index])
                index += 1
            else:
                stop = True
        elif key == Key.delete:  # Manually stop the process!
            stop = True
    
    
    with Listener(on_press=on_press, daemon=True) as listener:
        while listener.is_alive() and not stop:
            time.sleep(2)