简体   繁体   English

Python 不会在子包中导入父 package

[英]Python won't import parent package within a subpackage

Here is the file structure of my current project:这是我当前项目的文件结构:

mechanism
│   .gitignore
│   dataframe.py
│   mechanism.py
│   vectors.py
│   __init__.py
│
├───examples
│       temp.py
│       __init__.py

I would like to be able to use the contents of the parent package in any file under examples .我希望能够在examples下的任何文件中使用父 package 的内容。 In temp.py , I have the following line:temp.py中,我有以下行:

from ..vectors import Vector

This raises the following error:这会引发以下错误:

Traceback (most recent call last):
  File "C:\Users\gmbra\Downloads\Python Programs\Mechanisms\mechanism\examples\temp.py", line 1, in <module>
    from ..vectors import Vector
ImportError: attempted relative import with no known parent package

I'm not sure what is going on here because I have following the syntax according to section 5.7 found here in the docs.我不确定这里发生了什么,因为我遵循了文档中第 5.7 节的语法。 What can I do to fix this?我该怎么做才能解决这个问题?

In a comment you mentioned that you are executing temp.py directly.在评论中,您提到您正在直接执行temp.py When you do this, the temp.py package namespace is not considered to be a sub-package of mechanism but instead it's own package. This is the reason it does not work.当你这样做时, temp.py package 命名空间不被认为是mechanism的子包,而是它自己的 package。这就是它不起作用的原因。

If you intend to be calling the files from examples directly, it is best to move them out of the package and do from mechanism.vectors import Vector .如果您打算直接从examples中调用文件,最好将它们移出 package 并执行from mechanism.vectors import Vector

Actually, you might be able to keep it a sub-package and just change the import to the above suggestion.实际上,您可以将它保留为一个子包,只需将导入更改为上述建议即可。

temp.py is top script in your project structure, not in a python package. While relative import is the concept of package scope. So you get the error. temp.py是项目结构中的顶级脚本,而不是 python package。而relative import是 package scope 的概念。所以你会得到错误。

Typically, for your scenario, the suggest solution is as next:通常,对于您的场景,建议的解决方案如下:

temp.py:温度.py:

from vectors import Vector

execute:执行:

$ cd mechanism
$ PYTHONPATH=. python3 examples/temp.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM