繁体   English   中英

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

[英]Calling R script using subprocess command but Library() command in r script prevents it from running

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

CalledProcessError: Command '['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']' returned non-zero exit status 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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM