How to source a python file that imports another python file using reticulate in an R-package

I have an R-package with 2 python files in inst/python called A.py and B.py.
A.py is sourced with reticulate, where A.py in turn needs to import B.py. But A.py fails to find B.py.

A.py is in R sourced like this:

 reticulate::source_python(system.file("python",
                                        "A.py",
                                        package = "My_Package_Name",
                                        mustWork = TRUE
  ))

A.py is in turn trying to import B.py, like this:

import os, sys
sys.path.append('./inst/python/')
from B import main

When running the function that uses A.py and B.y this is the resulting error:
Error in py_run_file_impl(file, local, convert) : **
** ModuleNotFoundError: No module named 'B'

I have tried to source B.py before sourcing A.py in R using reticulate::source_python().
I have also tried in A.py to find the correct path to the B.py. That is, in R I print the current position for where R finds the A.py file, which is where the R-package files are located in the system:
/Library/Frameworks/R.framework/Versions/4.2/Resources/library/package/python/
However, the exact location of this will of course differ across OS etc.

When sourcing A.py in R, that file in turn looks for B.py but in the wrong location.
This is what I’ve tried in python (followed by the printed message):
1

print(os.getcwd())
/Users/OK/Desktop/Research/package

2

print(sys.path.append('./inst/python/'))
None

3

print(sys.argv[0])
/Users/OK/Library/r-miniconda/envs/package/bin/python

4

print( os.path.abspath(sys.argv[0]))
/Users/OK/Library/r-miniconda/envs/package/bin/python

Any help is much appreciated.

i got this to work by setting the python path from R using reticulate like this:

  My_Package_Name_path <- system.file("python", package = "My_Package_Name")
  reticulate::py_run_string(paste0("import sys; sys.path.append('", My_Package_Name_path, "')"))

reticulate::source_python(system.file("python",
                                        "A.py",
                                        package = "My_Package_Name",
                                        mustWork = TRUE
  ))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.