W Anderson
W Anderson

Reputation: 53

Running an R script from command line (to execute from python)

I'm currently trying to run an R script from the command line (my end goal is to execute it as the last line of a python script). I'm not sure what a batch file is, or how to make my R script 'executable'. Currently it is saved as a .R file. It works when I run it from R.
How do I execute this from the windows command prompt line? Do i need to download something called Rscript.exe? Do I just save my R script as an .exe file? Please advise on the easiest way to achieve this.
R: version 3.3 python: version 3.x os: windows

Upvotes: 4

Views: 4389

Answers (3)

Dirk is no longer here
Dirk is no longer here

Reputation: 368221

You already have Rscript, it came with your version of R. If R.exe, Rgui.exe, ... are in your path, then so is Rscript.exe.

Your call from Python could just be Rscript myFile.R. Rscript is much better than R BATCH CMD ... and other very old and outdated usage patterns.

Upvotes: 3

Parfait
Parfait

Reputation: 107587

As mentioned, Rscript.exe the automated executable to run R scripts ships with any R installation (usually located in bin folder) and as @Dirk Eddelbuettel mentions is the recommended automated version. And in Python you can run any external program as a subprocess with various types including a call, check_output, check_call, or Popen and the latter of which provides more facility such as capturing errors in the child process.

If R directory is in your PATH environmental variable, you do not need to include full path to RScript.exe but just name of program, Rscript. And do note this is fairly the same process for Linux or Mac operating systems.

command = 'C:/R-3.3/bin/Rscript.exe'          # OR command = 'Rscript'
path2script = 'C:/Path/To/R/Script.R'
arg = '--vanilla'

# CHECK_CALL VERSION
retval = subprocess.check_call([command, arg, path2script], shell=True)

# CALL VERSION
retval = subprocess.call(["'Rscript' 'C:/Path/To/R/Script.R'"])

# POPEN VERSION (W/ CWD AND OUTPUT/ERROR CAPTURE)
curdir = 'C:/Path/To/R/Script'
p = subprocess.Popen(['Rscript', 'Script.R'], cwd=curdir,
                     stdin = subprocess.PIPE, stdout = subprocess.PIPE, 
                     stderr = subprocess.PIPE)            
output, error = p.communicate()

if p.returncode == 0:            
    print('R OUTPUT:\n {0}'.format(output.decode("utf-8")))
else:                
    print('R ERROR:\n {0}'.format(error.decode("utf-8"))) 

Upvotes: 4

Loïc
Loïc

Reputation: 11943

You probably already have R, since you can already run your script.

All you have to do is find its binaries (the Rscript.exe file).

Then open windows command line ([cmd] + [R] > type in : "cmd" > [enter])

Enter the full path to R.exe, followed by the full path to your script.

Upvotes: 1

Related Questions