【问题标题】:in R, invoke external program in path with spaces with command line parameters在 R 中,使用带有命令行参数的空格在路径中调用外部程序
【发布时间】:2021-06-09 22:27:05
【问题描述】:

这里有一系列令人沮丧的问题。 本质上,我希望 R 使用命令行参数打开一个外部程序。我目前正在尝试在 Windows 机器上实现它,理想情况下它可以跨平台工作。

程序 (chimera.exe) 位于包含空格的目录中:C:\Program Files\Chimera1.15\bin\ 例如,命令行选项可以是 --nogui 标志和脚本名称,所以我会从 shell 编写(除了空间细节):

C:\Program Files\Chimera1.15\bin\chimera.exe --nogui scriptfile

如果我在 windows cmd.exe 中进入目录本身并输入 chimera.exe --nogui scriptfile,则此方法有效

现在在 R 中:

我一直在玩 shell()shell.exec()system(),但基本上我因为空格和/或路径分隔符而失败了。

大多数时候 system() 出于某种原因只打印“127”:

> system("C:/Program Files/Chimera1.15/bin/chimera.exe")
[1] 127`

后/正斜线使问题进一步复杂化,但不能使其发挥作用:

> system("C:\Program Files\Chimera1.15\bin\chimera.exe")
Error: '\P' is an unrecognized escape in character string starting "C\P"

> system("C:\\Program Files\\Chimera1.15\\bin\\chimera.exe")
[1] 127

> system("C:\\Program\ Files\\Chimera1.15\\bin\\chimera.exe")
[1] 127

> system("C:\\Program\\ Files\\Chimera1.15\\bin\\chimera.exe")
[1] 127

当我将程序安装在没有空格的目录中时,它可以工作。如何在system() 或相关命令中转义或传递空格,或者如何调用程序?

【问题讨论】:

    标签: r command-line-arguments path-separator


    【解决方案1】:

    尝试system2,因为它不使用cmd 行处理器并使用r"{...}" 以避免必须使用双反斜杠。这假设 R 4.0 或更高版本。有关引号语法的完整定义,请参阅 ?Quotes

    chimera <- r"{C:\Program Files\Chimera1.15\bin\chimera.exe}"
    system2(chimera, c("--nogui",  "myscript"))
    

    例如,这对我有用(您可能需要更改路径):

    R <- r"{C:\Program Files\R\R-4.1\bin\x64\Rgui.exe}"  # modify as needed
    system2(R, c("abc", "def"))
    

    当 Rgui 启动时,我们可以通过在 R 的新实例中运行它来验证参数是否已传递:

    commandArgs()
    ## [1] "C:\\PROGRA~1\\R\\R-4.1\\bin\\x64\\Rgui.exe"
    ## [2] "abc"                                       
    ## [3] "def"   
    

    系统

    交替使用system,但在路径周围加上引号,以便cmd 正确解释它——如果它被输入到Windows cmd 行中,也需要引号。

    system(r"{"C:\Program Files\Chimera1.15\bin\chimera.exe" --nogui myscript}")
    

    【讨论】:

    • 我稍后会试试这个;非常感谢。你能给我指出一个关于 r"{}" 合成器的参考吗,以前没见过吗?关于为什么system() 双反斜杠空格转义失败或者我们对这个命令像 *shrug* 有什么想法?
    • 已添加对答案的回复。
    • ?Quotes 透露了很多非常有用但在早期学习 R 时很容易被忽视的信息。谢谢。
    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多