简体   繁体   中英

Programmatically create a keyboard shortcut in python

I'm creating the setup for a script. I need the setup to include a keyboard shortcut to the script itself. Basically an easy way to do this would be to use Windows 7 equivalent to Ubuntu's bind command. How can I do this in Python?

What I've tried:

I read somewhere that creating a vcst file will allow me to make keybindings, so I tried this:

def run_setup(self):
    with open(self.file_name, 'a+') as vsct:
        vsct.write("""<KeyBindings>
 <KeyBinding guid="esc_tool" id="c:\users\{}\desktop\esc_tool\main.py"
        key1="8" mod1="CONTROL" mod2="ALT"/>
</KeyBindings>
            """.format(getpass.getuser()))

That didn't work.

How can I do this successfully?

EDIT

The above seems a little confusing, so what I want to do is create a keyboard shortcut to a script called main.py from inside of a script called setup.py . So:

python setup.py creates a keyboard shortcut with the keys CNTRL-ALT-8 to a script called main.py . So when the user presses CNTRL-ALT-8 it runs main.py in the Python interpreter.

Do you mind if setup.py is an AutoHotkey script instead, ie setup.ahk ?

Downside: you have to install an extra program ( AutoHotkey ) if you don't already have it.

Upside: the script is tiny:

^!8::            ;defines the shortcut as Ctrl+Alt+8 (Ctrl is ^, Alt is !)
     RunWait, python "C:\Path\To\Your\Script\main.py"
Return

Note: this assumes python is in the PATH environment variable; otherwise use the full path to python.exe in row 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM