Create Keyboard Shortcut? - python

I am searching for a way to create a cross-platform keyboard shortcut in Python. Such that when I press something like Ctrl+C or Ctrl+Alt+F, the program will run a certain function.
Does there exist such method or library?

I don't know is it possible to send combinations of Ctrl and/or alt. I tried couple of times but I think it doesn't work. (If someone has any other information please correct me). What you can do is something like this:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
PrintSomething()
def PrintSomething():
print('Printing something')
this will run a scrpit every time you press ESC although it will only work when you run it in command prompt.

You can create a listener for keypress event by pynput library.
this is a simple code that run a function when press CTRL+ALT+H keys:
from pynput import keyboard
def on_activate():
print('Global hotkey activated!')
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()

Try keyboard. It can be installed with pip install keyboard, and the Ctrl + C example can be accomplished with the syntax:
import keyboard
keyboard.add_hotkey("ctrl + c", print, args=("Hello", "world!"))

Related

Detect enter key pressed python

is there a way to detect if ENTER is pressed with python? I was able to detect letters with win32api using win32api.GetAsyncKeyState(ord('H')) , but couldn't do the same with enter. I need to run the code on windows.
Thanks.
You can use keyboard lib.
pip3 install keyboard
import keyboard
if keyboard.read_key() == "enter":
...
https://github.com/boppreh/keyboard

Make auto key and mouse press on activate window on Python

I want to write an app in Python on Windows to do some jobs repeatedly.
For example, I need to convert some files into other type. I have a software installed in Windows to do that. However, that program was designed to do it file by file. Now I want to do it automatically.
Therefore, I need to write a software to simulate the key press on active windows. There are a lot of code on autokeyboard but it only works in terminal which run Python script. Specially, after I run Python script, I minimize the terminal, then open some program then the Python script will simulate the key press and/or mouse click in this program.
I found a lot of program can do something like hotkey and after press hotkey, it will simulate some key press and mouse. So I think it is possible.
Could anyone give me a solution for that?
Thanks.
This will help you to automate:
for mouse clicks:
import pyautogui
pyautogui.click(1319, 45)
pyautogui.scroll(200)
pyautogui.hotkey("ctrlleft", "a")
For keyboard
import keyboard
# It writes the keys r, k and endofline
keyboard.press_and_release('shift + r, shift + k, \n')
keyboard.press_and_release('R, K')
# it blocks until esc is pressed
keyboard.wait('esc')
# It records all the keys until escape is pressed
rk = keyboard.record(until='Esc')
# It replay back the all keys
keyboard.play(rk, speed_factor=1)

Detect keyboard press

I want to make a program that runs a code when you just click on a button on a keyboard for example, I press A and some code runs, but I do not have to press enter or input it to run it. Just like in video games, your character moves if you press W. Sorry if it is worded badly, I am pretty confused about this.
Keep in mind please it's Python 2.7
I am assuming you mean in the console and not in any gui like tkinter or something.
I'd suggest using pynput (pip install pynput)
with code similar to this
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
while True:
with Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
word of warning:
The above code also catches exit keys so ctrl + c will not stop the console. for that you would need to implement something to break out of the While loop when ctrl+c is pressed.

Python get keyboard input without getting stuck

I'm making a python program that changes my wallpaper every hour, but i want to be able to also change the wallpaper when i press a certain button.
this is the code i've tried
while True:
key = ord(getch())
but the only bad part is that it gets stuck on that until i press something. Is there a better way to do this?
You may be able to achieve what you want by using https://pypi.python.org/pypi/pynput.
See also its docs on pythonhosted http://pythonhosted.org/pynput/, especially the section about monitoring the keyboard http://pythonhosted.org/pynput/keyboard.html#monitoring-the-keyboard.
The following is an example from the docs:
from pynput.keyboard import Key
from pynput.keyboard import Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
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()
It will print every key you press until you press ESC, after which it will terminate.
Note that there are some operating system specific things to consider, for example on OSX the process must run as root.
I somehow accidentally found this.
import msvcrt
if msvcrt.kbhit():
Key = ord(getch())
if Key ==96:
#Do something here
And that seems to work. I think msvcrt.kbhit() is waiting for an keypress. Key = ord(getch()) takes the keypress and if Key ==96: checks if its the right keypress

Code that recognises a keypress in Python 3

Is there anyway for python 3 to recognise a keypress? For example, if the user pressed the up arrow, the program would do one thing whereas if the down arrow was pressed, the program would do something else.
I do not mean the input() function where the user has to press enter after the keypress , I mean where the program recognises the keypress as some as it was pressed.
Is this question too confusing? xD
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('up'): #if key 'up' is pressed.You can use right,left,up,down and others
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
It Also Detect Key For The Whole Windows.
Thanks.
I assume this is a gui program,
If using the built-in gui module Tkinter, you can use bind to connect a function to a keypress.
main.bind('<Up>', userUpkey)
Where userUpKey is a function defined in the current scope.

Categories