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

2024-10-04 03:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 方法字符串代码命令行test版本脚本参数
1条回答
网友
1楼 · 发布于 2024-10-04 03:22:33

(如果您希望在键入每个字母(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

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):

相关问题 更多 >