【问题标题】:How does R grab arguments passed from PythonR如何抓取从Python传递的参数
【发布时间】:2018-03-15 22:24:31
【问题描述】:

我想从 Python 运行 R 脚本。以下脚本在没有“+ 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 ....

【问题讨论】:

  • 我在您的 R 代码中看到的一个问题是您使用的是 myArgs[0],它应该是 myArgs[1],因为 R 向量以 1 而不是 0 开头。当然 python 从 0 开始,所以这是一个在两种语言之间切换很容易出错。

标签: python r arguments subprocess


【解决方案1】:

这是您的代码,其中包含一些应该适合您的更正。我还将 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 上运行了它,它对我有用。它至少应该让您朝着正确的方向开始,具体取决于您的需求细节。

【讨论】:

  • 您可能想要查看的一个选项是rpy2。这可能会使 Python 和 R 之间的数据处理更容易。我已经有一段时间没有使用它了,但是当我使用它时效果很好。
猜你喜欢
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 2022-10-08
  • 2012-12-17
  • 2016-09-09
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多