Search code examples
pythonuser-inputpynput

How can I ignore all user inputs for duration of function run?


I have a Python module that listens for a key combination using pynput then, once it's pressed, it types a string into a text program.

It works great! Except...

In the example below, the user's key combo is set to shift + space. This makes a lot of sense and will likely be the most common chosen key command for Windows users running my program. The trouble is, while the shift key is held down it changes what pynput types. Instead of 01/20/2019, it will type )!/20/2019.

I need a way to disable the keyboard until pyautogui is finished typing the string. Thanks a lot for your help!!!

Bonus question: I can't seem to get a result when the key combination includes a ctrl key. Key.ctrl simply fails to ever trigger, whilst other keys work fine.

from pynput.keyboard import Key, Controller, Listener
import time

keyboard = Controller()

def insert():                                 # check line 1 of config file 
     keyboard.type('01/20/2019')

# The currently active modifiers
current = set()

def on_press(key):
    if key in COMBINATION:
        current.add(key)
        if all(k in current for k in COMBINATION):      # I don't know what this k in current for k shit is.
            current.remove(key)
            insert()                                # run insert

    if key == Key.esc:
        listener.stop()


def on_release(key):
    try:
        current.remove(key)
    except KeyError:
        pass

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
``

Solution

  • You can use pyautogui.keyUp("shift") before you type.

    def insert():
    f=open('tc.txt')
    line=f.readlines()
    insert.timestamp=(line[0])
    time.sleep(.1)
    pyautogui.keyUp("shift")
    pyautogui.typewrite(insert.timestamp)