FileNotFoundError on subprocess.call() in Python

Question:

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"
Asked By: Siddham Jasoria

||

Answers:

Have you tried subprocess.call(['<absolute path to Rscript>', '--vanilla', '"C:/Users/siddh/Downloads/R_script_BCA.R"'])? Just adding the double quotes?

Answered By: esskayesss

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 FilesRR-4.2.1binRscript',    # 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 FilesRR-4.2.1bin'   # 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
Answered By: Vitalizzare
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.