确定 ghostscript 版本

Tyl*_*ker 4 r

我曾经写过一篇关于将 graphis 与外部程序结合的博客,并收到了一位读者(-单击此处-)关于完全在 R 中使用 ghostscript 实现这一点的精彩评论,如下所示。我最近一直在使用这个,我想与其他人分享。我想修改它以使功能更直观,检测 ghostscript 类型是我想做但不能做的一种模式。通过.Platform. 症结在于 Windows 32 与 64 之间的挣扎。

如何使用 R 检测正在运行的 ghostscript 版本(gswin32c 或 gswin64c)?仅查看计算机的规格还不够好,因为我在 Win 64 计算机上运行 gswin32c。这个想法是完全删除 os 参数或将其设置为NULL并让函数尝试访问此信息。

mergePDF <- function(infiles, outfile, os = "UNIX") {
    version <- switch(os,
        UNIX = "gs",
        Win32 = "gswin32c",
        Win64 = "gswin64c")
    pre = " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="
    system(paste(paste(version, pre, outfile, sep = ""), infiles, collapse = " "))
}


pdf("file1.pdf", width = 10, height = 8)
plot(1:10, col="red", pch = 19)
dev.off()

pdf("file2.pdf", width = 16, height = 8)
plot(1:10)
dev.off()

mergePDF("file1.pdf file2.pdf", "mergefromR.pdf", "Win32")
Run Code Online (Sandbox Code Playgroud)

A5C*_*2T1 5

泰勒,伙计。我是否已从 Stack Ove- R- flow同行降级为您博客的“读者”?或者那是促销活动;)

这对我来说有点hackish,但应该可以完成工作。将此添加为函数的前几行并删除 os 参数:

testme <- c(UNIX = "gs -version", 
            Win32 = "gswin32c -version", 
            Win64 = "gswin64c -version")
os <- names(which(sapply(testme, system) == 0))
Run Code Online (Sandbox Code Playgroud)

我使用了-version开关,这样 R 就不会尝试不必要地加载 Ghostscript。

在我的 Ubuntu 系统上,当我运行它os时,按预期UNIX返回Win32. 在运行 32 位 GS 的 64 位机器上尝试一下,让我知道它是如何工作的。


更新

在阅读了system()和的帮助页面后system2(),我了解到了Sys.which(),这似乎正是您要查找的内容。这是在我的 Ubuntu 系统上运行的:

Sys.which(c("gs", "gswin32c", "gswin64c"))
#            gs      gswin32c      gswin64c 
# "/usr/bin/gs"            ""            "" 
names(which(Sys.which(c("gs", "gswin32c", "gswin64c")) != ""))
# [1] "gs"
Run Code Online (Sandbox Code Playgroud)

因此,可以在mergePDF()函数中完全跳过操作系统规范:

mergePDF <- function(infiles, outfile) {
  gsversion <- names(which(Sys.which(c("gs", "gswin32c", "gswin64c")) != ""))
  pre = " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="
  system(paste(paste(gsversion, pre, outfile, sep = ""), infiles, collapse = " "))
}
Run Code Online (Sandbox Code Playgroud)

您可能想要进行一些错误检查。例如,如果 的长度gsversion> 1 或 0,您可能希望停止该函数并提示用户安装 Ghostscript 或验证其 Ghostscript 版本。