2017-07-19 27 views
2

我想使用R(系統)命令調用.exe程序(spi_sl_6.exe),但是我無法使用「system」向程序輸入參數。以下是我的命令和參數:system("D:\\working\spi_sl_6.exe")如何使用R調用exe程序和輸入參數?

https://i.stack.imgur.com/I6Try.jpg 我在網上搜索了很長時間。但沒用。請幫助或嘗試提供一些想法如何實現這一點。提前致謝。

+0

通過'輸入參數'你是指命令行參數還是你的意思是一旦你打開程序那些是你會進入程序的東西?第一種情況很容易處理。第二個...可能是不可能的,除非該程序被修改。 – Dason

+0

這似乎(imo)R問題呢。你是否能夠通過命令行將參數發送到exe程序(剛剛使用R進行迴避)。如果不是的話,你可以確定,因爲並非所有的程序都會促進這一點。 – user20650

+0

@梁中;您需要確保exe程序具有在命令行輸入參數的功能。如果你能做到這一點,那麼你可以使用R – user20650

回答

1

您可以構建使用sprintf命令:

cmd_name <- "D:\\working\spi_sl_6.exe" 
param1 <- "a" 
param2 <- "b" 
system2(sprintf("%s %s %s",cmd_name,param1,param2)) 

或者使用system2(我喜歡這個選項):

system2(cmd_name, args = c(param1,param2)) 
+0

謝謝你的回答。根據你的建議,我使用system2'system2(「D:\\ working \\ SPI \\ test \\ spi_sl_6.exe」,args = c(2,3,6,「D:\\ working \ \ SPI \\ test \\ Kita.cor「,」D:\\ working \\ SPI \\ test \\ restult.txt「))'但是exe程序無法工作。該消息如下「無法打開輸出文件」。在我有限的R經驗中,我不知道爲什麼。 – Liangzhong

1

這是通過使用標準化降水指數的軟件從 http://drought.unl.edu/MonitoringTools/DownloadableSPIProgram.aspx

這似乎給使用Windows工作解決方案(但不是沒有警告!)

最前一頁下載軟件和示例文件

# Create directory to download software 
mydir <- "C:\\Users\\david\\spi" 
dir.create(mydir) 

url <- "http://drought.unl.edu/archive/Programs/SPI" 
download.file(file.path(url, "spi_sl_6.exe"), file.path(mydir, "spi_sl_6.exe"), mode="wb") 

# Download example files 
download.file(file.path(url, "SPI_samplefiles.zip"), file.path(mydir, "SPI_samplefiles.zip")) 
# extract one example file, and write out 
temp <- unzip(file.path(mydir, "SPI_samplefiles.zip"), "wymo.cor") 
dat <- read.table(temp) 
# Use this file as an example input 
write.table(dat, file.path(mydir,"wymo.cor"), col.names = FALSE, row.names = FALSE) 

從幫助文件基本-,SPI第3頁program-information.pdf在上面的鏈接中,命令行代碼的格式應該是spi 3 6 12 <infile.dat >outfile.dat,但是, 以下任何一種都不能(僅從命令行而不是R中)以及如何傳遞參數的各種迭代。

C:\Users\david\spi\spi_sl_6 3 <C:\Users\david\spi\wymo.cor >C:\Users\david\spi\out.dat 
cd C:\Users\david\spi && spi_sl_6 3 <wymo.cor >out.dat 

然而,在使用公認的答案從Running .exe file with multiple parameters in c# 似乎工作。這又是在命令行

cd C:\Users\david\spi && (echo 2 && echo 3 && echo 6 && echo wymo.cor && echo out1.dat) | spi_sl_6 

所以到R中運行這個你可以在shell(你需要將路徑更改爲您保存的exe)

shell("cd C:\\Users\\david\\spi && (echo 2 && echo 3 && echo 6 && echo wymo.cor && echo out2.dat) | spi_sl_6", intern=TRUE) 

這個包起來out1.datout2.dat應該是相同的。

這會拋出警告消息,我認爲從echo(在R中,但不是從命令行),但產生輸出文件。

假設您可以自動化所有的回調調用,所以您只需輸入時間參數即可。

timez <- c(2, 3, 6) 
stime <- paste("echo", timez, collapse =" && ") 
infile <- "wymo.cor" 
outfile <- "out3.dat" 
spiCall <- paste("cd", mydir, "&& (" , stime, "&& echo", infile, "&& echo", outfile, ") | spi_sl_6") 
shell(spiCall) 
+1

謝謝你的回覆。你已經完美地解決了我的問題。 – Liangzhong

+0

我完全不知道; P,但你非常歡迎。我在答案中加入了一個完整的示例,希望它能讓熟悉Windows命令行的人更容易提供改進建議。 – user20650

相關問題