Skip to main content
 首页 » 编程设计

python之使用 subprocess 命令调用 R 脚本,但 r 脚本中的 Library() 命令阻止它运行

2025年04月02日13lvdongjie

我创建了一个 R 脚本,我需要从 Python 调用 R 脚本。 R 脚本需要一些包才能运行,但每当我运行 python 代码时,我都会收到以下错误:

CalledProcessError: 命令 '['C:/Program Files/R/R-3.2.3/bin/x64/Rscript.exe', 'D:/Abhi/desktop/testing/SCRIPTS/JMOTIF/data -04-13/NewClassificationMethod.R', '51', '9', '20', '20', 'D://Abhi//desktop//testing//SCRIPTS//JMOTIF//data-04- 13//PureAgri.csv', 'D://Abhi//desktop//testing//SCRIPTS//JMOTIF//data-04-13//PureForest.csv']'返回非零退出状态1。

如果我注释掉库调用,那么我不会收到任何错误并且脚本可以运行。

作为一个小例子,下面的代码将不起作用:

pythonArgs = commandArgs(trailingOnly = TRUE) 
library(plyr) 
wSize=  as.numeric(pythonArgs[1]) #as.numeric(pythonArgs[1])#Window Size 
paaSize=as.numeric(pythonArgs[2])#Pax approximation size  
cat(wSize, paaSize) 

虽然这段代码可以工作

pythonArgs = commandArgs(trailingOnly = TRUE) 
#library(plyr) 
wSize=  as.numeric(pythonArgs[1]) #as.numeric(pythonArgs[1])#Window Size 
paaSize=as.numeric(pythonArgs[2])#Pax approximation size  
cat(wSize, paaSize) 

以下是我目前如何从 Python 中调用它:

cmd = [command, path2Script] + args 
x = subprocess.check_output(cmd,universal_newlines = True) 

请您参考如下方法:

考虑使用 Python 的子进程 Popen 有条件地捕获子进程的输出或错误,这里是 R 脚本。

from subprocess import Popen, PIPE 
 
cmd = [command, path2Script] + args 
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)             
output, error = p.communicate() 
 
if p.returncode == 0:             
    print('R OUTPUT:\n {0}'.format(output))             
else:                 
    print('R ERROR:\n {0}'.format(error))  

如果您运行 POpen,将在 Python 控制台中直接产生一条信息更丰富的错误消息,提醒您包路径情况。

R ERROR: 
 b"Error in library(plyr) : there is no package called 'plyr'\r\nExecution halted\r\n"