如何从AHK脚本运行python函数?如果可能的话,我怎么会:
将参数从python函数传递给python function?
我能找到的唯一相关信息是this answer,但是我无法将它实现到我自己的脚本中。
实现这一点的最佳尝试是以下代码片段:
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?
发布于 2021-05-21 21:08:49
没有本地的方法可以做到这一点,因为AHK与Python的唯一交互就是运行整个脚本。但是,您可以修改python脚本以接受参数,然后可以在脚本之间进行交互(比如链接问题)。
解决方案如下--类似于您所链接的问题,设置python脚本,以便它将函数名和函数参数作为参数,然后让它使用这些参数运行函数。
类似于我对链接问题的回答,您可以使用sys.argv
执行以下操作:
# 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命令(取决于您是否要等待函数完成)来调用该函数。
RunWait, script.py "functionName" "firstArgument" "secondArgument"
你问题的第二部分很棘手。在您所链接的问题中,对于如何返回整数值(TLDR:使用sys.exit(integer_value)
)有一个很好的解释,但是,如果您想返回所有类型的数据,例如字符串,那么问题就会变得更加混乱。问题是,在这一点上,我认为最好的解决方案是将输出写到文件中,然后让AHK在执行Python脚本之后读取该文件。但是,如果您已经准备沿着“写到文件,然后读取它”路由,那么您最好从一开始就这样做,并使用该方法将函数名和参数传递给python脚本。
https://stackoverflow.com/questions/67643517
复制相似问题