22

I have a python script which takes some 5 arguments( a filename, 3 int values and 2 float values). I need to call this python script from R. How can I do that. I am trying to use rPython, but it doesnt allow me to pass the argument

library("rPython")
python.load("python scriptname")

I dont know how to pass the arguments

from command line, i run my python script like:

python scriptname filename 10 20 0.1 5000 30
user1631306
  • 4,350
  • 8
  • 39
  • 74

2 Answers2

35

You can invoke a system command

system('python scriptname')

To run the script asynchronously you can set the wait flag to false.

system('python scriptname filename 10 20 0.1 5000 30', wait=FALSE)

The arguments that get passed as they would in command line. You will have to use sys.argv in the python code to access the variables

#test.py
import sys

arg1 = sys.argv[1]
arg2 = sys.argv[2]
print arg1, arg2

The R command below would output 'hello world'

system('python test.py hello world', wait=FALSE)
Stefan Avey
  • 1,148
  • 12
  • 23
badger0053
  • 1,179
  • 1
  • 13
  • 19
  • great. but system commands waits for the python program to get completed. is there any way it wont wait, – user1631306 Jan 13 '17 at 16:03
  • @user1631306 yes, [Documentation](https://stat.ethz.ch/R-manual/R-devel/library/base/html/system.html) is here. add wait=False – badger0053 Jan 13 '17 at 16:05
  • So using this I'd have to manually type in the entire path to a file if I'm passing a text file as an argument. Is there a way to instead give it a variable name that has the path stored in it? This way I can automate my R script for any input text file. – AHegde Jun 28 '18 at 17:58
  • Never mind, I found the "system2" command in R with a bit of Googling: https://www.mango-solutions.com/blog/integrating-python-and-r-part-ii-executing-r-from-python-and-vice-versa – AHegde Jun 29 '18 at 17:00
  • > system('python --version') Warning message: running command 'python --version' had status 127 – Peter.k Jan 17 '20 at 22:08
  • `> system(python /Users/jdmoore7/Downloads/hw.py) Error in system(python/Users/jdmoore7/Downloads/hw.py) : object 'python' not found` I'm finding that R cannot locate python. At least this is my Mac OSX experience.. EDIT: I'm a fool, I didn't pass in the command as a string! It works now. – jbuddy_13 Apr 18 '20 at 16:53
9

There is a small typo in the great previous answer. The right code is the following:

 system('python test.py hello world', wait = FALSE)

where wait is FALSE (not wait=Flase or wait=False)

Andrii
  • 2,843
  • 27
  • 33