簡體   English   中英

如何將單個字符串值從 Python 子進程代碼傳遞到 R 代碼

[英]How to pass single String value from Python sub-process code to R Code

我正在嘗試使用 Subprocess 庫從 Python 運行 R 代碼。 我需要從 python 運行 one.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)   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM