【问题标题】:How do I pass an argrument to an R Script from Python using subprocess.Popen如何使用 subprocess.Popen 从 Python 将参数传递给 R 脚本
【发布时间】:2020-09-08 05:12:50
【问题描述】:

我想在从 python 运行时将一个变量传递给我的 R 脚本。

这是我的代码 -

i = 0 

with open(result_filename, 'a') as result:
    process = subprocess.Popen(['Rscript',
                                'MyScript.R'
                                ],
                                stdout=result);

这是一个可重现的 R 示例


#! /usr/bin/Rscript

print(i)
print(3)

如何从我的 R 脚本访问i

【问题讨论】:

标签: python r


【解决方案1】:

你可以在 Python 中查看subprocess

您必须将参数作为字符串传递。然后您可以将其转换回您的 R 脚本中

Python

import subprocess
    
i = 0 
with open(result_filename, 'a') as result: 
    output = subprocess.run(['Rscript', 'RScriptWeeklyActives.R', str(i)], stdout=result)

R

#! /usr/bin/Rscript
args = commandArgs(trailingOnly=TRUE)
i = strtoi(args[1])
print(i)
print(3)

【讨论】:

    【解决方案2】:

    使用Subprocess

    import subprocess
    
    i = 0 
    
    with open(result_filename, 'a') as result:
        command = subprocess.Popen(['Rscript', 'RScriptWeeklyActives.R', 'i'], stdout=result)
    

    Rscript 将获取值 0 作为字符串,您必须将其转换为 int。

    【讨论】:

    • 不幸的是,Shell = True 对我不起作用。您可以将脚本设置为 print(1),对我来说,输出文件是空的。当我摆脱 shell = True 时,输出文件显示数字 1
    • 我不清楚如何从 R 访问 i 变量
    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    相关资源
    最近更新 更多