0

I am trying to get the hang of modules/packages in Python 2.7. I have a file called tmp.py in /Users/me/dir

import mypackage.datamanagement.lib.models
from mypackage.datamanagement.lib.models import Order

I can run it like this

$pwd   #/Users/me/dir
$python tmp.py  #runs fine

Everything works fine.

However, if I copy tmp.py to a different location in the package...

$cp tmp.py mypackage/datamanagement/scrips/ 

And then try to run it with $python mypackage/datamanagement/scripts/tmp.py from /Users/me/dir I get...

File "mypackage/datamanagement/scrips/tmp.py", line 1, in <module>
import mypackage.datamanagement.lib.models
ImportError: No module named mypackage.datamanagement.lib.models 

I have an init.py in all of the relevant directories. I think this has to do with pythonpath. I am osx and if I run

echo $PYTHONPATH

I get a blank line.

Can someone explain what is going on? Is the python working directory set by the location of the python file? And not the location where python is executed?

bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • When you run the `tmp.py` in the current working directory, `/Users/me/dir`, it looks for a subdirectory named `/Users/me/dir/mypackage`, so it must have found one if it worked. When you copied it to `/Users/me/dir/mypackage/datamanagement/scrips` and ran that, it looked for a subdirectory named `/Users/me/dir/mypackage/datamanagement/scrips/mypackage` and of course didn't find one. BTW, "scripts" has a "t" in it. `;-)`. Although you probably could change `$PYTHONPATH` to fix this, that would generally not be a good way to do so. The problem is your package hasn't been formally installed. – martineau Mar 15 '15 at 18:15
  • You can probably get this to work by adding a `.pth` file with an _absolute path_ to your package's root to your `/PythonXX/Lib/site-packages` directory. See the info about `.pth` files in [_Modifying Python’s Search Path_](https://docs.python.org/2/install/index.html#modifying-python-s-search-path). – martineau Mar 15 '15 at 18:47

1 Answers1

0

If you are trying to use a local Python module, in your case, "lib" would be the directory to your "tmp.py" module:

import os, sys
lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

Source: https://stackoverflow.com/a/4284378/950427

Community
  • 1
  • 1
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185