2017-03-16 46 views
1

我有一個調用多個R腳本的python腳本,到目前爲止,我可以成功地傳遞單個和多個變量,請R讀取並執行它。我目前的方法是非常粗糙的,它只有在傳遞字符串和數字失敗時纔有效。有沒有一種有效的方法來完成這項任務?將多個參數從python傳遞到R

#### Python Code 
import subprocess 

def rscript(): 
    r_path = "C:/.../R/R-3.3.2/bin/x64/Rscript" 
    script = "C:/.../test.R" 

    #The separators are not recognized in R script so commas are added for splitting text 
    a_list = ["C:/SomeFolder,", "abc,", "25"] 

    subprocess.call ([r_path, script, a_list], shell = True) 
    print 'Script Complete' 

#Execute R Function 
rscript() 

#### R Code 
options(echo=TRUE) 
args <- commandArgs(trailingOnly = TRUE) 

print(args) 

args1 <- strsplit(args,",") #split the string argument with ',' 
args1 <- as.data.frame(args1) 

print(args1) 

path <- as.character(args1[1,]) 
abc <- as.character(args1[2,]) 
number <- as.numeric(args1[3,]) 

print (path) 
print (abc) 
print (number) 

write.table(path, file = "C:/path.txt", row.names = FALSE) 
write.table(abc, file = "C:/abc.txt", row.names = FALSE) 
write.table(number, file = "C:/number.txt", row.names = FALSE) 

#### R - Output 
> print (path) 
[1] "C:/SomeFolder" 
> print (abc) 
[1] "abc" 
> print (number) 
[1] 1 

回答

2

你應該串聯[r_path, script]a_list產生一個平坦的列表。

script.R

options(echo=TRUE) 
args <- commandArgs(trailingOnly = TRUE) 
print(args) 

的Python REPL

>>> commands = ["rscript", "script.R"] 
>>> args = ["C:/SomeFolder", "abc", "25"] 
>>> subprocess.call(commands + args, shell=True) 
> args <- commandArgs(trailingOnly = TRUE) 
> 
> print(args) 
[1] "C:/SomeFolder" "abc"   "25" 
+0

漂亮的工作。我甚至沒有想到'subprocess.call()'的列表語法。 – cptpython