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

标签 python r subprocess

我正在从 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")
使用以下脚本:
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"]))
其中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'
它确实工作得很好,只有当嵌入另一个软件时。
此外,我尝试在名称中不使用空格并从根文件夹调用脚本而无需指定路径。
知道为什么它不适用于 R-4.* 甚至更好,如何解决?
谢谢!
PD:谢谢你,马丁,谢谢你的建议,让我提出一个更好的问题

最佳答案

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"']))
解决方案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)

关于python - 从 Python 调用 R 脚本不会在版本 4 中保存日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65887485/

相关文章:

python-3.x - Python3 子进程 check_output 对于某些命令返回空

python - 我可以从外部查看后台运行的Python程序的进度吗?

python - 如何在自定义嵌入式Python对象中存储指针

python - pandas 可以对 RollingGroupby 对象上的字符串类型列进行计数吗?

r - 结合气泡图和表格的嵌套图形

r - 条件变异和向量

r - 向 x 轴添加嵌套/分组级别

Python os.system 没有输出

python - 属性错误 : 'module' object has no attribute 'unique'

python - 使用 meshgrid 将 X、Y、Z 三元组转换为三个二维数组,用于 matplotlib 中的曲面图