如何将Python子流程代码中的单个字符串值传递给R Cod

2024-04-25 23:11:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

事先非常感谢

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 

Tags: 文件数据字符串代码cmdargscode流程
1条回答
网友
1楼 · 发布于 2024-04-25 23:11:04

我的脚本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)   

相关问题 更多 >