Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call python script from R with arguments

Tags:

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
like image 910
user1631306 Avatar asked Jan 13 '17 15:01

user1631306


People also ask

Can you call a Python script from R?

Use R and Python in a Single Project With the reticulate Package. Once installed, you can call Python in R scripts. In this example, we turn the Palmer Penguins dataset into a Pandas data frame. Then, we run the pandas.

How do you use R and Python together?

package comes with a Python engine you can use in R Markdown. Reticulate allows you to run chunks of Python code, print Python output, access Python objects, and so on. Easy, right? You can import any Python library and write any Python code you want, and then access the variables and functions declared with R.

How do you call an argument in a Python script?

You can use the command line arguments by using the sys. argv[] array. The first index of the array consists of the python script file name. And from the second position, you'll have the command line arguments passed while running the python script.

How do you run a function in Python in R?

First up, install some packages. You must have Python >=3.7 and R >= 4.0 installed to use rpy2 3.5. 2. Once R is installed, install the rpy2 package by running pip install rpy2 .


2 Answers

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)
like image 100
badger0053 Avatar answered Sep 21 '22 19:09

badger0053


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)

like image 28
Andrii Avatar answered Sep 20 '22 19:09

Andrii