首页 > 解决方案 > 在 R 中调用 applescript

问题描述

有没有办法在 R 中运行 applescript?

我在 CRAN 上的 R 常见问题解答中找到了这个参考

From release 1.3.1 R has partial support for AppleScripts. This means two things: you can run applescripts from inside R using the command applescript() (see the corresponding help)

但在我当前版本的 R

R version 3.4.1 (2017-06-30) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS High Sierra 10.13.6

既不applescript()也不?applescript()返回任何东西。

谢谢,西蒙

标签: rapplescript

解决方案


这些功能不在现代 R 版本中(IIRC 它们可以追溯到 macOS/Mac OS X 之前的日子)。

但是,该applescript()函数并没有发挥作用:

applescript <- function(script_source, extra_args = c()) {

  script_source <- paste0(script_source, collapse = "\n")

  tf <- tempfile(fileext = ".applescript")
  on.exit(unlink(tf), add=TRUE)

  cat(script_source, file = tf)

  osascript <- Sys.which("osascript")

  args <- c(extra_args, tf)

  system2(
    command = osascript,
    args = args,
    stdout = TRUE
  ) -> res

  invisible(res)

}

所以你可以用它做任何事情,比如打开一个文件夹:

applescript(
  sprintf(
    'tell app "Finder" to open POSIX file "%s"',
    Sys.getenv("R_DOC_DIR")
  )
)

或者,查询应用程序并返回数据:

res <- applescript('
  tell application "iTunes" 
    set r_name to name of current track
    set r_artist to artist of current track
  end
  return "artist=" & r_artist & "\ntrack=" & r_name
')

print(res)
## [1] "artist=NICO Touches the Walls" "track=Hologram"

为了(mebbe)更容易使用(我说“mebbe”,因为 pkg 依赖于reticulate某些东西)我将它添加到以macthekinfemacOS 为中心的 R 包中。


推荐阅读