Good morning,
I am using Python's 3.8 pynput (in windows 10) to get each time the character entered (in system level) and then the unicode of this character.
from pynput import keyboard
def on_press(key):
if key == keyboard.Key.esc: #if button escape is pressed close the program
listener.stop()
else: #if button escape is not pressed get the unicode code of the button-char pressed
unicode_code = ord(getattr(key, 'char', '0'))
print("The unicode is ",unicode_code)
print("The char entered is",chr(unicode_code))
controller = keyboard.Controller()
# Collect events until released
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
The problem I am facing is that when I change my keyboard to greek (with shift+alt), it keeps the unicodes of the english language and not the greek ones.
You can see the screenshot attached to understand better.
What to do to overcome this problem?
No, you aren't getting English unicode codes. You are getting unicode representation of codes returned by the keyboard. They will be the same no matter what language is chosen because keyboard layer is designed to always return same codes for same keys (by their location and/or meaning on querty/quertz or other HID compliant keyboards) if possible. What you are doing in your code is essentially reverting the process done by pynput which converts the keyboard code using char()/unichar() function. Think about it: is there a greek representation of e.g. F11 key?
I cannot remember whether pynput has higher-level inputs support or not, although I think it does. and that it should be possible to get directly what you want
What you have to do is either to find another attribute (if there is one, I am not pynput specialist) containing the character sent to the input field, or check the current keyboard language and appropriately map the codes returned. You can also try playing with codepages using the codecs module. Worst case scenario would include snatching the character directly from the GUI's input field. But that would be very inelegant, bruteforc-ish and simply the shouldn't do it thing if not strictly necessary. There are other methods for getting input from the OS - like directly linking to its event input system or kernel using built-in libraries through ctypes, wintypes, Cocoa/Carbon on Mac or GTK on Linux.
Try using pynput version 1.1.7, it works there. It is broken after 1.4 and in between these two it works, but changing the layout with the windows shortcut while the program is running, isn't working 70% of the time, meaning Windows just doesn't change the language. Alternatively, you can work around it in newer verisons by trying this solution, that converts the characters in real time if you don't care about performance. I have opened an issue for it to be fixed in the repo's github.
Related
is there a key to detect when the terminal is focused?
For example the KEY_RESIZE is used to detect when the terminal is resized.
Thanks
There's no predefined key, but with ncurses it is possible to define keys as done in the examples xterm-1002 and xterm-1003, which use this xterm feature
xterm+focus|xterm focus-in/out event "keys",
kxIN=\E[I, kxOUT=\E[O,
documented in XTerm Control Sequences. There's no predefined keycode, but a program could
ask ncurses for the string corresponding to "kxIN" with tigetstr (noting that 0 and -1 are special values denoting failure),
tell ncurses that this is really a key that getch should report as a keycode, using define_key, and
use key_defined to retrieve the resulting keycode.
The ncurses test-program demo_defkey uses define_key and key_defined to demonstrate how to use these functions. That's in C, of course. From python that's also doable (see for example this).
Other terminals implement a subset of xterm's control sequences. OP comments about foot, which happens to recognize mode 1004 (focus in/out). One could make a customized terminal description
foot-focus|foot with focus-in/out,
use=xterm+focus, use=foot,
and use tic to compile that. (Starting with the terminal description for foot is recommended; just setting TERM=xterm-1002, etc., tends to lead to disappointment on the part of users).
I want my configuration menu to open at the start of a script if the Ctrl key is being pressed. That is, the user would start pressing the key before the script starts running.
To intercept that I have tried keyboard.is_pressed('ctrl'), but it always returns false.
I have also tried keyboard.read_key but this method gives me two problems:
If it is not pressed, the program does not continue running.
If it is pressed, it just continues running only when I release the control key.
Maybe I just need to think of another way to open this menu.
I'm assuming you're using the keyboard module for this. Looking through the code, it seems like that library is event based, so if the CTRL key is pressed before your program starts, then it isn't recognized by the program.
My recommendation would be to read directly from stdin using the sys library. However, looking at How to get Ctrl, Shift or Alt with getch() ncurses?, it seems like CTRL, ALT, and SHIFT don't generate their own input to stdin but rather modify existing input, so you should probably look at using another key as your modifier. You also need a timeout, which Read file with timeout in Python suggests the select module provides. In case you don't know already, sys.stdin is your standard input, and you can treat it like any other file.
Assuming my code is going to run on Windows and thanks to my experience in C++ I came up with the win32api module.
# Windows module to controll the keyboard
import win32api
# Windows module with every key code
import win32con
# Check whether the control key is pressed
if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000 > 0:
# Do stuff
Is there a way to disable (keyboard) input on windows with python. I would like to convert this program to exe and the
from ctypes import *
ok = windll.user32.BlockInput(True) #enable block
method is not suitable for that (as it needs admin privileges). I looked at other articles with described how using the pyHook would work. Unfortunatelly this method is a bit old and does not work for me anymore, it just makes the mouse and keyboard lag a little bit.
There is a working method by just putting keystrokes (from for example the pynput library) in a while loop, so it just spams keystrokes and the user can not overwrite this by typing lets say alt+f4. This is a very dirty way and I would like a cleaner way(this method causes the computer to lag for a minute because it cant comprehend that amount of input in such a short time)
#### Blocking Keyboard ####
import keyboard
#blocks all keys of keyboard
for i in range(150):
keyboard.block_key(i)
I am using Linux Mint 20 with Python 3. I am a complete noob with Python. However, I am trying to set up a keyboard shortcut to display certain text wherever my cursor is at in the active window (an input box, text editor, etc.). I know how to set up shortcuts and run simple python programs in Terminal.
It seems I have to use some type of GUI interface? I have looked at GTK and pkinter, but I can't seem to figure out the correct code. Would rather use GTK or something that already comes with the system.
Thanks.
You can use the pynput module to make keypresses wherever the cursor is. Here is an example:
import pynput
from pynput import keyboard
string_to_type = "Hello! How are you?"
c = keyboard.Controller()
for char in string_to_type:
c.tap(char)
c.tap() presses and then quickly unpresses the key passed as an argument.
You can also call c.press() and c.unpress(), both of which require an argument representing a key. This enables you to hold down keys.
I have a problem, that consists in following: Pyautogui typewrite won't type letters, only numbers. For example, when I execute
pyautogui.typewrite("abc123")
only "123" appears.
This question is similar to this one:
Pyautogui typewrite is writing only numbers
Unfortunately, there are no answers about the issue, as well as other Internet topics.
I have the Windows 7 machine and Python 3.5.
There seems to be a bug in the typewrite function of PyAutoGui. I workaround it with this function which preprocesses the string into keypresses instead. Note that this version of the function leaves a comma at the end of the output array so that you can easily append more characters or button presses at the end.
def preprocess(something):
something = str(something)
output = []
for x in range(len(something)):
output.append(something[x])
output.append(',')
return output
I faced the same problem. I was not able to send letters using typewrite() function.This bug in PyAutoGUI can be overcome by installing OpenCV 3.1.0
Download openCV 3.1.0 from below site:
1) https://sourceforge.net/projects/opencvlibrary/files/opencv-win/3.1.0/opencv-
3.1.0.exe/download
2) Extract the OpenCV -> Then go to OpenCV\build\python\2.7\x64 and copy cv2.pyd to C:\Python27\Lib\Site-packages
And your problem will be solved. Give it a try, it worked for me
I had the same problem couple of days ago
Try using other pyautogui functions that presses keyboard keys like pyautogui.press("k")
If you have a problem with all keyboard functions related to letters in general it's probably because your default input language is set to something other than english
you can fix that easily by going to your keyboard and input settings and changing the default input language to english
you'll still be able to write in your first language and it will hopefully solve your problem