如何像在 autohotkey 中一样在 python 中编程热字串

How to program hotstrings in python like in autohotkey

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

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

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

你需要 pywin32,但不要使用 pip install pywin32
下载 从 https://github.com/mhammond/pywin32/releases
下载 否则它不适用于 AutoHotkeyU64.exe,它只适用于 AutoHotkeyU32.exe。
确保下载amd64,(我下载了pywin32-300.win-amd64-py3.8.exe)
原因如下:how to register a 64bit python COM server

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_MACHINE\SOFTWARE\Classes\CLSID${myClsid}
            # HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}
            # and here
            # HKEY_LOCAL_MACHINE\SOFTWARE\Classes${myProgID}
            # HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.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_MACHINE\SOFTWARE\Classes\CLSID\{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.

import pythoncom
print(pythoncom.CreateGuid())

然后,将 myClsid 设置为该输出

注册:
python "toUppercase COM server.py" --register
取消注册:
python "toUppercase COM server.py" --unregister

热字串pythontoUppercase.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):