skip to Main Content

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:

enter image description here

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:

  1. I open a new terminal
  2. Go to 01SpaceInvaders
  3. 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


  1. The most straightforward way is to indicate the path by adding the following at the top of the code:

    import sys
    sys.path.append("./")
    

    enter image description here

    You can also configure PYTHONPATH using .env file

    Login or Signup to reply.
  2. The 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:

    1. configure your PYTHONPATH environment variable temporarily from command line:
    set PYTHONPATH=%PYTHONPATH%;C:UserssalvaDocumentsVS Codepysandbox
    
    1. configure it permanently on windows by searching for "edit environment variables" in your start menu

    2. edit your vscode settings.json file (see documentation here) ctrl + shift + p -> "open user settings (JSON)" and add:

    "terminal.integrated.env.windows": {
        "PYTHONPATH": "${env:PYTHONPATH};C:\your\path\here"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search