【问题标题】:R output when script is run form python从python运行脚本时的R输出
【发布时间】:2015-11-24 12:41:53
【问题描述】:

我想从 python 运行一个 R 脚本,并将输出捕获到一个 .Rout 类型的文件中。 R 脚本采用命令行参数。我正在苦苦挣扎……下面是最小的工作示例。

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 脚本,not 会生成“outputFile.Rout”。然而,python 输出包括:

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

当我在不涉及 python 的情况下从命令行运行它时,输出文件 is 会生成。请注意,我已尝试指定输出文件的完整路径等。

谁能解释一下 i) 这里发生了什么; ii) 如何从 python 运行 R 脚本,其中 R 脚本接受命令行参数 生成 Rout 类型文件?

提前致谢。

【问题讨论】:

    标签: python r


    【解决方案1】:

    i) 这里发生了什么

    您获取的Rscript 调用使用了称为i/o 重定向的shell 功能。特别是,该命令的结尾,&gt; outputFile.Rout 2&gt;&amp;1 是一个特殊的 shell 功能,这意味着大致将命令的所有输出重定向到文件“outputFile.Rout”,哦,还将标准错误重定向到标准输出,所以它最终也出现在该文件中

    来自subprocess docs

    shell=False 禁用所有基于 shell 的功能

    换句话说,subprocess.call() 的默认设置是在不使用 shell 的情况下运行命令,因此您无法访问基于 shell 的功能。相反,例如,'>' 和 'outputFile.Rout' 直接作为 args 传递给 R,就像 a 一样。

    ii) 使用输出重定向运行 R 脚本

    虽然有几种方法可以解决这个问题,例如使用os.system() 或将shell=True 传递给subprocess.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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 2013-11-22
      • 2013-05-03
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多