我想从Python运行R脚本。如果没有" + args",以下脚本可以正常工作。任何人都知道传递args的错误是什么?
Python脚本:
import subprocess
Iterations = 10
command = 'C:/Program Files/R/R-3.4.3/bin/Rscript.exe'
path2script = 'C:/Users/a0266997/Documents/PossionDistribution.R'
args = [str(Iterations)]
cmd = [command, path2script] + args
subprocess.Popen(cmd)
R脚本:
myArgs <- commandArgs(trailingOnly = TRUE)
Iterations = myArgs[0]
Iterations
do something in R ....
答案 0 :(得分:0)
这是您的代码,其中包含一些适合您的更正。我还将R代码更改为应该可重现的内容(例如,打印到stdout和stderr)。
我将subprocess.Popen(cmd)
调用更改为subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
,这应解决部分问题。 R代码中也有一个修复程序。
import subprocess
Iterations = 10
command = 'C:/Program Files/R/R-3.4.3/bin/Rscript.exe'
path2script = 'C:/Users/a0266997/Documents/PossionDistribution.R'
args = [str(Iterations)]
cmd = [command, path2script] + args
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
results = p.communicate()
R脚本(代码的修改版本)
这已将myArgs[0]
更改为myArgs[1]
myArgs <- commandArgs(trailingOnly = TRUE)
Iterations = myArgs[1]
write(paste0("stdout: ", Iterations), file = stdout())
write("stderr", file = stderr())
我在Mac OS上运行它,它对我有用。至少应该让你开始朝着正确的方向前进,这取决于你需要的细节。