0

I'm having some trouble accessing python modules across different directories..

My current directory looks something like this:

__main__.py
__test__.py
tests
    some_tests.py
    _init__.py
modules
    main_modules.py
    __init__.py       

where in some_tests.py I will call some methods from /modules, with test.py executing my testing modules in /tests

I am using the below in some_tests.py to reference the modules in /modules

sys.path.append(r'../modules/')  
from main_modules import  xfunc, yfunc

this works fine if I just run some_tests.py in isolation. But as soon as I use test.py to call some_tests.py I return an ImportError where the modules from /modules cannot be found when this script calls some_tests.py

I have tried importing the modules directly into the test.py but this also doesn't work. What am I doing wrong here?

EDIT

in some_tests.py I do something like

sys.path.append(r'../modules/')  
from main_modules import modulea, moduleb

def func():
    x = modulea.xfunc()
return x

but this is what I get at runtime..

File "__test__.py", line 14, in <module>
  from tests import some_test.py
File "C:\...\__init__.py", line 2, in <module>
  from .some_test.py import (func,
File "C:\...\some_test.py", line 7, in <module>
  from modules import modulea, moduleb
ModuleNotFoundError: No module named modulea

From what I can gather at runtime, when I run test.py and it goes to import strictly that function, the function cannot be imported because it no longer runs over the sys.path.append, therefore doesnt know where to look. This is still the case even if I import the module into test.py explicitly

mrt1011
  • 21
  • 2

1 Answers1

0

You don't need to do sys.path.append instead you can directly import in the below way:

if you want to import methods or class of "main_modules.py"

from modules.main_modules import xyz,abc(whatever method or classes)

likewise follow other also

j suman
  • 127
  • 4
  • but the test modules and the main modules are at the same level of the directory structure so I need to go back up a level in order to call those modules in the test modules or I am still getting an import error.. – mrt1011 Mar 21 '20 at 18:34
  • also the exception does not come if I execute some_tests.py from the command line, it comes from when I call some_tests.py from __test__.py which is at the higher level. – mrt1011 Mar 21 '20 at 20:26