Call And Execute An R Script From Python
Solution 1:
Similar to Python .py scripts that can be automatically run at command line with python.exe
, R scripts can be run with Rscript.exe
(an executable in bin folder of R installation directory). This will run R code in background process without need of an IDE like RStudio. (Remember like any programming language you can write R code in simple text editor without any IDE).
Below uses subprocess.Popen
which is more useful to capture output and error of child process and change working directory in child process. Plus, you pass args in a list instead of space separated string. Remember an error in child process will not raise a Python exception.
def dbc2csv(raw_filename):
command = 'C:/Path/To/bin/Rscript.exe'
# command = 'Rscript' # OR WITH bin FOLDER IN PATH ENV VAR
arg = '--vanilla'
try:
p = subprocess.Popen([command, arg,
"Code/R/dbc2csv.R",
"Data/CNES/2005",
"Data/CNES/2005",
raw_filename],
cwd = os.getcwd(),
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")))
return True
except Exception as e:
print("dbc2csv - Error converting file: " + raw_filename)
print(e)
return False
Solution 2:
You should not call the R script through Rstudio, but with Rscript. This is a command line program that comes with R and is provided for particular this purpose.
If you write the result to a CSV file, I would not hard code it into your R script, but pass the filename to the script as a command line parameter (can be obtained in the R script with commandArgs). Then you can store the file in a temporary directory, as e.g. created with the python module tempfile.
Post a Comment for "Call And Execute An R Script From Python"