4

I'm building a library that will be included by other projects via pip.

I have the following directories ('venv' is a virtualenv):

project
  \- bin
     \- run.py
  \- myproj
     \- __init__.py
     \- logger.py
  \- venv

I activate the virtualenv.

In bin/run.py I have:

from myproj.logger import LOG

but I always get

ImportError: No module named myproj.logger

The following works from the 'project' dir:

python -c "from myproj.logger import LOG"

It's not correctly adding the 'project' directory to the pythonpath when called from the 'bin' directory. How can I import modules from 'myproj' from scripts in my bin directory?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
user1491250
  • 1,831
  • 4
  • 18
  • 21

4 Answers4

9

Install myproject into venv virtualenv; then you'll be able to import myproject from any script (including bin/run.py) while the environment is activated without sys.path hacks.

To install, create project/setup.py for the myproject package and run from the project directory while the virtualenv is active:

$ pip install -e .

It will install myproject inplace (the changes in myproject modules are visible immediately without reinstalling myproject).

jfs
  • 399,953
  • 195
  • 994
  • 1,670
5

The solution here is to source the virtualenv you have and then install the package in developer mode.

source venv/bin/activate

pip install -e .

You can then import myproject.logger from run.py.

You'll need to create a setup.py file as well to be able to install the package into your environment. If you don't already have one you can read the official documentation here.

Community
  • 1
  • 1
eandersson
  • 25,781
  • 8
  • 89
  • 110
  • 2
    Given that OP uses virtualenv; `sys.path` manipulations are [unnecessary](http://stackoverflow.com/a/16816683/4279) or even [harmful](http://stackoverflow.com/a/14186074/4279). – jfs May 29 '13 at 14:41
  • 2
    I prefer to use an absolute path from the script so the script can be run from anywhere. `sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '..'))` – Maxime Oct 27 '15 at 22:22
1

Only the current working directory is inside the PYTHONPATH, which is used to resolved dependencies. So, if you are inside bin and execute your script, project is not in the path anymore. You have to use one of the common methods to add project to the PYTHONPATH, either by appending to the environment variable or through editing the sys.path list programmatically, as indicated in the other answer.

languitar
  • 6,554
  • 2
  • 37
  • 62
0

add the path of project in the PYTHONPATH

Ying.Zhao
  • 154
  • 3
  • 13