[英]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.