You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置isort与VSCode,仅超行宽时拆分Python导入语句?

解决方案

1. 强制VSCode使用isort处理导入整理

当前VSCode的source.organizeImports默认可能调用Pylance而非isort,导致行为与命令行isort不一致。修改settings.json如下:

{
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "ms-python.black-formatter",
    "[python]": {
        "editor.codeActionsOnSave": {
            "source.organizeImports": "explicit"
        },
        "editor.codeActionsOnSaveExplicit": [
            "source.organizeImports.isort"
        ]
    },
    "isort.args": ["--line-length", "120", "--profile", "black"]
}

2. 确保VSCode使用虚拟环境中的isort

  • 点击VSCode左下角的Python环境选择器,切换到Poetry创建的虚拟环境
  • 若环境未自动识别,可手动指定路径:
// macOS/Linux
"python.pythonPath": "./.venv/bin/python"
// Windows
"python.pythonPath": "./.venv/Scripts/python.exe"

3. 验证isort版本一致性

命令行执行poetry run isort --version,VSCode终端切换到虚拟环境后执行isort --version,确保两者版本一致。若版本不同:

  • 执行poetry add isort --dev更新虚拟环境中的isort
  • 或在VSCode中手动指定isort路径:
// macOS/Linux
"isort.path": ["./.venv/bin/isort"]
// Windows
"isort.path": ["./.venv/Scripts/isort.exe"]

原理说明

命令行中isort --line-length 120 --profile black的行为符合预期,但VSCode默认的导入整理工具并非isort,导致配置不生效。通过指定source.organizeImports.isort作为显式处理工具,同时保证VSCode使用与命令行一致的虚拟环境及isort版本,即可实现仅当导入语句超过120字符时才拆分的需求。

内容的提问来源于stack exchange,提问作者Mikhail Goussarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:25:05