首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从AHK脚本中调用python函数?

如何从AHK脚本中调用python函数?
EN

Stack Overflow用户
提问于 2021-05-21 20:29:52
回答 1查看 1.1K关注 0票数 2

如何从AHK脚本运行python函数?如果可能的话,我怎么会:

将参数从python函数传递给python function?

  • Return数据时,
  1. 将参数传递给正在运行的脚本?。

我能找到的唯一相关信息是this answer,但是我无法将它实现到我自己的脚本中。

实现这一点的最佳尝试是以下代码片段:

代码语言:javascript
运行
复制
e::; nothing, because RunWait it's the command recommended in the question that I linked, so that means that I have to do a RunWait every time I press e?
EN

回答 1

Stack Overflow用户

发布于 2021-05-21 21:08:49

没有本地的方法可以做到这一点,因为AHK与Python的唯一交互就是运行整个脚本。但是,您可以修改python脚本以接受参数,然后可以在脚本之间进行交互(比如链接问题)。

解决方案如下--类似于您所链接的问题,设置python脚本,以便它将函数名和函数参数作为参数,然后让它使用这些参数运行函数。

类似于我对链接问题的回答,您可以使用sys.argv执行以下操作:

代码语言:javascript
运行
复制
# Import the arguments from the sys module
from sys import argv

# If any arguments were passed (the first argument is the script name itself, so you must check for >1 instead of >0)
if len(argv) > 1:
    # This next line is basically saying- If argv is longer than 2 (the script name and function name)
    # Then set the args variable to everything other than the first 2 items in the argv array
    # Otherwise, set the args variable to None
    args = argv[2:] if len(argv) > 2 else None

    # If arguments were passed, then run the function (second item in argv) with the arguments (the star turns the list into args, or in other words turns the list into the parameter input format)
    # Otherwise, run the function without arguments
    argv[1](*args) if args else argv[1]()

# If there is code here, it will also execute. If you want to only run the function, then call the exit() function to quit the script.

然后,在AHK中,您所需要做的就是运行RunWait或run命令(取决于您是否要等待函数完成)来调用该函数。

代码语言:javascript
运行
复制
RunWait, script.py "functionName" "firstArgument" "secondArgument"

你问题的第二部分很棘手。在您所链接的问题中,对于如何返回整数值(TLDR:使用sys.exit(integer_value))有一个很好的解释,但是,如果您想返回所有类型的数据,例如字符串,那么问题就会变得更加混乱。问题是,在这一点上,我认为最好的解决方案是将输出写到文件中,然后让AHK在执行Python脚本之后读取该文件。但是,如果您已经准备沿着“写到文件,然后读取它”路由,那么您最好从一开始就这样做,并使用该方法将函数名和参数传递给python脚本。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67643517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档