VScode中debug模式下出现no module的exception

1,857 阅读1分钟

问题

在vscode使用过程中,有时需要通过vscode的debug模式进行单步调试。但是在点击start按钮后,系统却总是提示: ModuleNotFoundError: No module named 'xxx'。 已确认安装包没有问题,终端在不进入debug模式下,脚本运行也是正常,此问题让人很是费解。

解决过程

- 添加当前的根目录至工作目录

image.png

点击‘Add’操作后,在根目录下会生成一个文件:workspace.code-workspace。里面的具体内容如下:

{
	"folders": [
		{
			"path": ".."
		}
	],
	"settings": {},
	"launch": {
		"version": "0.2.0",
		"configurations": [
			
			{
				"name": "Python: Current File",
				"type": "python",
				"request": "launch",
				"program": "${file}",
				"cwd": "${workspaceFolder}",
				"console": "integratedTerminal"
			}
		]
	}
}

然而添加了工作目录后,再次尝试debug模式,问题依旧。

- 修改python解释器环境

继续尝试修改 setting.json 文件,将python解释器环境配置到所需的虚拟环境(我本人在本地已有python基础上新建了虚拟环境,目前所需的第三方包都安装到了此虚拟环境)。

{
  "python.defaultInterpreterPath": "/Users/leo.li/projects/bmw_proj/test-automation/.ta_venv/bin/python",
  "python.pythonPath": "/Users/leo.li/projects/bmw_proj/test-automation/.ta_venv/bin/python"
}

然并卵,debug时继续无效。

解决方案

修改launch.json, 新增‘env’ 和 ‘envFile’ 变量即可解决。

{
  // 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: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal",
      "env": {"PYTHONPATH":"${workspaceRoot}"},
      "envFile":"${workspaceFolder}/.env"
    }
  ]
}