python - 如何将单个字符串值从 Python 子流程代码传递给 R 代码
问题描述
我正在尝试使用 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
解决方案
我的脚本,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)
推荐阅读
- keras - 在 Keras 中连接层
- javascript - 单击标记时如何将数据显示到文本字段
- javascript - 当“输入”被编程方法更改时,“更改”事件不会调用
- java - 霍夫曼压缩压缩文件比原始文件大
- bash - 在 Google-Cloud 的不同本地化中合并同名的 fastq.gz 文件
- reactjs - 当我们只能使用自定义钩子时,为什么还要使用 Provider 和 useContext 呢?
- swift - Firebase 我可以检索用户的电子邮件地址,但我不能在 IOS 客户端中使用它
- python - 为什么熊猫在字符串末尾添加“.0”?
- javascript - ajax-bootstrap-select 是否支持 liveSearch?
- android - 从 Bundle 中插入字符串到 ArrayList 中