Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

Calling R script from Python does not save log file in version 4

I am calling from python an R script that is very simple called R Code.R:

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

setwd("<YOUR PATH>")
output <- head(mtcars, n = n)
write.table(output, "output.txt")

using the following script:

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"]))

where arguments.txt contain: n <- 10

The problem is that when I am using R-4.0.3 the log.txt file is not generating and I need to dump a log file because it is automatically looking for it in a posterior process I have.

When I am executing in CMD (Windows) the following command:

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'

It does work perfectly, it is only when embedded in another software.

Also, I have tried without white space in the name and calling the scripts from root folder without having to specify the path. Any idea of why it doesn't work for R-4.* or even better, how to solve it?

Thank you!

PD: Thank you, Martin, for your tips and for making me formulate a better question

question from:https://stackoverflow.com/questions/65887485/calling-r-script-from-python-does-not-save-log-file-in-version-4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rhelp people got this solved, thank you, Duncan Murdoch!

Solution 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"']))

Solution 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...