【问题标题】:How to pass single String value from Python sub-process code to R Code如何将单个字符串值从 Python 子流程代码传递给 R 代码
【发布时间】:2020-03-24 17:33:56
【问题描述】:

我正在尝试使用 Subprocess 库从 Python 运行 R 代码。 我需要从 python 运行一个 .R 文件并传递一个字符串值(args = [“INV28338”])。 我是 R 新手,因此无法在 R 和 Python 中找出确切的数据类型转换代码。

请有人帮助我,如何将单个字符串/标量值从 Python 传递到 R 函数/模型? 稍后我将为这段代码给出“Flask REST API”的形状。

非常感谢您

Python 代码:-

import subprocess
command = 'Rscript'
path2script = 'classification_model_code.R'
args = ["INV28338"]
cmd = [command, path2script] + args
x = subprocess.check_output(cmd, universal_newlines=True)
print('The Output is:', x)

R代码:-

myArgs <- commandArgs(trailingOnly = TRUE)
nums = as.numeric(myArgs)
invoice_in_scope<-nums
#Followed by more code 

【问题讨论】:

  • 嗨 Gautam,欢迎来到 SO。问题在于你的 python,而不是 R。我已经在下面发布了运行 shell R 的方式。至于你的 Flask REST API,如果你有问题,最好发布另一个问题 :) 避免在一个单个帖子。

标签: python r python-3.x flask subprocess


【解决方案1】:

我的脚本,test2.R

myArgs <- commandArgs(trailingOnly = TRUE)
nums = as.character(myArgs)
print(nums)

您需要将args 作为列表的一部分,因此将其附加到cmd 并且可以正常工作:

import subprocess 
command = 'Rscript' 
path2script = './test2.R' 
args = "INV28338" 
cmd = [command, path2script]
cmd.append(args)
x = subprocess.check_output(cmd, universal_newlines=True) 
print('The Output is:', x)   

【讨论】:

  • 是的,但是 args = "INV28338" 在上述函数中仍然不起作用,R 代码无法将此值保存在 'nums' 变量中。而 args = "9" 工作正常。当我通过 ="INV28338" 时我需要做些什么改变
  • 嘿,“INV28338”不是数字。你需要它作为角色。 nums = as.character(myArgs)。查看我编辑的答案
猜你喜欢
  • 2019-10-22
  • 2019-11-24
  • 2011-09-06
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
相关资源
最近更新 更多