Trung Kiên
Trung Kiên

Reputation: 185

ModuleNotFoundError: No module named XXX

This is a part my workspace directory structure:

workspace
+-- .vscode
    +-- launch.json
+-- main
    +-- __init__.py
    +-- main.py
+-- utils
    +-- __init__.py
    +-- func.py
    +-- func2.py

In func.py I wrote:

import sys
sys.path.append('.')

from func2 import func2

def func1():
    ...
    func2()
    ...
    return ...

And in main.py I wrote:

import sys
sys.path.append('.')

from utils.func import func1

When executing main.py, vscode throws an error:

Traceback (most recent call last):
  File "...\workspace\main\main.py", line 4, in <module>
    from utils.func import func1
  File "...\workspace\utils\func1.py", line 4, in <module>
    from func2 import func2
ModuleNotFoundError: No module named 'func2'

I tried calling func1 inside file func.py and run that file, it worked perfectly. Why can't I call it in main.py ?

Upvotes: 0

Views: 725

Answers (2)

Anirban Bhattacharya
Anirban Bhattacharya

Reputation: 12

According to me you are getting directory related issues. Try placing the necessary files in a same directory.

Upvotes: 0

anurag
anurag

Reputation: 1932

Here is an edit for your files (notice when executing main.py all paths are relative to that):

func2.py

import sys
sys.path.append('.')

def func2():
    print('Here is...\n')

func.py

import sys
sys.path.append('.')

from utils.func2 import func2    # The change is here; use the path relative to main

def func1():
    func2()
    
    return 0

main.py

import sys
sys.path.append('.')

from utils.func import func1

if __name__ == '__main__':
    func1()
    print('Hello World\n')

Upvotes: 1

Related Questions