【问题标题】:Problems running an AppleScript from SublimeText从 SublimeText 运行 AppleScript 的问题
【发布时间】:2025-11-21 10:35:02
【问题描述】:

我被困住了。我有我在 Stata(一个统计包)中编写运行代码的 SublimeText 插件。 准备好文件后,我以前是这样做的:

cmd = """osascript<< END
 tell application "stata" 
  activate
  open POSIX file "%s"
 end tell
END""" % dofile_path
os.system(cmd)

... dofile_path 是我希望运行的 stata 文件的路径。

不幸的是,随着 Stata 更新发生了一些变化,现在这会打开 Stata 编辑器而不是主包。因此,我尝试使用系统事件和剪贴板重写它。

cmd = """osascript -e "activate application \"StataMP\"" -e "tell app \"System Events\" to set the clipboard to \"do sublime2stata.do\" " -e "tell app \"System Events\" to keystroke \"v\" using {command down}" -e "tell app \"System Events\" to keystroke return"            end tell""" 

我也尝试过这样的多行脚本......

cmd = """osascript<< END
tell application \"StataMP\"
    activate
end tell
tell application \"System Events\"
    keystroke \"1\" using {command down}
    set the clipboard to \"do %s\"
    keystroke \"v\" using {command down}
    keystroke return
end tell
say "finished"
END""" % dofile_path
os.system(cmd)

keystroke "1" using {command down} 只是用来确保选择了 stata 的命令窗口。

问题是什么都没有发生!文件生成,脚本运行(因为它说“完成”OK),但没有任何内容粘贴到 stata 命令窗口中。

谁能看到我的错误?

【问题讨论】:

    标签: applescript sublimetext2 stata sublimetext3


    【解决方案1】:

    在获得 Stata 13 后,我的 BBEdit 脚本运行 do-files 时遇到了同样的问题。这是现在有效的方法;也许您可以将其适应ST。诀窍是使用DoCommand 脚本命令来do Stata 中的do 文件。该脚本将在没有DoCommand "cd 行的情况下运行,但该行可确保程序日志和数据文件与 do 文件保存在同一文件夹中。

    tell application "BBEdit"
        save text document 1
        set loc to file of text document 1 as alias
    end tell
    
    
    tell application "StataMP"
        activate
        if version < 13 then
            open loc
        else
            tell application "Finder"
                set foldr to POSIX path of (folder of file loc as alias)
                set ploc to the POSIX path of loc
            end tell
            DoCommand "cd " & "\"" & foldr & "\""
            DoCommand "do " & "\"" & ploc & "\""
        end if
    end tell
    

    【讨论】:

    • 谢谢。不幸的是,我仍在使用尚未实现 AppleScript DoCommand 的 Stata 12:(请注意,对于阅读此文章的任何人,Andrew Heiss 已经为此实现了 package。我现在将继续使用 Stata 12!跨度>
    • 太糟糕了。我的脚本确实将 open loc 命令(我在您的原始脚本中看到)应用于版本 whatsnew 结果中没有任何关于编辑器的信息。
    【解决方案2】:

    所以我似乎已经解决了这个问题,但几乎完全是偶然的。 首先,您必须转到首选项>执行文件编辑器>高级并取消选中“在执行文件编辑器中编辑从查找器打开的执行文件”框。但这还不够。我还更改了 applescript,使其与 Finder 而不是 Stata 对话。

    cmd = """osascript<< END
    tell application "Finder"
      open POSIX file "%s"
    end tell
    END""" % dofile_path
    

    如果结果不可靠,我将更新此线程,但与此同时,我已将这些更改推送到我正在维护的 github repository

    【讨论】:

    • 伟大的发现!因为我很少使用编辑器,所以我从没想过看那里。事实证明,我改变了偏好,我仍然可以tell Stata to open loc。唯一的行为变化是 do 文件暂停,除非我有 set more off。当我运行发布的版本时,这并不是不必要的。