Turn pynput.keyboard.Key key to an ascii value - python

For a project I'm working on I need to send keyboard keys pressed in one computer to another. I managed to find pynput and it works pretty well in detecting which key pressed or released. My problem is that if a not alphanumerical key is pressed it returns an object of the type pynput.keyboard.Key which I couldn't find any way to convert into ascii code. This is how a simple code to detect the use of a key looks like:
from pynput import keyboard
def on_press(key):
print(['pressed', key])
def on_release(key):
print(['released', key])
def detect_keyboard():
keyboard.Listener(on_press=on_press, on_release=on_release).start()
if __name__ == '__main__':
detect_keyboard()
while True:
pass
I would really like to know if there is a way to do so, and if not I would be happy for other ideas how to implement my goal.

I understand that it would be tedious, but you could write a dictionary with the key references returning the ascii values. Eg:
from pynput.keyboard import Key
AsciiKeys = {
Key.backspace:8,
Key.esc:27}
Then you would later be able to reference it to get the ascii values.
You will be able to find all of the current keys here: https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key

Related

pyautogui keydown and keyup arent working properly python

so I'm using pyautogui to type, and I'm trying to hold a key down for more than a second but I've ran into this problem where the key only types a single letter
import pyautogui
import time
pyautogui.keyDown("w")
time.sleep(2)
pyautogui.keyUp("w")
my output is "w"
but my output should be "wwwwwwwwwwwwwww" since I'm holding down the key?
the same thing occurs when im using the press function for pyautogui,
pyautogui.press("w") #but instead of pressing a single key, it totally just doesnt get outputted but only works for main keyboard functions like windowsKey and enter
if this is wrong, is their a way i can make it so I'm holding down the key?
From the Documentation it seems that it's not possible to do the way you have tried, however this function can help for 'holding down' a letter for a set number of seconds:
def hold_character(hold_time, character, interval=0.1):
pyautogui.write(character * int(hold_time / interval), interval=interval)
hold_character(2, 'w')
...gives the 'wwwwwwwwwwwwwww' effect for me

Breaking a loop without ending the program (python)

I have a dictionary with a list of key presses and file names stored in key-value pairs as strings. I want to check if the key pressed is in the dictionary then print the pressed key and the file name associated with it.
My issue is that after I press one key, it keeps looping through the same function and only prints that key. I know I need to stop it from looping, but I don't know how to do that without using "break" or "return" to end the program. The only condition I want the program to end under is if the "esc" key is pressed.
I feel like the answer is ridiculously easy and I'm missing something simple, please help.
Here is my code:
import keyboard
import pygame
# there is more in the dictionary, but it's not much different from what is already pasted here
keys = {"`": "sounds/c2.mp3", "1": "sounds/db2.mp3", "2": "sounds/d2.mp3",}
key = keyboard.read_key()
def sound():
play = keys.get(key, "")
pygame.mixer.init()
pygame.mixer.music.load(play)
pygame.mixer.music.play()
def keypress():
while True:
if key in keys.keys():
if key != "esc":
print(key)
sound()
else:
break
keypress()
I think you need to move key = keyboard.read_key() inside your while loop. (Probably just after while True:)

How can I mask or hide user input in python without using getpass()?

as the question suggest I am looking for a way to hide or mask user input within python without using the standard getpass library due to using spyder; I am wondering if this would potentially be possible using key pressed and recording each key pressed without it displaying until say enter is pressed? If this is possible would someone be able to help me with a snippet for this purpose
Thanks,
Sam Hedgecock
You should take a look at a kind of key-logging mechanism. You could detect which key the user pressed, store those keys in a buffer to finally output them after ENTER is pressed.
Working cross-platform example:
from getkey import getkey, keys
#Buffer holding all the pressed keys
pressed_keys = []
while True:
#Getting the pressed key
key = getkey()
#Appending it to array
pressed_keys.append(key)
#If ENTER is pressed, exit loop
if key == keys.ENTER:
break
#Outputting all pressed keys after ENTER is pressed
for key in pressed_keys:
print(key, end='')
You need to install getkey though. Use pip3 install getkey.

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()
``
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)

How to use keyboard event as part of a conditional statement

I'm trying to make a program that outputs a key press event as a response to another keyboard event. How do I get it to use the particular value of the key pressed in a conditional statement? The codes I try seem to be skipping the conditional statement altogether.
Initially tried [if key == '1':], then tired by [if key == 1:]. Also tried various means of assigning [key] to a variable. Also tried [print('2')] instead of using [pyautogui.typewrite('2')]. Tried putting the code both in on_press(key) and in on_release(key).
`
import pyautogui
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(key))
def on_release(key):
print('{0} release'.format(key))
k = format(key)
if k == '1': #THIS IS THE PART I CAN'T GET TO WORK
pyautogui.typewrite('2', 0.5)
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
`
Expected to output '2' whenever I press '1' on the keyboard(in addition to the output of the keypress and keyrelease event). The output for the pressing of '1' doesn't work.
You can use keyboard library, in order to handle/create key events.
while True:
try:
if keyboard.is_pressed('1'):
print('{} is pressed'.format(1))
break
else:
pass
except:
break
the above code runs until 1 is received as a keypress. Upon pressing the key, 1 is pressed will be printed.
You can further use other functions of this library, in order to detect a key down even too.
The key parameter that your on_press/on_release receives is not the character string but rather a Key/KeyChar object, that's why you can't compare it directly with a string.
To access the keyboard input character, use key.char instead:
def on_press(key):
print("pressed '{}'".format(key.char))
Look at the example codes on pynput's documentation on how to capture non letter keys.

Categories

Resources