【问题标题】:how to call python script from R with arguments如何使用参数从 R 调用 python 脚本
【发布时间】:2017-05-29 01:24:14
【问题描述】:

我有一个 python 脚本,它接受一些 5 个参数(一个文件名、3 个 int 值和 2 个 float 值)。我需要从 R 调用这个 python 脚本。我该怎么做。我正在尝试使用 rPython,但它不允许我传递参数

library("rPython")
python.load("python scriptname")

我不知道如何传递参数

从命令行,我运行我的 python 脚本:

python scriptname filename 10 20 0.1 5000 30

【问题讨论】:

标签: python r


【解决方案1】:

您可以调用系统命令

system('python scriptname')

要异步运行脚本,您可以将等待标志设置为 false。

system('python scriptname filename 10 20 0.1 5000 30', wait=FALSE)

在命令行中传递的参数。您必须在 python 代码中使用 sys.argv 来访问变量

#test.py
import sys

arg1 = sys.argv[1]
arg2 = sys.argv[2]
print arg1, arg2

下面的 R 命令会输出 'hello world'

system('python test.py hello world', wait=FALSE)

【讨论】:

  • 太棒了。但系统命令等待 python 程序完成。有什么办法让它不等待,
  • @user1631306 是的,Documentation 在这里。添加等待=假
  • 因此,如果我将文本文件作为参数传递,我必须手动输入文件的整个路径。有没有办法给它一个变量名,其中存储了路径?这样我就可以为任何输入文本文件自动化我的 R 脚本。
  • 没关系,我在 R 中通过谷歌搜索找到了“system2”命令:mango-solutions.com/blog/…
  • > system('python --version') 警告信息:运行命令 'python --version' 的状态为 127
【解决方案2】:

之前的好答案中有一个小错字。正确的代码如下:

 system('python test.py hello world', wait = FALSE)

其中 waitFALSE(不是 wait=Flase 或 wait=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多