【问题标题】:How can I call a python function from inside an AHK script?如何从 AHK 脚本中调用 python 函数?
【发布时间】:2021-08-11 01:45:45
【问题描述】:

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

  1. 将参数传递给 python 函数?
  2. 将 python 函数中的数据返回给我正在运行的 AHK 脚本?

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

我实现这一点的最佳尝试是以下 sn-p 代码:

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?

【问题讨论】:

  • 请将您的尝试添加到您的问题中。
  • 你不会从 ahk 调用 Python 函数。您运行 Python 脚本。您可以返回单个数字(退出代码),但不能返回文本数据。你希望做什么?
  • 我不知道,谢谢...这就是为什么我说如果可能的话,因为我不想返回信息(我想在未来的项目中使用它,但知道我不要)....所以你是说我不能从 ahk 调用 python 函数?
  • 如果您不想每次使用新参数运行脚本时都调用 runWait,您可以在 ahk 中创建一个Function,将参数作为参数,并在每次运行时使用这些参数运行脚本被调用。
  • 另外,正如@TimRoberts 提到的,唯一直接返回给 AHK 的是 Python 程序的退出代码,您也可以让 Python 脚本写入文件,然后让您的一旦 Python 脚本执行完毕,AHK 脚本就会读取文件。一个潜在的缺点是,每次调用它可能需要几毫秒的执行时间,所以如果你的程序需要高水平的时间精度或者你每秒调用数百次 Python 脚本,它可能并不理想。如果这些条件都可以,我可以为你实现代码。

标签: python autohotkey


【解决方案1】:

没有本地方法可以做到这一点,因为 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)),但是如果您想返回各种数据,例如字符串,那么问题就会变得更加混乱。问题是,在这一点上,我认为最好的解决方案是将输出写入文件,然后在 Python 脚本执行完成后让 AHK 读取文件。但是,如果您已经打算走“写入文件,然后读取它”的路线,那么您可能已经从一开始就这样做了,并使用该方法将函数名称和参数传递给 python脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-23
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多