首页 > 解决方案 > 使用参数调用python函数并在autohotkey中获取返回值

问题描述

我有一个名为“server.py”的 python 脚本,在其中我有一个函数def calcFunction(arg1): ... return output如何使用参数调用函数 calcFunction 并在 autohotkey 中使用返回值?这就是我想在 autohotkey 中做的事情:

ToSend = someString ; a string
output = Run server.py, calcFunction(ToSend) ; get the returned value from the function with ToSend as argument
Send, output ; use the returned value in autohotkey

我在网上看过,但似乎没有什么能完全回答我的问题。甚至可以做到吗?

标签: pythonautohotkey

解决方案


为了将参数发送到 Python,您可以使用 Python 脚本中的参数。您可以使用sys库执行此操作:

import sys
print(sys.argv[0]) # name of file
print(sys.argv[1]) # first argument
print(sys.argv[2]) # second argument...

在 AutoHotKey 脚本中,您可以通过在指定文件名后立即将参数添加为参数来将参数发送到 Python 脚本:

RunWait, server.py "This will be printed as the first argument!" "This is the second!"

然后,要将函数的输出返回给 AHK,您可以sys利用它的exit()函数再次使用:

sys.exit(EXIT_NUMBER)

回到 AHK,您会收到EXIT_NUMBER内部变量ErrorLevel。综上所述,您的代码应如下所示:

; AHK
RunWait, server.py "%ToSend%"

# Python
sys.exit(calcFunction(sys.argv[1]))

; AHK
MsgBox %ErrorLevel%

推荐阅读