Running R script from python

I would not trust too much the source within the Rscript call as you may not completely understand where are you running your different nested R sessions. The process may fail because of simple things such as your working directory not being the one you think.

Rscript lets you directly run an script (see man Rscript if you are using Linux).

Then you can do directly:

subprocess.call ("/usr/bin/Rscript --vanilla /pathto/MyrScript.r", shell=True)

or better parsing the Rscript command and its parameters as a list

subprocess.call (["/usr/bin/Rscript", "--vanilla", "/pathto/MyrScript.r"])

Also, to make things easier you could create an R executable file. For this you just need to add this in the first line of the script:

#! /usr/bin/Rscript

and give it execution rights. See here for detalis.

Then you can just do your python call as if it was any other shell command or script:

subprocess.call ("/pathto/MyrScript.r")

Leave a Comment