如何像在 autohotkey 中一样在 python 中编程热字符串 [英] How to program hotstrings in python like in autohotkey

查看:37
本文介绍了如何像在 autohotkey 中一样在 python 中编程热字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中制作热字符串,在经过一些处理后将输入的一个单词转换为另一个单词,因为 AHK 在确定要输入的单词时非常有限.现在,我正在 ahk 中使用一个热字符串,它在命令行上运行代码,该代码运行一个 python 脚本,并将我输入的单词作为参数.然后我使用 pyautogui 来输入这个词.但是,这非常慢,并且在快速打字时不起作用.我正在寻找一种使用 python 而无需 ahk 的方法来完成这一切,但我还没有找到在 python 中执行热字符串的方法.例如,每次我输入test"这个词时,它用测试"代替.谢谢你的帮助.我正在运行最新版本的 Python 和 Windows 10,如果这对任何人都有用的话.

I want to make hotstrings in python that converts one word when typed into another after some processing, since AHK is very limiting when it comes to determining which word to type. Right now, I am using a hotstring in ahk that runs code on the command line that runs a python script with the word that I typed as arguments. Then I use pyautogui to type the word. However, this is very slow and does not work when typing at speed. I'm looking for a way to do this all with python and without ahk, but I have not found a way to do hotstrings in python. For example, every time I type the word "test" it replaces it with "testing." Thanks for your help. I'm running the latest version of Python and Windows 10 if that is useful to anyone by the way.

推荐答案

(如果你想在输入每个字母时处理它(t,te,tes,test),你应该编辑你的问题)

(if you want to process it as each letter is typed(t,te,tes,test), you should edit your question)

我使用 ahk 热键调用我的 SymPy 函数.我将 python 脚本注册为 COM 服务器并使用 ahk 加载它.
我没有注意到任何延迟.

I call my SymPy functions using ahk hotkeys. I register the python script as a COM server and load it using ahk.
I do not notice any latency.

你需要 pywin32,但不要使用 pip install pywin32
https://github.com/mhammond/pywin32/releases
下载否则它不适用于 AutoHotkeyU64.exe,它仅适用于 AutoHotkeyU32.exe.
确保下载 amd64,(我下载的是 pywin32-300.win-amd64-py3.8.exe)
原因如下:如何注册 64 位 python COM 服务器

you'll need pywin32, but don't download using pip install pywin32
download from https://github.com/mhammond/pywin32/releases
OR ELSE IT WON'T WORK for AutoHotkeyU64.exe, it will only work for AutoHotkeyU32.exe.
make sure to download amd64, (I downloaded pywin32-300.win-amd64-py3.8.exe)
here's why: how to register a 64bit python COM server

toUppercase COM server.py

toUppercase COM server.py

class BasicServer:
    # list of all method names exposed to COM
    _public_methods_ = ["toUppercase"]

    @staticmethod
    def toUppercase(string):
        return string.upper()
        
if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Error: need to supply arg (""--register"" or ""--unregister"")")
        sys.exit(1)
    else:
        import win32com.server.register
        import win32com.server.exception

        # this server's CLSID
        # NEVER copy the following ID 
        # Use "print(pythoncom.CreateGuid())" to make a new one.
        myClsid="{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}"
        # this server's (user-friendly) program ID
        myProgID="Python.stringUppercaser"
        
        import ctypes
        def make_sure_is_admin():
            try:
                if ctypes.windll.shell32.IsUserAnAdmin():
                    return
            except:
                pass
            exit("YOU MUST RUN THIS AS ADMIN")
        
        if sys.argv[1] == "--register":
            make_sure_is_admin()
                
            import pythoncom
            import os.path
            realPath = os.path.realpath(__file__)
            dirName = os.path.dirname(realPath)
            nameOfThisFile = os.path.basename(realPath)
            nameNoExt = os.path.splitext(nameOfThisFile)[0]
            # stuff will be written here
            # HKEY_LOCAL_MACHINESOFTWAREClassesCLSID${myClsid}
            # HKEY_LOCAL_MACHINESOFTWAREClassesCLSID{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}
            # and here
            # HKEY_LOCAL_MACHINESOFTWAREClasses${myProgID}
            # HKEY_LOCAL_MACHINESOFTWAREClassesPython.stringUppercaser
            win32com.server.register.RegisterServer(
                clsid=myClsid,
                # I guess this is {fileNameNoExt}.{className}
                pythonInstString=nameNoExt + ".BasicServer", #toUppercase COM server.BasicServer
                progID=myProgID,
                # optional description
                desc="return uppercased string",
                #we only want the registry key LocalServer32
                #we DO NOT WANT InProcServer32: pythoncom39.dll, NO NO NO
                clsctx=pythoncom.CLSCTX_LOCAL_SERVER,
                #this is needed if this file isn't in PYTHONPATH: it tells regedit which directory this file is located
                #this will write HKEY_LOCAL_MACHINESOFTWAREClassesCLSID{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}PythonCOMPath : dirName
                addnPath=dirName,
            )
            print("Registered COM server.")
            # don't use UseCommandLine(), as it will write InProcServer32: pythoncom39.dll
            # win32com.server.register.UseCommandLine(BasicServer)
        elif sys.argv[1] == "--unregister":
            make_sure_is_admin()

            print("Starting to unregister...")

            win32com.server.register.UnregisterServer(myClsid, myProgID)

            print("Unregistered COM server.")
        else:
            print("Error: arg not recognized")

首先需要注册python COM服务器:
首先,获取您自己的 CLSID:只需使用 python shell.

you first need to register the python COM server:
first, get your own CLSID: just use a python shell.

import pythoncom
print(pythoncom.CreateGuid())

然后,将 myClsid 设置为该输出

then, set myClsid to that output

注册:
python "toUppercase COM server.py";--注册
注销:
python "toUppercase COM server.py";--取消注册

to register:
python "toUppercase COM server.py" --register
to unregister:
python "toUppercase COM server.py" --unregister

hotstring python toUppercase.ahk

hotstring python toUppercase.ahk

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
#SingleInstance, force
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
SetBatchLines, -1
#KeyHistory 0
ListLines Off
#Persistent
#MaxThreadsPerHotkey 4

pythonComServer:=ComObjCreate("Python.stringUppercaser")
; OR
; pythonComServer:=ComObjCreate("{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}") ;use your own CLSID


; * do not wait for string to end
; C case sensitive
:*:hello world::

savedHotstring:=A_ThisHotkey

;theActualHotstring=savedHotstring[second colon:end of string]
theActualHotstring:=SubStr(savedHotstring, InStr(savedHotstring, ":",, 2) + 1)
send, % pythonComServer.toUppercase(theActualHotstring)


return



f3::Exitapp

你可以测试hotstring hello world的速度,对我来说非常快.
根据自己的喜好编辑 def toUppercase(string):

you can test the speed of hotstring hello world, it's very fast for me.
Edit def toUppercase(string): to your liking

这篇关于如何像在 autohotkey 中一样在 python 中编程热字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆