This question is 3 years old: Code is working in pyCharm but not in Visual Studio Code
So, maybe this is the reason why it doesn’t work anymore. Anyway, I have this project structure:
It works perfectly when I run "main.py" under "01SpaceInvaders", but the same code in vscode returns this error:
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:UserssalvaDocumentsVS Codepysandboxgame1SpaceInvadersmain.py", line 5, in <module>
from game.sdfengine.locals import *
ModuleNotFoundError: No module named 'game'
For sure, there is a configuration missing in my VSCode, but I don’t know what. Any clue?
This is how I execude the code from VSCode:
- I open a new terminal
- Go to
01SpaceInvaders
py main.py
Following the comments it seems VSCode configuration problem:
Where can I find the file to edit and a guide to understand how to edit it?
2
Answers
The most straightforward way is to indicate the path by adding the following at the top of the code:
You can also configure PYTHONPATH using
.env
fileThe issue here is that python does not know where to find the directory called
game
since it is not an installed python library (it’s a directory in your project structure)To let python know of directories that it should consider as libraries to import from you can use the environment variable PYTHONPATH (see documentation here)
You can:
PYTHONPATH
environment variable temporarily from command line:configure it permanently on windows by searching for "edit environment variables" in your start menu
edit your vscode
settings.json
file (see documentation here) ctrl + shift + p -> "open user settings (JSON)" and add: