skip to Main Content

My project file structure is like this,

project/src/test/myscript.py
project/src/utils/file_utils.py

When I run myscript.py, which has from utils import file_utils, it gave me error:

ModuleNotFoundError: No module named ‘utils’

Previously in Pycharm IDE I did not get this type of error (maybe due to _ init _.py), the subdirs of the same parent dir could be detected. But not sure for VSCode, is there something I need to add for specifying the file structure? And I opened the folder project as my VSCode workspace (not sure if where I open the workspace matters)

I tried adding:

  1. in the /project/.vscode/launch.json
"cwd": "${workspaceFolder}/src"
  1. or in the begining of myscript.py
import sys
import os
src_path = os.path.dirname(os.path.abspath('/project/src/'))
sys.path.insert(0, src_path)

But none of them works. Does anyone have any insights? Thank you very much!

3

Answers


  1. Yes, in Pycharm you didn’t get this error because it adds __init__.py file automatically when you create a python module. The python identifies the structure of your project through these files, if your folder does not have __init__.py python will understand it as just any folder.

    Login or Signup to reply.
  2. You could consider placing a .env file at the root of your project which adds your source directory to PYTHONPATH. i.e. something like

    >>> cat /project/.env
    PYTHONPATH=/project/src/
    >>>
    

    Your code will look a smidgen nicer without the explicit manipulation of sys.path.

    VSCode’s usage of .env files is documented here.

    Login or Signup to reply.
  3. Unlike pycharm, vscode uses the workspace as the root directory to retrieve files. The first method you try is to write it in the launch.json file, which is applicable to debug rather than running it directly. You can use the following code to import:

    from src.utils import file_utils
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search