如何找到正在执行的 AppleScript 的名称?
原因:我想创建一个根据文件名更改其行为的脚本。比如:
if myname is "Joe" then ACTION1
else if myname is "Frank" then ACTION2
else ACTION3
获取名字的正常方法是使用“我的名字”。然而,applescripts 是由 applescript runner 运行的,因此当您在脚本上使用它时,您会得到“Applescript Runner”作为名称。如果您将脚本编译为应用程序,那么“我的名字”将起作用。获取脚本名称的唯一方法是获取其路径并提取名称。因此,这样的东西适用于脚本......
getMyName()
tell me to display dialog result
on getMyName()
set myPath to path to me as text
if myPath ends with ":" then
set n to -2
else
set n to -1
end if
set AppleScript's text item delimiters to ":"
set myName to text item n of myPath
if (myName contains ".") then
set AppleScript's text item delimiters to "."
set myName to text 1 thru text item -2 of myName
end if
set AppleScript's text item delimiters to ""
return myName
end getMyName
这里有一个方法适用于以下所有情况:
*.scpt
文件(已编译的 AppleScript 文件;在 AppleScript 编辑器中运行或使用 osascript
)*.applescript
文件(未编译的 AppleScript 文件;在 AppleScript 编辑器中运行或使用 osascript
)#!/usr/bin/env osascript
开头):*.app
使用 AppleScript 编辑器创建的文件*.app
使用 Automator 创建的包含 AppleScript 操作的文件注意:相比之下,它确实不适用于以下情况:
*.workflow
文件)的 macOS 服务 - 它们总是报告 WorkflowServiceRunner[.xpc]
*.workflow
文件,其中包含 ApplesScript 操作并使用 automator
运行 - 它们总是报告 Automator Runner[.app]
获取正在运行的脚本的名称,包括文件扩展名(
.scpt
、.app
或.applescript
,视情况而定):
tell application "System Events" to set myname to get name of (path to me)
如果您想使用单个命令删除文件扩展名,请使用以下基于
do shell script
的方法:
tell application "System Events" to set myname to do shell script "rawName=" & quoted form of (get name of (path to me)) & "; printf '%s' \"${rawName%.*}\""
这是一个更详细的全 AppleScript 替代方案(但按照 AppleScript 标准简洁):
tell application "System Events"
set myname to name of (path to me)
set extension to name extension of (path to me)
end tell
if length of extension > 0 then
# Make sure that `text item delimiters` has its default value here.
set myname to items 1 through -(2 + (length of extension)) of myname as text
end if
最后,这是一个变体:您可以使用
set myname to getMyName()
: 调用的子例程
on getMyName()
local myName, tidSaved
tell application "System Events"
set myAlias to path to me -- alias to the file/bundle of the running script
set myName to name of myAlias -- filename with extension, if any.
if name extension of myAlias is not "" then -- strip away extension
set {tidSaved, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}}
set myName to items 1 through -(2 + (length of (get name extension of myAlias))) of myName as text
set AppleScript's text item delimiters to tidSaved
end if
end tell
return myName
end getMyName
找出路径基础部分的更简单方法是使用
name of
:
tell application "Finder"
set p to path to me
set nam to name of file p as text
end tell
也许是这样: 将 appname 设置为当前应用程序的名称