确定AppleScript脚本中文件的路径,作为Automator工作流程的一部分

问题描述

对于Automotor和AppleScript,我仍然处于学习曲线的最底端,因此我对缺乏基本的理解深表歉意,这不可避免地导致了这个问题。

我正在MacBook Air上运行MacOSX 10.15.6(Catalina)。我的最终目的是获取一个.pages文件(或其他兼容文件类型)文件夹,并通过使用Pages打开然后将其导出到与新文件类型相同的文件夹中,批量转换为.pdf(或其他)。我已经设置了一个包含以下内容的Automator脚本: 一世。获取指定的查找器项目-定义包含文件文件夹 ii。获取文件内容-列出文件夹中的所有文档 iii。 AppleScript打开每个文档并导出为PDF

即使在到达“导出”位之前(在下面的位中,我已经注释掉了导出命令),当我尝试获取包含该文件的目录的路径时,AppleScript也会引发错误。 AppleScript看起来像:

on run {input,parameters}
    
    repeat with theFile in input
        
        tell application "Pages"
            set theDoc to open theFile
            set theDocName to name of theDoc
            set theName to (characters 1 thru -7 of theDocName) as text
            set thePDFPath to ((path to theFile as text) & theName & ".pdf") as text
            -- export theDoc to thePDFPath as PDF
            close theDoc
            
        end tell
        
    end repeat
    
end run

我得到的错误是:

“运行AppleScript”操作遇到错误:“页面上有一个 错误:无法将别名“ path:to:directory:test.pages”设置为类型 恒定。”

一段时间以来,我一直在为此苦苦挣扎,到目前为止,我在网上发现的所有建议均未解决该问题。任何帮助将不胜感激。

解决方法

path to仅返回应用程序或脚本或文件系统中某些位置(例如home folderdocuments folder)的路径。不过,您不需要使用任何东西来获取路径,因为theFile已经是输入中对某项的引用-您可以将其强制为文本。此外,一旦您建立了文件路径,Pages就会期望导出文件的说明符。

请注意,文件路径包含扩展名,因此需要一点操作将其与名称的其余部分分开-在这里,我添加了一个处理程序,以将文件路径拆分为包含文件夹,名称和扩展名,以便可以根据需要对其进行处理:

on run {input,parameters}
   repeat with theFile in input
      set {folderPath,fileName,extension} to getNamePieces from theFile
      tell application "Pages"
         set theDoc to open theFile
         set theDocName to name of theDoc
         set theName to (characters 1 thru -7 of theDocName)
         set thePDFPath to (folderPath & fileName & theName & ".pdf")
         export theDoc to file thePDFPath as PDF
         close theDoc
      end tell
   end repeat
end run

to getNamePieces from someItem
   tell application "System Events" to tell disk item (someItem as text)
      set theContainer to the path of container
      set {theName,theExtension} to {name,name extension}
   end tell
   if theExtension is not "" then
      set theName to text 1 thru -((count theExtension) + 2) of theName
      set theExtension to "." & theExtension
   end if
   return {theContainer,theName,theExtension}
end getNamePieces

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...