GPT确实是好用,这种代码网上根本找不到
AHK部分:
#SingleInstance, Force
SendMode Input
SetWorkingDir, %A_ScriptDir%
; RunPython.ahk
; 设置 Python 解释器的路径
pythonPath := "D:\Anaconda\envs\py3.8\pythonw.exe"
pythonArguments1 := "1234"
pythonArguments2 := "5678"
; 要执行的 Python 脚本路径
pythonScript := "C:\Users\Administrator\Desktop\AHKTEST\test.py -" pythonArguments1 " -" pythonArguments2
MsgBox, %pythonScript%
; 使用 Run 命令并捕获输出
RunWait %pythonPath% %pythonScript% ,UseErrorLevel, OutputVarPID
MsgBox, %OutputVarPID%
; 读取 Python 脚本的输出文件
FileRead, output, output.txt
; 检查错误级别并输出结果
if (ErrorLevel = 0) {
MsgBox 成功执行 Python 脚本!输出:%output%
} else {
MsgBox Python 脚本执行失败!错误级别:%ErrorLevel%
}
Python部分:
import time
from sys import argv
arguments = argv
time.sleep(5)
with open("output.txt", "w") as file:
file.write(str(arguments))
总体来说,是通过AHK附带参数运行Python文件,并使用不带命令行窗口的pythonw在后台执行,Python执行后,把执行结果写入到一个文件中,再由ahk读取,这种方法比剪贴板高级一点,但是比从Python调用AHK使用subprocess复杂一点。
需要注意的是,如果pythonScript采用这种写法
pythonScript := Format("C:\Users\Administrator\Desktop\AHKTEST\test.py -{1} -{2}",pythonArguments1,pythonArguments2)
会导致OutputVarPID获取失败,尝试了一下,需要使用下面的写法才能正确获取OutputVarPID
pythonScript := "C:\Users\Administrator\Desktop\AHKTEST\test.py -" pythonArguments1 " -" pythonArguments2
除了使用RunWait还可以使用Run + process,waitclose的方式,这种方式可以解决在等待期间无法响应其他输入
#SingleInstance, Force
SendMode Input
SetWorkingDir, %A_ScriptDir%
; 设置 Python 解释器的路径
pythonPath := "D:\Anaconda\envs\py3.8\pythonw.exe"
pythonArguments1 := "1234"
pythonArguments2 := "5678"
; 要执行的 Python 脚本路径
pythonScript := "C:\Users\Administrator\Desktop\AHKTEST\test.py -" pythonArguments1 " -" pythonArguments2
MsgBox, %pythonScript%
; 使用 RunWait 命令并捕获输出
Run %pythonPath% %pythonScript%, , UseErrorLevel, OutputVarPID
MsgBox, %OutputVarPID%
; 等待 Python 脚本执行完成
Process, WaitClose, %OutputVarPID%
; 读取 Python 脚本的输出文件
FileRead, output, output.txt
; 检查错误级别并输出结果
if (ErrorLevel = 0) {
MsgBox 成功执行 Python 脚本!输出:%output%
} else {
MsgBox Python 脚本执行失败!错误级别:%ErrorLevel%
}