python相对导入的问题
我正在 Windows 上运行以下项目,具有以下目录结构。
Project\Src\Lib\General\Module_lib.py
Project\Src\executables\example.py
现在,我想在 example.py
中导入 Module_lib.py
。请帮助我如何解决这?
example.py
的内容:
from ..lib.general.Module_lib import Module_lib
输出:
Value Error : Attempted relative import in non-packages
实现此目的的最佳方法是什么?
I am running the following project on windows with the following directory structure..
Project\Src\Lib\General\Module_lib.py
Project\Src\executables\example.py
Now , I want to import Module_lib.py
in example.py
.. Please help me how to solve this?
content of example.py
:
from ..lib.general.Module_lib import Module_lib
output :
Value Error : Attempted relative import in non-packages
what is the best way to achieve this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
Project\Src\Lib\General
添加到 PYTHON_PATH 以便运行时可以找到它。这是我能想到的唯一真正方便的解决方案。您可以在此处找到添加 python 路径的方法:
https://stackoverflow.com/questions/6318156
在脚本中执行此操作是也有可能:
这不能开箱即用,因为
dirname
调用是针对您当前的文件。要解决此问题,您可以多次调用它来向上移动目录。我希望这已经足够清楚了。Add
Project\Src\Lib\General
to your PYTHON_PATH so the runtime can find it. That's the only real convenient solution I can think of.You can find a way of adding your python path here:
https://stackoverflow.com/questions/6318156
Doing it in script is also possible:
This won't work out of the box because the
dirname
call is to your current file. To fix this you can call it multiple times to move up directories. I hope this is clear enough.您需要定义 PYTHONPATH 环境变量,以便它包含您希望 Python 在其中查找模块的所有目录。假设您的源代码树位于 C: 驱动器的根目录中,您有两个选择:
将所有叶目录添加到 PYTHONPATH 并直接导入模块,例如:
在这种情况下,您可以直接导入模块:
通过添加名为 __init__ 的空文件来制作目录的包。 py,这样您就可以使用限定名称来导入模块,并且可以减少添加到 PYTHONPATH 中的目录。你可以这样做:
在这种情况下,您可以使用合适的限定名称导入模块:
要实现此目的,您需要将名为
__init__.py
的空文件添加到 C:\Project\Src\Lib 和 C:\Project\Src\Lib\General 目录中。You need to define the PYTHONPATH environment variable so that it contains all the directories where you want Python to look for your modules. Assuming that your source tree is in the root of the C: drive you have two options:
Add all the leaf directories to PYTHONPATH and import your modules directly e.g.:
In this case you can import your module directly:
Make packages of your directories by adding empty files named
__init__.py
, so that you may use qualified names to import your modules and have less directories to add to your PYTHONPATH. You could do something like:In this case you can import your module with a suitable qualified name:
To achieve this you need to add an empty file named
__init__.py
to the C:\Project\Src\Lib and the C:\Project\Src\Lib\General directories.