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)
1
  • 1
    The first example in the linked tutorial does exactly what you want. Just import your module instead of OS. Commented Jul 22, 2018 at 13:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Sir, I'm getting this error by doing this: Warning: Error in py_get_attr_impl: AttributeError: module 'Task3' has no attribute 'function2()'
That's because you don't define or import function2 in your module. You need to fix your python code.
Is it possible also to pass parameters to the function call ?
@Angelo. I would assume so. I've never actually used R :)
0

You can try using source_python() instead of py_run_file. This will add a function to your .Globalenv which the python function in task3.py.

library(reticulate)
observeEvent(input$action,{
    source_python("task3.py")
    function2()
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.