1

I am trying to run an R script from Python. The Rscript train.R is in the same folder as the Jupyter Notebook. The working directory is set to that folder.

import subprocess
try:
    subprocess.check_call(['Rscript', 'train.R'], shell=False)
except subprocess.CalledProcessError as e:
    print(e.output)
    print(e.returncode)
    print(e)
    print(e.stderr)

I am getting a CalledProcessError:

None
1
Command '['Rscript', 'train.R']' returned non-zero exit status 1
None

I tried to set the argument shell=True and I tried to set the argumentcwd=os.path.dirname(os.path.realpath("train.R")) as mentioned here.

The command Rscript train.R works just fine if I open a console in the folder.

What am I doing wrong?

PascalIv
  • 595
  • 7
  • 21
  • What does the `stderr` reveal? It's attached to the exception. – a_guest Jan 20 '20 at 12:21
  • @a_guest It holds None – PascalIv Jan 20 '20 at 12:22
  • 2
    It is `None` because you don't capture neither stdout nor stderr. You should use `subprocess.run(..., capture_output=True)` instead. See [the docs](https://docs.python.org/3/library/subprocess.html#subprocess.check_call). – a_guest Jan 20 '20 at 12:24

1 Answers1

3

I'd recommend you make use of Popen instead

import subprocess
try:
    pro = subprocess.Popen(['Rscript', 'train.R'], shell=False)

    stdout, stderr = pro.communicate()

    print(stdout)
    print(stderr)

With this you should be able to get your error or output values from the subprocess

maestro.inc
  • 796
  • 1
  • 6
  • 13
  • 2
    Just wanted to add... If for some reason you aren't getting the expected stdout and stderr output from your process, you may need to also include the 'subprocess.PIPE' parameter in your Popen constructor. ie pro = subprocess.Popen(['Rscript', 'train.R'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) – Jadon Manilall Jan 20 '20 at 14:49