Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import module from bin directory of the same project

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?

like image 259
user1491250 Avatar asked Dec 06 '22 07:12

user1491250


2 Answers

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).

like image 135
jfs Avatar answered Jan 05 '23 17:01

jfs


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.

like image 42
eandersson Avatar answered Jan 05 '23 17:01

eandersson