Python中如何配置vscode以优化开发环境
我有个 hello.py 文件,我要直接运行这个文件,但是引用的 python 是系统自带的,不是我虚拟环境中的。网上资料说需要设置 tasks.json,贴下我 tasks.json 的配置,
{
"version": "0.1.0",
"command": "/Users/apple/github/flasky-blog/venv/bin/python",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}
我已经把 command 的值也就是 python 路径给写死了,但是直接 run hello.py 还是用的是系统的 python。
不过最让我困惑的是,我已经在 setting.json 中指定了"python.pythonPath": "${workspaceRoot}/venv/bin/python3",而且 debug 是没有问题,再贴下我的 debug.json 配置,
{
"version": "0.2.0",
"configurations": [
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": true,
"pythonPath": "${config:python.pythonPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
]
}
唯独这个 tasks.json,按道理说我已经指定路径了,可是我一 run 就读到系统的 python 路径了。
给帮忙看看。谢谢
Python中如何配置vscode以优化开发环境
善用搜索 https://stackoverflow.com/questions/37642045/use-virtualenv-with-python-with-visual-studio-code-in-ubuntu http://www.cashqian.net/blog/00148782264567542a619e58913497eb7f15af7426517ba000
配置VSCode进行Python开发,核心是安装Python扩展和配置几个关键设置。
首先安装Microsoft官方的Python扩展(ms-python.python),这是基础。然后建议安装Pylance(ms-python.vscode-pylance)作为语言服务器,它能提供更好的智能提示、类型检查和代码补全。
关键配置在.vscode/settings.json里:
{
"python.defaultInterpreterPath": "你的Python解释器路径(如venv/bin/python)",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.formatting.provider": "black",
"python.formatting.blackArgs": ["--line-length", "88"],
"python.testing.pytestEnabled": true,
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}
解释一下:formatOnSave保存时自动用Black格式化代码,organizeImports自动整理import语句。用Pytest做测试框架。Black的行长我设88,你也可以按PEP 8的79。
调试配置在.vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
这样就能直接按F5调试当前文件。
总结:装对扩展、配好自动格式化和测试,开发效率能提一大截。
问题已经解决了 。我装了个 Run Code 插件。这样就可以直接 run 起来了。当然前提还是要设置 python 解释器的路径,也就是我上文中说的 settting.json 里的内容。所以不需要设置那个 tasks.json。这个插件可以很方便的 run code。
3q
我记得 vscode 还可以随时切换 env 的, 这个也挺方便
F1> interpreter -> Python: Selelct Workspace Interpreter
还是 pycharm 好用,嘿嘿。
如果要用 VSCode 的断点调试,指定 Python Path,配置里这么写:
“python.pythonPath”: "python3"
如果用 Code runner 插件:
“code-runner.executorMap”: {
“python”: “python3”
},
补充一下,pythonPath 里写 Python 可执行文件的绝对路径比较好。
这个其实就会自动生成 setting.json 里的内容
这个要看实际情况,因为我的每个项目都是用一个单独的 virtual env,所以写绝对路径就不太适用了
用 pythonVSCode 插件的话, 在已经激活的 virtualenv 里运行 code 会自动使用当前的 virtualenv

