获取Windows命令以运行system / shell.exec

时间:2015-03-18 18:59:30

标签: r windows

我经常使用Windows command tree打印出文件内容的树形图。我想将此添加到我在R中的工作流程但是无法通过systemshell.exec运行命令,并且无法找出原因。以下是shQuotesystem命令中使用shell.exec(有和没有)的4种方法和错误消息的可重现示例。当我使用cat时,我可以将命令粘贴到Windows命令行手册(不使用R),并生成树形图。我做错了什么,我无法在R中运行?

## build some mock files and directories with lapply
lapply(file.path("TEMP", c("", "X", "Y")), dir.create)
lapply(file.path("TEMP", paste0(c("A", "B"), ".txt")), file.create)

## create path to external file
out <- file.path(getwd(), "TREE.txt")

## create the tree command
cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
cat(cmd)  ## view it

system(cmd)  ## attempt 1

cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
shell.exec(cmd)  ## attempt 2

cmd2 <- paste("tree", file.path(getwd(), "TEMP"), "/f /a >", out)
system(cmd2)  ## attempt 3
shell.exec(cmd2)  ## attempt 4

cat(cmd, file="clipboard")


## > out <- file.path(getwd(), "TREE.txt")
## > cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
## > cat(cmd)
## tree "C:/Users/trinker/Desktop/TEMP" /f /a > "C:/Users/trinker/Desktop/TREE.txt"> 
## > system(cmd)
## Too many parameters - >
## > 
## > cmd <- paste("tree", shQuote(file.path(getwd(), "TEMP")), "/f /a >", shQuote(out))
## > shell.exec(cmd)
## Error in shell.exec(cmd) : 
##   'tree "C:/Users/trinker/Desktop/TEMP" /f /a > "C:/Users/trinker/Desktop/TREE.txt"' not found
## > 
## > 
## > cmd2 <- paste("tree", file.path(getwd(), "TEMP"), "/f /a >", out)
## > system(cmd2)
## Too many parameters - >
## > shell.exec(cmd2)
## Error in shell.exec(cmd2) : 
##   'tree C:/Users/trinker/Desktop/TEMP /f /a > C:/Users/trinker/Desktop/TREE.txt' not found

1 个答案:

答案 0 :(得分:5)

使用shell。在Windows上,system不使用shell(它只运行系统命令)。您尝试使用管道重定向输出,因此您遇到了? system中提到的问题:

  

command必须是可执行文件(扩展名'.exe','。com')或批处理文件(扩展名'.cmd'和'.bat'):如果没有,则依次尝试这些扩展名这意味着无法使用重定向,管道,DOS内部命令......:如果要传递shell命令行,请参阅shell