2015-08-30 94 views
1

我想从python运行R脚本,并将输出捕获到.Rout类型文件中。 R脚本采用命令行参数。我正在努力......最小的工作示例如下。从python运行脚本时的R输出

ř脚本:

job_reference <- commandArgs(trailingOnly = TRUE) 
arg1 <- job_reference[1] 
arg2 <- job_reference[2] 
arg3 <- job_reference[3] 
arg4 <- job_reference[4] 
print("***") 
print(paste(arg1, arg2, arg3, arg4)) 
print("***") 

Python脚本:

import subprocess 
arg1 = 'a' 
arg2 = 'b' 
arg3 = 'c' 
arg4 = 'd' 
subprocess.call(["/usr/bin/Rscript", "--no-save", "--no-restore", "--verbose", "print_letters.R", arg1, arg2, arg3, arg4, ">", "outputFile.Rout", "2>&1"]) 

在Python脚本中的最后一行是经由this stackoverflow link

如果我运行python脚本,“outputFile.Rout”是而不是产生的。然而,蟒输出包括:

running 
'/usr/lib/R/bin/R --slave --no-restore --no-save --no-restore --file=print_letters.R --args a b c d > outputFile.Rout' 

和当我运行,从而不涉及蟒命令行输出文件是产生。请注意,我已经尝试指定完整路径来输出文件等。

任何人都可以解释我)这里发生了什么; ii)我如何通过R脚本接受命令行参数来生成Rout类型文件,从而使用python运行R脚本?

在此先感谢。

回答

4

我)这里发生了什么

Rscript叫你抓着使用称为I/O重定向外壳功能。特别是,该命令的末尾> outputFile.Rout 2>&1是一个特殊的shell特征,这意味着大致将命令的所有输出重定向到文件“outputFile.Rout”,并将标准错误重定向到标准输出,因此它最终以文件以及

subprocess docs

shell=False禁止所有基于Shell功能

换句话说

,为subprocess.call()默认是不使用shell中运行的命令,这样你就不会得到访问基于shell的功能。相反,例如'>'和'outputFile.Rout'直接作为参数传递给R,就像a一样。

ii)与输出运行R.脚本重定向

虽然有几种方法去这个问题,如使用os.system()或通过shell=Truesubprocess.call()和传递命令字符串,推荐的方法就是使用机器在subprocess做相当于I/O重定向:

with open('outputFile.Rout','w') as fileobj: 
    subprocess.call(["/usr/bin/Rscript", "--no-save", "--no-restore", 
        "--verbose", "print_letters.R", 
        arg1, arg2, arg3, arg4], 
        stdout=fileobj, stderr=subprocess.STDOUT)