2

I'm using source_python() function to run a Python Script via user interface of R Shiny. Code is running properly and I'm successful in it. But I want to run a function named function2() which is in Task3.py. Can I do this? If yes then how can I do this? I just want to execute function2(). I don't want function1() and function3() to run. I'm doing this by using following lines and syntax which I found by Googling. I'm unsuccessful in running just function2() by following below link. The link that I followed is:

https://rstudio.github.io/reticulate/articles/calling_python.html

server.R:

library(reticulate)
observeEvent(input$action,{
    py_run_file("applications/Task3.py")
    function2()
  })

Task3.py:

def main(argv):
   function1()
   ....
   function2()
   ....
   function3()
   ....
if __name__ == "__main__":
    try:
        k=sys.exit(main(sys.argv))
    except (ValueError, IOError) as e:
        sys.exit(e)
Knowledge Seeker
  • 526
  • 7
  • 25

1 Answers1

2

To call a single function from a python module, you need to import the module as an object and run the function from it rather than executing the module as a script.

The tutorial you linked starts with how to do exactly that. Instead of py_run_file, you'll want to use import:

library(reticulate)
observeEvent(input$action,{
    task3 <- import("Task3")
    task3$function2()
})

You may have to switch to the applications directory or add it to your PYTHONPATH for the import to work properly.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264