3

Possible Duplicate:
How to import the src from the tests module in python

I want to call another module which is located in another dir. My code structor is

flask_beginner/
  app.py
  models/
      __init__.py
      user.py
  tests/
      __init__.py
      user_test.py

I want to call user module from user_test.py. My user_test.py is like this..

import models.user
....

But it raise error that no module named models.user

Do you have any idea? My Python Version is 2.7.2.(with virtualenv)

Thanks in advance.

Community
  • 1
  • 1
nobinobiru
  • 792
  • 12
  • 28

3 Answers3

5
import sys
sys.path.append('PathToModule')
import models.user
jbaldwin
  • 924
  • 1
  • 7
  • 21
1

If you are running user_test.py from the tests directory it will not be able to find the models package. However if you run it from flask_beginner directory it will be able to find the module. The reason being the directory from which you are executing the scripts is appended to the python path and hence it can find all the modules in your project.

Ifthikhan
  • 1,484
  • 10
  • 14
1

When you run import <module_name>, Python searches in all the directories in the PythonPath variable for a module with that name and, if it finds it, imports it. The current directory (i.e. the directory in which your script is running) is usually in PythonPath, so most scripts will be able to find a module which is in the same directory.

If you need to import a module that's in a different directory, you'll need to add that directory to the PythonPath. You can do this as follows:

import sys
sys.path.append(<the_path_to_the_module>)

(Where, of course, you should replace <the_path_to_the_module> with the right path, which, in this case, would be '../models/user.py')

scubbo
  • 4,969
  • 7
  • 40
  • 71