Skip to content Skip to sidebar Skip to footer

Executing An R Script From Python

I have an R script that makes a couple of plots. I would like to be able to execute this script from python. I first tried: import subprocess subprocess.call('/.../plottingfile.R'

Solution 1:

First thing first, make sure that you have your platttingfile.R script at a place where you can access. Typically it is the same directory.

I read in the internet that there is a utility that comes called RScript which is used to execute R script from the command line. So in order to run the script you would use python like this:

importsubprocessretcode= subprocess.call(['/path/to/RScript','/path/to/plottingfile.R'])

This would return the retcode 0 upon successful completion. If your plottingfile.R is returning some kind of an output, it will be thrown on STDOUT. If it pulling up some GUI, then it would come up.

If you want to capture stdout and stderr, you do it like this:

import subprocess
proc = subprocess.Popen(['/path/to/RScript','/path/to/plottingfile.R'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

Solution 2:

Shell error 126 is an execution error.

The permission denied implies that you have a "permission issue" specifically.

Go to the file and make sure R/Python is able to access it. I would try this out first:

$sudochmod 777 /.../plottingfile.R

If the code runs, give it the correct but less accessible permission.

If this doesn't work, try changing R to Rscript.

Solution 3:

have you tried chmod u+x /pathTo/Rscript.R ?

Solution 4:

something likes this work usually for me:

subprocess.Popen("R --vanilla /PATH/plottingfile.R", shell = True)

Post a Comment for "Executing An R Script From Python"