-1

Not sure what's wrong here, function's not printing anything (tried '1' as argument i). I've seen an answer suggesting adding flush=True to print, but that doesn't solve the issue. Any hints appreciated! More broadly - should I even be using the try/except framework if I want the function to be keyboard-controled, or is there a better way?

def i_printer(i):
    while True:
        try:
            if keyboard.is_pressed('q'):
                break
        except:
            print(i)
            time.sleep(3)

EDIT: using Windows, apparently keyboard doens't work with it, looking for different solution.

the_dude
  • 61
  • 7

2 Answers2

0

Try and except blocks are used to handle exception. Since you are not going to face any error when clicking 'q', I don't think the usage of them is any good here. Just simple if statement would do the job.

def i_printer(i):
    while True:
        if keyboard.is_pressed('q'):
            break
        print(i)
        time.sleep(3)

EDIT: In case you wanna record keyboard press try this out. The following code will record all the keys except 'q' and print recorded keys.

import keyboard

def i_printer():
    rk = keyboard.record(until ='q') 
    return keyboard.play(rk, speed_factor = 1) 

i_printer()
Rustam Garayev
  • 2,632
  • 1
  • 9
  • 13
  • The problem with this is, I'm not getting any reaction when i press q, it's just looping away. – the_dude Feb 06 '21 at 19:50
  • then check if input character is 'q' instead of doing keyboard.is_pressed('q') – Rustam Garayev Feb 06 '21 at 19:53
  • Apologies, I'm reading through the docs for keyboard and having a hard time finding the one you had in mind, could you point me in the right direction? – the_dude Feb 06 '21 at 20:02
  • @AndrzejK, I edited answer, check if this is what you are looking for. – Rustam Garayev Feb 06 '21 at 20:04
  • the function stops executing once I press q, but does not print out all the other keys I pressed, as it should. Might be that I'm using Windows not Linux? There's mention of it here:https://stackoverflow.com/questions/24072790/detect-key-press-in-python ("keyboard apparently requires root in linux :/") – the_dude Feb 06 '21 at 20:18
  • Well, I am using MacOS and it worked perfectly. I don't really know if it is because you are using Windows or something, since there is no limitation pointed out in the documentation for Windows for this case. Also, are you obligated to use keyboard module? – Rustam Garayev Feb 06 '21 at 20:28
  • No, I'm not obligated, I'll try with pynput as suggested in that other thread. – the_dude Feb 06 '21 at 20:31
0

Got the ball rolling this way, with a generator function and an iterator (using windows, not linux):

import keyboard
import time

def printer():
    while True:
        yield '1'
        time.sleep(1)

def iterator():
    for i in aaa():
        if keyboard.is_pressed('q'):
            break
        else:
            print(i)

iterator()
the_dude
  • 61
  • 7