简体   繁体   中英

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 .

I am trying to import Outlook class in test.py file as follows -

from .outlook import Outlook

outlook = Outlook()

I am running the script from Root folder as - 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

Also don't forget to add the init .py to all the folders

some_directory/
    Root/
        __init__.py
        outlook/
            __init__.py
            outlook.py
        test/
            __init__.py
            test.py

EDIT1:
Depending on how you want to import from inside test.py you can face 2 different scenarios

from Root.outlook.outlook import Outlook

will require the 'Root' directory to be accessible by python

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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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