[英]Python Subpackages - Absolute Import Failure
This question has been asked in different contexts, but I still am unable to get a successful absolute import.这个问题在不同的情况下被问过,但我仍然无法获得成功的绝对导入。
I have this directory structure我有这个目录结构
21:48:07$ tree
start_dir
└── top_package
├── README.md
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ └── secrets.cpython-37.pyc
├── subpackage1
│ ├── __init__.py
│ └── test.py
├── requirements.txt
├── secrets.py
└── subpackage2
└── __init__.py
All I want to be able to do is from test.py be able to import from secrets.我想做的就是从test.py能够从秘密中导入。 Here is the contents of test.py:下面是 test.py 的内容:
# import top_package # ImportError: No module named top_package
# from top_package import secrets # ImportError: No module named top_package
import top_package.secrets # ImportError: No module named top_package
None of these have worked.这些都没有奏效。 I've read through multiple pages on having multiple subpackages in a top level package but still no dice.我已经阅读了多页关于在顶级 package 中拥有多个子包的信息,但仍然没有骰子。
Is this simply because I'm trying to execute the file directly by running python test.py
instead of calling this from start_dir?这仅仅是因为我试图通过运行python test.py
而不是从 start_dir 调用它来直接执行文件吗? If so, what's the best way to develop and work around this?如果是这样,开发和解决此问题的最佳方法是什么?
Goal: I want to be able to absolute import secrets
from test.py
.目标:我希望能够从test.py
绝对import secrets
。 If possible, I do not want to do anything with the site-packages or with the setup.py
.如果可能的话,我不想对 site-packages 或setup.py
做任何事情。 I want to be able to run python test.py
and have the line: import top_package
not give a ImportError no module found .我希望能够运行python test.py
并具有以下行: import top_package
not give a ImportError no module found 。 Please advise the best course of action.请告知最佳行动方案。
So you created top_package
and want to import
it anywhere within your system.因此,您创建了top_package
并希望将其import
系统中的任何位置。 You can do so by copying the package folder to the site-packages
folder of your environment.您可以通过将 package 文件夹复制到您环境的site-packages
文件夹来执行此操作。 This is a path where python would look while importing packages.这是 python 在导入包时会查看的路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.