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:
- in the
/project/.vscode/launch.json
"cwd": "${workspaceFolder}/src"
- 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!
CodePudding user response:
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.
CodePudding user response:
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.