从Python调用自定义AutoIt函数

0 投票
2 回答
1183 浏览
提问于 2025-04-18 09:43

我找到了一种方法,可以通过下面的代码在Python中运行内置的AutoIt函数。

from win32com.client import Dispatch
Auto = Dispatch("AutoItX3.Control")
Auto.Run("notepad.exe", "", 5)

那么,有没有类似的方法可以调用自定义的方法呢?也就是说,调用在my_AutoIt_File.au3这个文件中定义的方法?

假设我在这个文件里有一个方法:

Func my_autoit_method
   ;some code
EndFunc

有没有办法从Python中调用这个my_autoit_method

2 个回答

1

你需要让你的AutoIt函数可以被其他应用程序使用。这可以通过一个叫做AutoItObject的工具来简单实现,它可以在ROT中注册一个对象

下面是AutoIt的代码:

#include <AutoItObject.au3>

$oObject = _AutoItObject_Create()
_AutoItObject_RegisterObject($oObject, 'MyVery.CustomApplication')
_AutoItObject_AddMethod($oObject, '_my_custom_function', '_my_custom_function')

While Sleep(100)
WEnd

Func _my_custom_function($oSelf)
    MsgBox(0, '', 'AutoIt says Hi')
    Exit
EndFunc

而Python的代码应该是:

from win32com.client import Dispatch
Auto = Dispatch("MyVery.CustomApplication")
Auto._my_custom_function()
1

来自帮助文件:

AutoIt特定的命令行开关

  • 格式1: AutoIt3.exe [/ErrorStdOut] [/AutoIt3ExecuteScript] 文件名
    [参数 ...]

               Execute an AutoIt3 Script File
    

/ErrorStdOut 这个选项可以把严重错误信息输出到标准输出(StdOut),这样像Scite编辑器这样的应用程序就能捕捉到这些信息。这个选项可以和编译后的脚本一起使用。

要执行一个标准的AutoIt脚本文件,比如'myscript.au3',可以使用命令: 'AutoIt3.exe myscript.au3'

  • 格式2: Compiled.exe [/ErrorStdOut] [参数 ...]

            Execute an compiled AutoIt3 Script File produced with Aut2Exe.
    
  • 格式3: Compiled.exe [/ErrorStdOut] [/AutoIt3ExecuteScript 文件名] [参数 ...]

            Execute another script file from a compiled AutoIt3 Script File. Then you don't need to fileinstall another copy of AutoIT3.exe in your compiled file.
    
  • 格式4: AutoIt3.exe [/ErrorStdOut] /AutoIt3ExecuteLine "命令行"

            Execute one line of code.
    

要执行一行代码,可以使用以下命令:

Run(@AutoItExe & ' /AutoIt3ExecuteLine  "MsgBox(0, ''Hello World!'', ''Hi!'')"')

撰写回答