Neil Jain
Neil Jain

Reputation: 21

Debug "ImportError: attempted relative import with no known parent package"

I have the following directory structure

Test/
    __init__.py
    __main__.py
    Package_1/
        __init__.py
        module_1.py
        module_2.py
    Package_2/
        __init__.py
        module_3.py
        module_4.py
        Subpackage/
            __init__.py
            module_3.py

The init.py files are empty

module_1.py

from .module_2 import function_1
function_1()


module_2.py

def function_1():
print('function_1')


module_5.py 

def function_2():
print('function_2')


main.py

from .Package_1.module_1 import *
function_1.py

I get the following output-

(base) C:\Users\Neilabh\Desktop\PS4-OP\STADS\Image Generation\Test>python -m main.py

Traceback (most recent call last):
  File "C:\Users\Neilabh\Miniconda3\lib\runpy.py", line 183, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "C:\Users\Neilabh\Miniconda3\lib\runpy.py", line 109, in _get_module_details
    __import__(pkg_name)
  File "C:\Users\Neilabh\Desktop\PS4-OP\STADS\Image Generation\Test\main.py", line 1, in <module>
    from .Package_1.module_1 import *
ImportError: attempted relative import with no known parent package

I have tried various permutations to import a file from an import within the main file. I have been unable to get it right. Any help in debugging the same is welcome. If there is another way of getting this done, it would be most welcome.

Thank you.

Upvotes: 2

Views: 1957

Answers (1)

ywbaek
ywbaek

Reputation: 3031

Instead of

C:\Users\Neilabh\Desktop\PS4-OP\STADS\Image Generation\Test>python -m main.py

Try this:

C:\Users\Neilabh\Desktop\PS4-OP\STADS\Image Generation\>python -m Test.main

Upvotes: 1

Related Questions