简体   繁体   English

了解模块和绝对/相对包导入

[英]Understanding module & absolute / relative package imports

I have created a package containing sub-folders and I would like to include a parent module from a sub-package module . 我创建了一个包含子文件夹的包,我想从子包模块中包含一个父模块

I have tried to follow the project structure suggested here https://docs.python-guide.org/writing/structure/ and attempted to replicate the step-by-step procedure as listed here http://zetcode.com/lang/python/packages/ but it seems that I am missing something obvious about python's package system 我试图遵循https://docs.python-guide.org/writing/structure/中建议的项目结构,并尝试复制此处列出的分步过程http://zetcode.com/lang/ python / packages /但似乎我遗漏了一些关于python的包系统的明显信息

Here's my project structure 这是我的项目结构

watches/
-- ...
-- watches/
---- __init__.py (empty)
---- Logger.py
---- main.py
---- db/
------ __init__.py (empty)
------ EntryPoint.py

Logger.py contains a single class : Logger.py包含一个类:

class Logger:
   ...

I try to import Logger.py's class and methods from db/EntryPoint.py as follow : 我尝试从db/EntryPoint.py导入Logger.py的类和方法,如下所示:

from watches.Logger import Logger
class EntryPoint: 
   ...

Then, I want to wrap-up everything in main.py as follow: 然后,我想在main.py包装所有main.py ,如下所示:

from db.EntryPoint import EntryPoint

if __name__ == "__main__":
    t = EntryPoint("local")

and finally, when I try to execute main.py as follow python3 main.py (so I am located in watches/watches directory as you can guess), I guet the following error stack trace : 最后,当我尝试按照python3 main.py执行main.py (所以我位于python3 main.py watches/watches目录中,你可以猜到),我知道以下错误堆栈跟踪:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from db.EntryPoint import EntryPoint
  File "some/absolute/path/watches/watches/db/EntryPoint.py", line 4, in <module>
    from watches.Logger import Logger
ModuleNotFoundError: No module named 'watches'

Every import will be relative to the location where the script is being run, in your case, main.py. 每个导入都是相对于运行脚本的位置,在您的情况下是main.py.

So, the point of view of your program is: 因此,您的计划的观点是:

-logger.py
-__init__.py
-db/
---__init__.pt
---EntryPoint.py

The program is not aware that he is an module called watches, so if you want to import the logger.py in your main, simply do: 程序不知道他是一个名为watches的模块,所以如果你想在你的main中导入logger.py,只需执行:

from Logger import Logger

Or move your main to the parent folder. 或者将您的主页移动到父文件夹。

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

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