printing key presses to the screen instantly with python - python

I know this question is long but what I really want to know is in bold.
I would prefer to use python on Linux.
I'm trying to make a new keyboard layout kind of like devorak but the layout is set to either layout1 or layout2 depending on if you are holding a hot key or not (the hot key should probably be ctrl?)
e.g. press d -> "z" prints to the screen using key layout1
e.g. press ctrl d -> "x" prints to the screen using key layout2
My main problem (and question that needs answering) is the way characters need to print to the screen.
if someone presses the keys (in this order) "(a)(b)(c)(d)(ctrl+d)(shift+e=E)(f)(Enter)"
now lets say the output for these key presses should be "oijzxKb"
I don't want output to render with new lines:
o
i
j
z
x
K
b
I want the characters to appear instantly on the screen as each character is pressed (without waiting for them to press enter).
e.g.
press o
Screenshot1 o
press i
Screenshot2 oi
press j
Screenshot3 oij
.. etc
I assume I will need the following:
a way to read keypresses instantly
a way to print key presses instantly (to the terminal or a GUI or whatever is easiest initially, if it worked on any editor that would be cool!)
I could probably do this in PyGame (but then I probably wouldn't be able to cut and paste etc) and I'm guessing there should be an easier way.
I'm using a Logitech G110 keyboard, I may eventually want to use this as an alternative to my qwerty keyboard on all my applications across all my devices.
Thanks!
EDIT: SOLUTION:
Thanks to the first response,
using Getch from http://code.activestate.com/recipes/134892/
getch = _Getch()
word=""
while True:
c=getch.impl()
if c=="a":
word+="z"
elif ord(c)==127: #backspace
word=word[:-1]
else:
word+=c
print word
This will suffice for now thank you. Once I'm happy with refinement I'll look at doing something lower level, operating system specific without python.
One problem with getch however is that ctrl+a cant be distinguished between ctrl+A (e.g. if you hold ctrl and press keys, it can't tell the difference between upper and lower case)

If it's ok to depends on the X window system, you can use the python-xlib module or the xpyb module to access the X window system and use a XGrabKey call to grab the keyboard related events. Upon each KeyPress event you will be able to print the pressed key.
Now, if you really want to write a keymap, this is totally OS/window system dependent. If you use the X window system (Ubuntu does), you need to check the X documentation about how to write a new keymap. On Ubuntu, the current keymaps definition should be in /usr/share/X11/xkb. Take a look, and try to copy and edit one. You can use setxkbmap to change the current keymap then.

To modify the key mapping of your keyboard, you must use the tools provided by your OS. Most applications don't accept generated events for security reasons.
In your case, that would be xmodmap. Don't forget to create a backup of your current keymap using the -pke option because you will make a mistake - and then, your keyboard won't be working anymore.
If you also want your new keymap work on the console, have a look at the kbd package which changes the keyboard layout at the kernel level.

Related

PyAutoGUI seems to ignore numpad key presses

I'm using Windows, Python, and PyAutoGUI to try to automate some activities in Minecraft as a fun project.
I have been successful with using PyAutoGUI to switch to Minecraft once I start the script in Visual Studio Code, click on the "Back to Game" button, and then move the avatar forward by holding the "w" key.
I am using a 3rd party program called "NeatMouse" to use my numpad keys in place of using a mouse. The numpad 8 button is equivalent to moving the mouse up, which in Minecraft causes your avatar to look up. When I press this button myself in Minecraft, it works as expected, so it must be the case that NeatMouse is not the problem.
When I try to have PyAutoGUI replicate this same key press, it seems like nothing is happening.
I have tried different combinations of
pag.press()
pag.hold()
pag.keyDown() & pag.keyUp()
These functions do work for the WASD keys, so I know that Minecraft is able to receive keyboard input from PyAutoGUI, so that generally must not be the problem.
Here is a sample code block of what I have tried.
import pyautogui as pag
def align_vertical_facing_axis(target):
facing = get_facing_axes()[1]
# Looking down
if facing > target:
print('torture')
pag.keyDown('num8')
sleep(1)
pag.keyUp('num8')
get_facing_axes() is a function I wrote to retrieve the axes the avatar is facing as a tuple from the Minecraft debug screen. A positive value in the [1] index means the character is looking at a downward angle. When I run this script, it does print "torture" to my console so I know for sure it is entering that "if" block.
That was the long version of the explanation, the short version is: PyAutoGUI won't press the numpad keys, what do??
After some research, pyautogui.platformModule contains the mappings for numpad.
Here are the windows key mappings: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
import pyautogui as pag
#This is where you update key mappings, num8 is now referring to the virtual key code VK_NUMPAD8 or 0x68
pag.platformModule.keyboardMapping.update({'num8':0x68})
#To call it, you use the mapping name you gave to the virtual key code
pag.press('num8')
Use the list I gave you for other key mapping values such as 0x68 for num8 and so on.

Psychopy in python : having two answers once when the key is pressed and the second when is released

I need to modify a script in psychopy. The thing I need is the subject to press and hold a buttom in the keyboard, but I'd like to have two responses: one when he/her presses it (and the windows with text has to change), and the second when he/her releases it (and the windows with text has to change again).
I am using event.getKeys function of psychopy, and then I'm using keyboard library.
after inizializing the window screen and the text and importing psychopy and the functions I need and keyboard library as key.
intro.draw()
win.flip() # reset the clock to record a response time and clear events
event.clearEvents('all')
event.globalKeys.clear() #to avoid problems with the keys you pressed before
intro_loop = True
while intro_loop:
intro_keys = kb.getKeys(["space"], waitRelease=True)
if key.is_pressed('space'):
intro.text = 'Hi, please follow these instructions :) '
intro.draw()
win.flip() # reset the clock to record a response time and clear events
if len(intro_keys):
win.close()
intro_loop = False
I did the same in another script (just to try) but instead of having a window text screen I printed two different things, and it worked. in this script, instead, it completely ignores the function "key.is_pressed".
do you have any ideas?

Execute Key Sequence on Button Click

I'm trying to create an Undo and Redo Button inside a GUI App using PyQt5 and Python 3.7.
When the Undo and Redo Buttons are clicked, the Key Sequences "Ctrl+Z" and "Ctrl+Y" should be executed respectively. Ive superficially gone through the documentation of QShortCut and QKeySequence but they seem to be designed for detecting key sequences and not triggering them. So how do I implement these buttons?
As per eyllanesc's comment, I'm adding this to better explain what I am trying to achieve.
self.undoButton = self.findChild(QtWidgets.QPushButton, 'undoButton')
self.undoButton.clicked.connect(self.undoButtonPressed)
self.anyPlainTextEdit = self.findChild(QtWidgets.QPlainTextEdit, 'anyPlainTextEdit')
# Function to Execute Key Sequence
def undoButtonPressed(self):
# Execute Ctrl+Z Key Sequence
I'm wondering if this is even possible.
If not, should I maintain Previous and current values of the PlainTextArea in separate variables and set the value of the PlainTextArea accordingly?
You don't have to launch the shortcut to enable redo or undo, just call the slot redo() and undo() when the buttons are pressed:
self.undoButton.clicked.connect(self.anyPlainTextEdit.undo)
self.redoButton.clicked.connect(self.anyPlainTextEdit.redo)

How to specify input language for Entry or any other input field?

In short, i try to type letters (in input components like "Entry", "Text") that are allowed by Windows language-keyboard (i'm using "Latvan(QWERTY)" keyboard) and i can't write long letters like 'ā', 'č', 'ģ' and others.
For example, when i try to write 'ā', the result is 'â'.
The interesting part - when i focus on specific GUI input fiend and change Windows keyboard-language (with "Alt+Shift" shortcut or manually) twice (for example, from "Latvan(QWERTY)" to "Russian" and back to "Latvan(QWERTY)") - then i can write all letters i needed.
What i want is to set all input fields keyboard-language so i could write all letters i want without doing things mentioned above every time i launch my GUI program.
If you need more info or there is already place where this question is answered, please leave a comment and i will act accordingly.
Edit 1:
I am using PyCharm to write my Python Tkinter code. I tried to assign necessary keyboard to my program's generated GUI form according to this guide but it didn't work (i guess that because i used it on temporary created GUI forms).
I was able to solve my problem by using pynput.
Here is simplified version of my final code:
from tkinter import *
from pynput.keyboard import Key, Controller
def change_keyboard_lang(event):
keyboard = Controller()
for i in range(2):
keyboard.press(Key.alt)
keyboard.press(Key.shift_l)
keyboard.release(Key.shift_l)
keyboard.release(Key.alt)
root = Tk()
word_input = Entry(root)
word_input.focus_set()
word_input.bind("<FocusIn>", change_keyboard_lang)
word_input.pack()
root.mainloop()
In short, if cursor is focused on Entry field "word_input", system calls function "change_keyboard_lang" that changes input language from original to other and back to original - and now i can write necessary letters.
It's not the best solution since i need to bind event to every input field in my GUI form but it gets the job done. If you have a better solution please post it here.

Pressing keys with python win32api

I am trying to achieve the following behavior in a PYTHON 2.4 script, here are the steps, and after them, the question:
Python script starts
The script gives a 3 seconds delay to change to 'Z' program's window
The script does some clicks on the 'Z' program's window.
The script stops making clicks
/* ¿? */
Ask to continue with the program's excecution
/* ¿? */
Go to step 2
So, in steps 5 and 7 what I want to do is simulate the pressing of keys Alt+Tab in order to go back to the script window (in step 5), and go back again to the 'Z' program's window (in step 7).
And the problem is that I have no idea how to achieve this (the simulation to press keys alt+tab), and didn't find answers to my doubts.
I am using the python win32api modules to positionate mouse in a certain point and make the clicks, but I don't find the way to simulate the key pressing.
Try This :
1) Use : https://gist.github.com/chriskiehl/2906125
2)
import win32api
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("app")
win32api.Sleep(100)
shell.AppActivate("myApp")
win32api.Sleep(100)
shell.SendKeys("name")
win32api.Sleep(500)
shell.SendKeys("{ENTER}")
win32api.Sleep(2500)
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text? Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever
You need the WinApi function SendInput.
See the description in the MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx
An Easier Way
Use this Library W32S
My Library.
And If u want , just copy the source instead

Categories

Resources