Can't import module from bin directory of the

2019-03-21 17:21发布

问题:

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?

回答1:

The simplest solution is to append the parent folder as a searchable path, above the import.

import sys,os
sys.path.append(os.path.abspath('..'))
from myproj.logger import LOG


回答2:

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



回答3:

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.



回答4:

add the path of project in the PYTHONPATH