[英]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.我正在构建一个库,该库将通过 pip 包含在其他项目中。
I have the following directories ('venv' is a virtualenv):我有以下目录('venv' 是一个 virtualenv):
project
\- bin
\- run.py
\- myproj
\- __init__.py
\- logger.py
\- venv
I activate the virtualenv.我激活了 virtualenv。
In bin/run.py I have:在 bin/run.py 我有:
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.从“bin”目录调用时,它没有正确地将“project”目录添加到pythonpath。 How can I import modules from 'myproj' from scripts in my bin directory?
如何从 bin 目录中的脚本中的“myproj”导入模块?
Install myproject
into venv
virtualenv;将
myproject
安装到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.那么您将能够从任何脚本(包括
bin/run.py
)导入myproject
,同时在没有sys.path
hacks 的情况下激活环境。
To install, create project/setup.py
for the myproject
package and run from the project
directory while the virtualenv is active:要安装,请为
myproject
包创建project/setup.py
并在 virtualenv 处于活动状态时从project
目录运行:
$ pip install -e .
It will install myproject
inplace (the changes in myproject
modules are visible immediately without reinstalling myproject
).它将就地安装
myproject
(无需重新安装myproject
立即看到myproject
模块中的更改)。
The solution here is to source the virtualenv you have and then install the package in developer mode.此处的解决方案是获取您拥有的 virtualenv,然后在开发人员模式下安装该软件包。
source venv/bin/activate
源 venv/bin/激活
pip install -e .
点安装 -e 。
You can then import myproject.logger
from run.py
.然后,您可以从
run.py
导入myproject.logger
。
You'll need to create a setup.py file as well to be able to install the package into your environment.您还需要创建一个 setup.py 文件才能将包安装到您的环境中。 If you don't already have one you can read the official documentation here .
如果您还没有,可以在此处阅读官方文档。
Only the current working directory is inside the PYTHONPATH, which is used to resolved dependencies.只有当前工作目录位于 PYTHONPATH 中,用于解析依赖项。 So, if you are inside bin and execute your script, project is not in the path anymore.
因此,如果您在 bin 内并执行您的脚本,则项目不再在路径中。 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.
您必须使用一种常用方法将项目添加到 PYTHONPATH,方法是附加到环境变量或通过以编程方式编辑 sys.path 列表,如另一个答案中所示。
在 PYTHONPATH 中添加项目路径
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.