从 Python 调用 R 脚本不会在版本 4 中保存日志文件

kar*_*ren 8 python subprocess r

我正在从 python 调用一个非常简单的 R 脚本,称为R Code.R

args <- commandArgs(TRUE)
print(args)
source(args[1])

setwd("<YOUR PATH>")
output <- head(mtcars, n = n)
write.table(output, "output.txt")
Run Code Online (Sandbox Code Playgroud)

使用以下脚本:

import subprocess

pth = "<YOUR PATH>"


subprocess.call(" ".join(["C:/R/R-3.6.0/bin/x64/R.exe", "-f", '"' + pth + '/R Code.R"', "--args", 
                '"' + pth + '/arguments.txt"',"1>", '"' + pth + '/log.txt"', "2>&1"]))


subprocess.call(" ".join(["C:/R/R-4.0.3/bin/x64/R.exe", "-f", '"' + pth + '/R Code.R"', "--args", 
                '"' + pth + '/arguments.txt"',"1>", '"' + pth + '/log.txt"', "2>&1"]))
Run Code Online (Sandbox Code Playgroud)

其中arguments.txt包含:n <- 10

问题是,当我使用 R-4.0.3 时,没有生成 log.txt 文件,我需要转储一个日志文件,因为它会在我拥有的后处理过程中自动查找它。

当我在 CMD (Windows) 中执行以下命令时:

C:/R/R-4.0.3/bin/x64/R.exe -f "<YOUR PATH>/R Code.R" --args "<YOUR PATH>/arguments.txt" 1> "<YOUR PATH>/log.txt" 2>&1'
Run Code Online (Sandbox Code Playgroud)

它确实工作得很好,只有当嵌入另一个软件时。

此外,我尝试在名称中不使用空格并从根文件夹调用脚本而无需指定路径。知道为什么它不适用于 R-4.* 甚至更好,如何解决?

谢谢!

PD:谢谢你,马丁,谢谢你的建议,让我提出一个更好的问题

kar*_*ren 5

Rhelp 的人解决了这个问题,谢谢你,邓肯默多克

解决方案1:

import os
pth = "<YOUR PATH>"
os.system(" ".join(["C:/R/R-4.0.3/bin/x64/R.exe", "-f", '"' + pth + '/RCode.R"', "--args", 
                '"' + pth + '/arguments.txt"',"1>", '"' + pth + '/log.txt"']))
Run Code Online (Sandbox Code Playgroud)

解决方案2:

import subprocess
pth = "<YOUR PATH>"
subprocess.call(" ".join(["1>", '"' + pth + '/log.txt"', "2>&1",
                          "C:/R/R-4.0.3/bin/x64/R.exe", "-f", '"' + pth + '/RCode.R"', "--args", 
                '"' + pth + '/arguments.txt"']), shell = True)
Run Code Online (Sandbox Code Playgroud)