Home > database >  Calling python functions in R
Calling python functions in R

Time:06-08

I have a Python file that is part of my R project currently, named functions.py. Now I have a series of functions defined in that I would like to call. How would I pass arguments into Python when calling it from R?

It seems that if I use system('python functions.py hello world') it will call the file with arguments hello and world, but how do I then call a specific function while including further arguments?

CodePudding user response:

I think argparse is better for arguments. Here is my demo
Instead of sys.argv[], which function should be executed according to the the variables you specify

import argparse


def task_func(text):
    print("task", text)


def id_func(text):
    print("id", text)


parse = argparse.ArgumentParser()
parse.add_argument("-t", "--task", help="Param1",
                   type=str, default="")
parse.add_argument("-i", "--id", help="Param2", type=str, default="")
args = parse.parse_args()
task, id_ = args.task, args.id
if task:
    task_func(task)
if id_:
    id_func(id_)

Test Code

cmd = "python functions.py -t 123 --id gogogo"
subprocess.run(cmd, shell=True)

Output

task 123
id gogogo

CodePudding user response:

Here is how you can use reticulate with arguments:

your python file called greeting.py

def greetings(name,time):
    print(f'Good {time.lower()} {name.upper()}')

Now source that into R:

reticulate::source_python('greeting.py')

Now run it just the normal way you would run a R function:

greetings('Biden','evening')
Good evening BIDEN
  • Related