I am trying to run R script using Python. I using subprocess.call function to achieve this. As suggested in other posts I have tried these different codes:
Code1
subprocess.call(['Rscript', '--vanilla', 'C:/Users/siddh/Downloads/R_script_BCA.R'])
Code 2
subprocess.Popen(['Rscript', '--vanilla', 'C:/Users/siddh/Downloads/R_script_BCA.R'])
Error for both
FileNotFoundError: [WinError 2] The system cannot find the file specified
Code 3
subprocess.Popen('Rscript --vanilla C:/Users/siddh/Downloads/R_script_BCA.R', shell=True)
Running code 3 just shows the following and nothing happens
<Popen: returncode: None args: 'Rscript --vanilla C:/Users/siddh/Downloads/R...>
The following code worked fine when used in command prompt/PowerShell
Rscript --vanilla "C:/Users/siddh/Downloads/R_script_BCA.R"
CodePudding user response:
This can happen if Rscript wasn't found in the PATH
environ variable. Put the full path to Rscript, sort of:
subprocess.call([
r'C:\Program Files\R\R-4.2.1\bin\Rscript', # put here the path to your Rscript
'--vanilla',
'C:/Users/siddh/Downloads/R_script_BCA.R'
])
Or add the path before running subprocess.call
:
import os
os.environ['PATH'] = ';' r'C:\Program Files\R\R-4.2.1\bin' # replace with your real path to Rscript
To see if you have or not the path to Rscript in the PATH
inside of the running python:
import os
for p in os.environ['PATH'].split(';'):
print(p)
To find the path to your Rscript in PowerShell:
Get-Command Rscript | Select-Object Source
CodePudding user response:
Have you tried subprocess.call(['<absolute path to Rscript>', '--vanilla', '"C:/Users/siddh/Downloads/R_script_BCA.R"'])
? Just adding the double quotes?