2

I have directory structure like the following:

MainDir --FooBar --foobar.py, __init__.py
         |
         Ltests -- foobartest.py, __init__.py

Inside foobartest.py, I am importing

from FooBar.foobar.func_in_foobar import *

__init__.py in foobar contains from .foobar import *

And the init.py is empty in tests folder

But when I try to run the foobartest I get this error

No module named FooBar.foobar.func_in_foobar
frazman
  • 32,081
  • 75
  • 184
  • 269
  • you can make a main file like `main.py` in MainDir that can access to all directories. – mortymacs May 14 '14 at 17:07
  • for tests i have found success in making my tests dependent on my python project, and using setuptools development mode to put in on path correctly https://pythonhosted.org/setuptools/setuptools.html#development-mode http://stackoverflow.com/a/18884727/594589 – dm03514 May 14 '14 at 17:15

1 Answers1

2

I think you can solve this problem the same way as in the answer by Sorin here - https://stackoverflow.com/a/6098238/1491900:

import os, sys, inspect
 # realpath() with make your script run, even if you symlink it :)
 cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
 if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

 # use this if you want to include modules from a subforder
 cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
 if cmd_subfolder not in sys.path:
     sys.path.insert(0, cmd_subfolder)

 # Info:
 # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
 # __file__ fails if script is called in different ways on Windows
 # __file__ fails if someone does os.chdir() before
 # sys.argv[0] also fails because it doesn't not always contains the path
Community
  • 1
  • 1
gat
  • 2,872
  • 2
  • 18
  • 21