简体   繁体   English

在python中以编程方式创建键盘快捷方式

[英]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. 基本上,一种简单的方法是使用与Ubuntu的bind命令等效的Windows 7。 How can I do this in Python? 如何在Python中执行此操作?

What I've tried: 我尝试过的

I read somewhere that creating a vcst file will allow me to make keybindings, so I tried this: 我在某处读到,创建vcst文件将允许我进行键绑定,因此我尝试了以下操作:

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 . 上面的代码似乎有些令人困惑,因此我想做的是从名为setup.py的脚本内部创建main.py脚本的键盘快捷键。 So: 所以:

python setup.py creates a keyboard shortcut with the keys CNTRL-ALT-8 to a script called main.py . python setup.py创建一个键盘快捷键,其键CNTRL-ALT-8指向名为main.py的脚本。 So when the user presses CNTRL-ALT-8 it runs main.py in the Python interpreter. 因此,当用户按下CNTRL-ALT-8时, main.py在Python解释器中运行main.py

Do you mind if setup.py is an AutoHotkey script instead, ie setup.ahk ? 您介意setup.py是否是AutoHotkey脚本,即setup.ahk吗?

Downside: you have to install an extra program ( AutoHotkey ) if you don't already have it. 缺点:如果尚未安装其他程序,则必须安装该程序( AutoHotkey )。

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; 注意:这假定python在PATH环境变量中; otherwise use the full path to python.exe in row 2. 否则,请使用第2行中python.exe的完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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