如何找到正在执行的AppleScript的名称?
原因:我想创建一个脚本,根据文件名更改其行为。类似的东西:
if myname is "Joe" then ACTION1
else if myname is "Frank" then ACTION2
else ACTION3
答案 0 :(得分:5)
获取名称的正常方法是使用“我的名字”。然而,applescript由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
答案 1 :(得分:2)
这是针对以下所有方法的工作的方法:
*.scpt
个文件(已编译的AppleScript文件;在AppleScript编辑器中运行或使用osascript
运行)*.applescript
个文件(未编译的AppleScript文件;在AppleScript编辑器中运行或与osascript
一起运行)#!/usr/bin/env osascript
开头):*.app
个文件
使用Automator创建的*.app
个包含AppleScript操作的文件注意:相比之下,不对以下内容起作用:
*.workflow
文件) - 始终报告'WorkflowServiceRunner [.xpc]'*.workflow
运行的通用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
答案 2 :(得分:0)
找出路径基础部分的更简单方法是使用name of
:
tell application "Finder"
set p to path to me
set nam to name of file p as text
end tell
答案 3 :(得分:0)
也许这个: 将appname设置为当前应用程序的名称