Search code examples
pythonkeyboard

I cant get keyboard.wait to continue with the code after pressing a key


I'm making a script in python that shouldn't continue with the script until after I've pressed a certain key (in this case that key is Y) but every time I get to that part of the script and press the key it just ends the program prematurely. I don't quite know if I'm missing something or just being mildly retarded.

import random
import time
import keyboard

loop = True
while loop == True:

north = random.randint(0,90)
south = random.randint(0,90)
west = random.randint(0,180)
east = random.randint(0,180)
nors = random.randint(0, 1)
eorw = random.randint(0, 1)

Snorth = str(north)
Ssouth = str(south)
Swest = str(west)
Seast = str(east)

if nors == 1:
    print("north: " , Snorth)
    time.sleep(.5)

else:
    print("south: " , Ssouth)
    time.sleep(.5)

if eorw == 1:
    print("west: " , Swest)
    print("Again?")
    if keyboard.wait('"y"'):
        print("test")
        loop = True
        time.wait(5)

    else:
        loop = False

else:
    print("east: " , Seast)
    print("Again?")
    if keyboard.wait("y"):
        print("test")
        loop = True
        time.wait(5)

    else:
        loop = False

Solution

  • I think you might be looking for the keyboard.read_key() function instead, as keyboard.wait() only blocks execution until the key is pressed, and returns a NoneType which fails in your if-else statement.

    while loop:
        north = random.randint(0,90)
        south = random.randint(0,90)
        west = random.randint(0,180)
        east = random.randint(0,180)
        nors = random.randint(0, 1)
        eorw = random.randint(0, 1)
    
        if nors == 1:
            print("north: " , str(north))
        else:
            print("south: " , str(south))
    
        if eorw == 1:
            print("west: " , str(west))
        else:
            print("east: " , str(east))
    
        print("Again?")
        if keyboard.read_key() == "y":
            loop = True
        else:
            loop = False
    

    From the documentation (https://github.com/boppreh/keyboard#keyboardread_keysuppressfalse):
    keyboard.read_key() blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code.