简体   繁体   English

如何使用 subprocess.Popen 将参数从 Python 传递给 R 脚本

[英]How do I pass an argrument to an R Script from Python using subprocess.Popen

I'd like to pass a single variable to my R script while running it from python.我想在从 python 运行它时将单个变量传递给我的 R 脚本。

This is my code -这是我的代码 -

i = 0 

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

Here's a reproducible R example这是一个可重现的 R 示例


#! /usr/bin/Rscript

print(i)
print(3)

How can I access i from my R Script?如何从我的 R 脚本访问i

You can look at the subprocess library in Python可以查看Python中的子进程

You must pass the argument as a string.您必须将参数作为字符串传递。 Then you can convert it back in your R script然后你可以将它转换回你的 R 脚本

Python :蟒蛇

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

R : R:

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

Use Subprocess使用子流程

import subprocess

i = 0 

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

Rscript will get value 0 as a string you have to convert it to int. Rscript 将获得值 0 作为字符串,您必须将其转换为 int。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中从subprocess.Popen将值传递给Shell脚本 - How to pass a value to shell script from subprocess.Popen in Python 使用subprocess.Popen()从python脚本实时输出 - Realtime output from python script using subprocess.Popen() 如何将字符串传递到 subprocess.Popen(使用 stdin 参数)? - How do I pass a string into subprocess.Popen (using the stdin argument)? 使用 python 脚本中的 subprocess.Popen() 运行 venv 时如何避免加载错误的库? - How to avoid loading wrong libraries when using a subprocess.Popen() from a python script to run a venv? 如何从子进程中获取“实时”信息.Popen在python(2.5)中 - How do I get 'real-time' information back from a subprocess.Popen in python (2.5) 在 python 中,如何检查 subprocess.Popen 对象的标准输出是否有任何要读取的内容? - In python, How do I check the stdout from a subprocess.Popen object for anything to read? 通过subprocess.Popen在python中执行R脚本 - Executing an R script in python via subprocess.Popen 如何通过subprocess.arg中的arg将'env'var传递给Python脚本 - How to pass 'env' var to a Python script via an arg in subprocess.Popen 在从Python子进程调用的脚本中模拟shell命令.Popen() - Mock a shell command in a script called from Python subprocess.Popen() 如何将Ruby的IO.popen调用转换为Python的subprocess.Popen调用? - How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM