skip to Main Content

I have the following file structure:

.
├── main.py
└── modules
    ├── __init__.py
    ├── package1
    │   ├── __init__.py
    │   ├── module1.py
    │   ├── module2.py
    │   └── __pycache__
    │       ├── __init__.cpython-310.pyc
    │       └── module1.cpython-310.pyc
    ├── package2
    │   ├── __init__.py
    │   ├── module_r.py
    │   └── __pycache__
    │       ├── __init__.cpython-310.pyc
    │       └── module_r.cpython-310.pyc
    └── __pycache__
        └── __init__.cpython-310.pyc

This is the code inside modules/package1/module1.py:

def func():
    print("the function was called")

and this is the code inside modules/package2/module_r.py:

from ..package1.module1 import func

func()

Also, this is the code inside main.py:

from modules.package2 import module_r 

When I execute the main file using the command: python3 main.py I get the expected result printed to the terminal ("the function was called") However, when I try to run python3 modules/package2/module_r.py I get this error:

Traceback (most recent call last):
  File "/home/santiago/Documents/test-python-packages/modules/package2/module_r.py", line 1, in <module>
    from ..package1.module1 import func
ImportError: attempted relative import with no known parent package

I have also tried absolute imports and this code:

import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from modules.package1.module1 import func

but I get the same result. How can I properly import my packages so that I can both import them from the main file and execute them as a script?

2

Answers


  1. I found a way to run ur code.
    This is the original web where I found the solution.

    In the ".", do cd ..

    Then do python3 -m try.modules.package2.module_r

    The reason of the error is that u are just running a single python file, not a python project. So there is no relation between the files.

    result

    Login or Signup to reply.
  2. Your absolute import should look like this

    I replaced . with 123 and opened it as a workspace.

    import sys
    # sys.path.append('e:\Desktop\123\modules')
    # sys.path.append('./modules')
    
    import os
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from package1.module1 import func    # There's no `modules.` here.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search