我正在尝试在 R 中复制一个 shell 命令,但无法弄清楚如何将命令串在一起。这只是返回工作文件夹的内容( system()
由于某种原因失败):
> shell("dir")
Volume info ..
Directory of E:\Documents\R
contents are listed..
现在让我们尝试导航到 C 驱动器并运行
dir
(不使用明显的 dir C:
)..> shell("cd C:")
C:\
> shell("dir")
Volume in drive E is GT
etc..
所以似乎命令不能单独输入,因为 shell 不记得工作目录。所以..
> (cmd = "cd C:
+ dir")
[1] "cd C:\ndir"
> shell(cmd)
C:\
运气不好,因为没有报告 C: 文件夹。我尝试过的其他方法也失败了。感谢任何想法。
最佳答案
The documentation解释原因 system
不起作用:它直接在 Windows 上执行命令,而不先生成 shell。shell
(或者更好, system2
)是要走的路,但正如您所注意到的,shell
将始终产生一个新的 shell,这样对环境的更改就不会延续。 system2
也不会直接工作,因为它引用了它的命令(因此不允许链接命令)。
正确 在这种情况下的解决方案是不使用 shell 命令来更改目录。使用 setwd
反而:
setwd('C:')
system2('dir')
如果要在执行命令后重置工作目录,请使用以下命令:
local({
oldwd = getwd()
on.exit(setwd(oldwd))
setwd('C:')
system2('dir')
})
关于r - Windows 中的多个 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20974317/