Python项目结构,项目主文件导入助手

前端之家收集整理的这篇文章主要介绍了Python项目结构,项目主文件导入助手 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是我的项目结构.

  1. [~/SandBox/pystructure]:$tree
  2. .
  3. ├── pystructure
  4. ├── __init__.py
  5.    ├── pystructure.py
  6.    └── utils
  7.    ├── eggs
  8.       ├── base.py
  9.       └── __init__.py
  10.    ├── __init__.py
  11.    └── spam.py
  12. ├── README.md
  13. └── requirements.txt
  14. 3 directories,8 files

这些是文件内容,

  1. [~/SandBox/pystructure]:$cat pystructure/utils/spam.py
  2. def do():
  3. print('hello world (from spam)!')
  4. [~/SandBox/pystructure]:$cat pystructure/utils/eggs/base.py
  5. def do():
  6. print('hello world (from eggs)!')
  7. [~/SandBox/pystructure]:$cat pystructure/utils/eggs/__init__.py
  8. from .base import do
  9. [~/SandBox/pystructure]:$cat pystructure/pystructure.py
  10. #!/usr/bin/python3
  11. from .utils import spam,eggs
  12. def main():
  13. spam.do()
  14. eggs.do()
  15. if __name__ == '__main__':
  16. main()

但是,当我尝试像这样运行应用程序时,出现此错误,

  1. [~/SandBox/pystructure]:$python3 pystructure/pystructure.py
  2. Traceback (most recent call last):
  3. File "pystructure/pystructure.py",line 3,in <module>
  4. from .utils import spam,eggs
  5. ModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package

或者当我尝试从创建文件的目录中运行代码时(这不是我的期望,因为我想将其作为服务或使用cron来运行),

  1. [~/SandBox/pystructure]:$cd pystructure/
  2. [~/SandBox/pystructure/pystructure]:$python3 pystructure.py
  3. Traceback (most recent call last):
  4. File "pystructure.py",eggs
  5. ModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package

但是,如果我导入它,它确实可以工作(但是只能从基本目录中…)

  1. [~/SandBox/pystructure/pystructure]:$cd ..
  2. [~/SandBox/pystructure]:$python3
  3. Python 3.6.7 (default,Oct 22 2018,11:32:17)
  4. [GCC 8.2.0] on linux
  5. Type "help","copyright","credits" or "license" for more information.
  6. >>> from pystructure import pystructure
  7. >>> pystructure.main()
  8. hello world (from spam)!
  9. hello world (from eggs)!
  10. >>>

(如果我尝试从它所在的目录中导入它,则会收到此错误),

  1. [~/SandBox/pystructure]:$cd pystructure/
  2. [~/SandBox/pystructure/pystructure]:$python3
  3. Python 3.6.7 (default,"credits" or "license" for more information.
  4. >>> import pystructure
  5. Traceback (most recent call last):
  6. File "<stdin>",line 1,in <module>
  7. File "~/SandBox/pystructure/pystructure/pystructure.py",eggs
  8. ImportError: attempted relative import with no known parent package
  9. >>>

我相信我的问题来自对PYTHONPATH的不完全了解,我尝试使用Google谷歌搜索,但是我还没有找到答案…请提供任何见解.

最佳答案
从程序包导入时,就是从该程序包的__init__.py导入….

因此在您的utils软件包中,您的__init__.py为空.

尝试将其添加到您的utils / __ init__.py

  1. print("utils/__init__.py")
  2. from . import eggs
  3. from . import spam

现在,当您说从utils导入鸡蛋时,您是在说垃圾邮件,是从utils包的init.py中导入我在其中导入的内容.

另外,在pystructure.py中

改变这个

  1. from .utils import eggs,spam

进入这个

  1. from utils import eggs,spam

猜你在找的Python相关文章