您的位置:首页 >用 AppleScript 运行 Python 脚本的完整方法
发布于2025-11-24 阅读(0)
扫一扫,手机访问

注意: 将 <username> 替换为你的实际用户名。确保 /Users/<username>/Desktop/pymac/ 目录存在。
AppleScript 脚本负责调用 Python 脚本。以下是一个示例脚本 test.scpt:
on runPython(pythonScriptPath)
do shell script "/usr/bin/python3 " & quoted form of pythonScriptPath
end runPython这个脚本接受 Python 脚本的路径作为参数,并使用 do shell script 命令执行它。
注意:
如果需要使用 Anaconda 环境执行 Python 脚本,需要在 AppleScript 脚本中激活 Anaconda 环境。以下是一个示例:
on runPythonWithAnaconda(pythonScriptPath)
set anacondaPath to "/Users/<username>/anaconda3/bin/activate" -- 替换为你的 Anaconda activate 脚本路径
set command to "source " & quoted form of anacondaPath & " base; /usr/bin/python3 " & quoted form of pythonScriptPath
do shell script command
end runPythonWithAnaconda注意:
要运行 AppleScript 脚本,可以:
以下是在 Excel VBA 中调用 AppleScript 的示例代码:
Sub RunPythonScript()
Dim scriptPath As String
Dim pythonScriptPath As String
Dim appleScriptCommand As String
Dim result As String
scriptPath = "/Users/<username>/Library/Application Scripts/com.microsoft.Excel/run_python.scpt" ' 替换为你的 AppleScript 脚本路径
pythonScriptPath = "/Users/<username>/Desktop/pymac/test.py" ' 替换为你的 Python 脚本路径
appleScriptCommand = "osascript " & scriptPath & " " & pythonScriptPath
result = Shell(appleScriptCommand, vbNormalFocus)
Debug.Print result ' 输出结果
End Sub注意:
另一种方式,使用AppleScriptTask函数,需要创建一个applescript处理函数:
a) 创建新的文件 closeterminal.sh (在工作目录), 只有一行:
#!/bin/bash
kill `ps -A | grep -w Terminal.app | grep -v grep | awk '{print $1}'`b) 在 /Users/<username>/Library/Application Scripts/com.microsoft.Excel创建新的applescipte文件, 例如 myscript.scpt
代码如下:
on myAppleScriptHandler(paramString)
tell application "Terminal"
activate
do script paramString
end tell
end myAppleScriptHandler插入一个子程序,完全可定制:
Sub test()
Dim myScriptResult As String
Dim myparams As String
myparams = "source /Users/<username>/anaconda3/bin/activate base; python /Users/<username>/Documents/<workingfolder>/<pythoncode>.py; /Users/<username>/Documents/<workingfolder>/closeterminal.sh"
myScriptResult = AppleScriptTask("myscript.scpt", "myapplescripthandler", myparams)
End Sub通过本教程,你已经学会了如何在 macOS 系统上使用 AppleScript 执行 Python 脚本,以及如何在 Excel VBA 中调用这些脚本。这种方法可以帮助你将 Python 脚本集成到 macOS 自动化流程中,提高工作效率。记住,在实际应用中,需要根据具体需求进行适当的调整和优化。
上一篇:三星手机查看内存方法详解
下一篇:笔记本升级指南:内存硬盘更换教程
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9