Search code examples
pythonjsonvisual-studio-code

`SyntaxError: invalid syntax` when starting Python script in VS Code on macOS


I'm trying to run a Python script from Visual Studio code, but the script fails to run and crashes with a SyntaxError pointing to the comment at the beginning of launch.json.

launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python | Default",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "pythonPath": "${config:python.pythonPath}",
            "program": "${file}",
            "cwd": "${workspaceFolder}",
            "env": {},
            "envFile": "${workspaceFolder}/.env",
            "debugOptions": [
                "RedirectOutput"
            ]
        }
    ]
}

Terminal Output:

File ".../.vscode/launch.json", line 2
    // Use IntelliSense to learn about possible attributes.
     ^
SyntaxError: invalid syntax

settings.json:

{
    "python.pythonPath": "${workspaceFolder}/venv/bin/python"
}

I was working on my Windows machine earlier and all of this worked perfectly fine. For some reason, VSCode is trying to run the launch.json file through Python and // is an invalid comment syntax in Python. If I remove the comments, I get this error:

Traceback (most recent call last):
  File ".../.vscode/launch.json", line 8, in <module>
    "stopOnEntry": false,
NameError: name 'false' is not defined

If I use Python's False, I don't crash but nothing happens and my script does not run. It seems very much like launch.json is being parsed by Python erroneously. Any fix for this?


Solution

  • I found my problem. I did not update the program key to always point to my main.py. Instead, the current open file was being executed as a Python script -- launch.json Changing the program key or navigating to a different file solved the problem. Obvious once you notice it!

    For Example:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Python: Current File",
                "type": "python",
                "request": "launch",
                "program": "main.py",
                "console": "integratedTerminal",
                "justMyCode": true
            }
        ]
    }