【问题标题】:`SyntaxError: invalid syntax` when starting Python script in VS Code on macOS`SyntaxError: invalid syntax` 在 macOS 上的 VS Code 中启动 Python 脚本时
【发布时间】:2018-01-25 04:37:28
【问题描述】:

已解决:我忘记更新program 键以始终指向main.py,因此我的配置将当前打开的文件作为Python 脚本运行。正确设置program 键或导航到不同的文件是解决方案。当 StackOverflow 允许时,我会将我的答案标记为解决方案。


我正在尝试从 Visual Studio 代码运行 Python 脚本,但该脚本无法运行并崩溃,SyntaxError 指向 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"
            ]
        }
    ]
}

终端输出:

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

settings.json:

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

}

我之前在我的 Windows 机器上工作,所有这些都运行良好。出于某种原因,VSCode 试图通过 Python 运行 launch.json 文件,而 // 在 Python 中是无效的注释语法。如果我删除 cmets,我会收到此错误:

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

如果我使用 Python 的 False,我不会崩溃,但什么也没发生,我的脚本也不会运行。看起来很像launch.json 被 Python 错误地解析了。有什么解决办法吗?

【问题讨论】:

    标签: python json visual-studio-code


    【解决方案1】:

    我发现了我的问题。我没有更新program 键以始终指向我的main.py。相反,当前打开的文件作为 Python 脚本执行——launch.json 更改 program 键或导航到不同的文件解决了这个问题。一旦你注意到它就很明显了!

    【讨论】:

    • StackOverflow 2 天内不允许我将此标记为答案,但我会尽可能将其标记为答案。
    【解决方案2】:

    解决方案 1

    我认为更简单的解决方案是:

    1. 关闭编辑器组的launch.json
    2. 打开待调试的main.py等python文件
    3. [运行]-[开始调试](F5)

    正如 Nick 提到的,在编辑器中关注 launch.json 时,调试系统运行在 launch.json 本身,而不是 python 文件上。

    解决方案 2

    修改launch.json中的“程序”如下:

    "program": "${workspaceFolder}/main.py",
    

    对应

    始终指向 main.py 的程序键

    正如尼克所说。

    请注意,如果 main.py 放在较深的目录中,上述修改可能无法正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2021-07-27
      • 2015-06-10
      • 1970-01-01
      • 2022-12-12
      • 2022-07-02
      • 1970-01-01
      相关资源
      最近更新 更多