如何使用参数从R调用python脚本

问题描述 投票:13回答:2

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

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

我不知道如何传递参数

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

python scriptname filename 10 20 0.1 5000 30
python r rpython
2个回答
18
投票

您可以调用系统命令

system('python scriptname')

要异步运行脚本,可以将wait标志设置为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)

8
投票

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

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

其中wait为FALSE(不等待= Flase或wait = False)

© www.soinside.com 2019 - 2024. All rights reserved.