[英]How to import class from one subfolder into another in Python 3?
So, I have the following folder structure ; 所以,我有以下文件夹结构;
Root/
--outlook/
----outlook.py
--test/
----test.py
outlook.py
contains a class named Outlook
. outlook.py
包含一个名为Outlook
的类。
I am trying to import Outlook
class in test.py
file as follows - 我试图按如下方式将
test.py
文件中的Outlook
类导入-
from .outlook import Outlook
outlook = Outlook()
I am running the script from Root folder as - python test/test.py
我正在从根文件夹运行脚本
python test/test.py
This results in error - 这导致错误-
Traceback (most recent call last):
File "test/test.py", line 1, in <module>
from .outlook.outlook import Outlook
ModuleNotFoundError: No module named '__main__.outlook'; '__main__' is not a package
Please help. 请帮忙。
Relative import paths will work only if the child module is being loaded from within the parent module: 相对导入路径仅在从父模块中加载子模块时才有效:
from Root.test.test import some_function
If you want to use components from two different child modules together and as standalone scripts I would suggest using non relative import paths: 如果要同时使用两个不同子模块中的组件作为独立脚本,建议使用非相对导入路径:
from Root.outlook.outlook import Outlook
You will need to have the module Root in a folder included in your PYTHON_PATH environment variable 您需要将模块Root放在PYTHON_PATH环境变量中包含的文件夹中
Also don't forget to add the init .py to all the folders 同样不要忘记将init .py添加到所有文件夹中
some_directory/
Root/
__init__.py
outlook/
__init__.py
outlook.py
test/
__init__.py
test.py
EDIT1: EDIT1:
Depending on how you want to import from inside test.py you can face 2 different scenarios 根据您要从test.py内部导入的方式,您可以面对2种不同的情况
from Root.outlook.outlook import Outlook
will require the 'Root' directory to be accessible by python 将要求python可以访问'Root'目录
PYTHON_PATH="...:...:/path_to_some_directory_that_contains_Root"
while 而
from outlook.outlook import Outlook
will required 将需要
PYTHON_PATH="...:...:/path_to_Root"
the ... indicates other paths already present in the environment variable which you should leave as they are. ...表示环境变量中已经存在的其他路径,您应保留原样。
The 'adding to the PYTHON_PATH represent the manual way to quickly achieve your desired result. “添加到PYTHON_PATH中”表示手动获得快速结果的方法。 In reality, what you should do when working with a module is install it, by using a 'setup.py' script with disutils inside the Root directory and the command
实际上,通过使用“ setup.py”脚本将其安装在模块上,方法是在根目录和命令中使用带有disutils的脚本
python setup.py install
you are importing wrong. 您输入错误。
from outlook.outlook import Outlook
Root/ --outlook/ ----outlook.py --test/ ----test.py
In your case you are checking inside the outlook folder so you have to point to the file as well. 在您的情况下,您正在Outlook文件夹中进行检查,因此您也必须指向该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.