简体   繁体   中英

Can't import modules in Python 3

I have a layout like

pylib/
    apps/
        main.py
    libs/
        MyClass.py
    __init__.py

In which MyClass.py is

class MyClass:
    pass


if __name__ == "__name__":
    obj = MyClass()

and in main.py I've tried

from pylib.libs.MyClass import MyClass
obj = MyClass()

And got

ModuleNotFoundError: No module named 'pylib'

from ..libs.MyClass import MyClass
obj = MyClass()

And got

ImportError: attempted relative import with no known parent package

from libs.MyClass import MyClass
obj = MyClass()

And got

ModuleNotFoundError: No module named 'libs'

If someone knows how to fix it I'd be very glad

The issue is that the folder that contains pylib is not on the path. You can fix this by adding the containing folder to the PYTHONPATH environment variable.

➜  apps  python3 main.py        
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from pylib.libs.MyClass import MyClass
ModuleNotFoundError: No module named 'pylib'
➜  apps  cd ..
➜  pylib  cd ..
➜  temp-code  export PYTHONPATH=`pwd`  # This is the fix!
➜  apps  python3 main.py        
(no error)

Another way you could do it is to include the logic in your code:

import os
import sys

project_home = '/home/username/temp-code/'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

In this case, the pylib folder is inside of the temp-code folder and this code runs before you import your class.

Hope that helps!

Reference: https://docs.python.org/3/using/cmdline.html?highlight=pythonpath#envvar-PYTHONPATH

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