0

I want to call an R program from a python script.

I wrote the following:

os.system("cat " + variableName + " | code.R")

It returns the error: sh: 1 : code.R: not found cat: write error: Broken pipe

Yet, I am sure of the name of the R file.

Why is it not working?

bigTree
  • 2,103
  • 6
  • 29
  • 45

2 Answers2

1

Is code.R in the current working directory? Is it executable? Can you run cat xxx | code.R from the shell and have it work properly, instead of running your python program?

Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
  • Yes to all these questions (for the executable part, ls -lrt gives -rwxr-xr-x. I had executed the code.R from another directory before copying it to the one where my python script is located) – bigTree Mar 11 '14 at 17:53
  • Do `print os.getcwd()` immediately before the `os.system()` call? – Russell Borogove Mar 11 '14 at 18:10
1

So, if code.R is a script that has to be interpreted you must build the pipe to the interpreter not to the script. You receive a Broken PIPE error because code.R by it self don't know how to handle command line arguments.

On the other hand if what you want is store the variable value inside code.R you have to change | by >>.

os.system("cat " + variablename + ">> code.R")

EDIT: Since it's working from terminal, try this:

import subprocess
input = open(variableName, "r")
result = suprocess.call(["code.R"], stdin=input)    # result is the return code for the command being called.

see subprocess.call for more details.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • Actually, code.R takes variable as input. What bothers me is that, from the terminal, cat variable | code.R worked perfectly. I would like to call this command from my python script, but for some reason it doesn't work... – bigTree Mar 11 '14 at 18:00
  • the problem is then solved. Thank you guys for your help – bigTree Mar 12 '14 at 08:28