将问题镜像至:
我想配置 VSCode 如何调用 isort,这样我就可以在 .py 文件中调用
Organize imports
时进行自定义。
特别是,VSCode 已开始删除两个 isort-section 之间的空行,不知道为什么。
from django...
from myproject... # removing blanck line between 2 sections
您可以使
isort
与black
兼容,并在保存文档时享受格式化代码。有两种方法可以实现这一目标:
Black
上配置 Isort
和 pyproject.toml
的设置。
在根目录的项目文件夹中,创建/更新您的 pyproject.toml
文件:[tool.isort]
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
line_length = 88
profile = "black"
settings.json
并配置 Black
和 Isort
。{
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"python.formatting.provider": "black",
"isort.args": ["--profile", "black"],
}
source.organizeImports: true
保存文档后会自动运行 Isort。
在 VS Code 中,“Python”扩展为我们提供了以下设置,可以将同一模块中的特定导入合并到单个导入语句中,并按字母顺序组织导入语句。 (在“settings.json”文件中)
"python.sortImports.args": ["-rc", "--atomic"],
在 VS Code 中使用“对导入进行排序”,请参考此文档:在 VS Code 中对导入进行排序。
您可以将Isort扩展安装到VSCode,如下所示。 *我在 Windows 11 上使用 Anaconda:
然后,将以下代码设置为
settings.json
。 *你可以看我的回答解释如何打开settings.json
:
// "settings.json"
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
下面是我完整的
settings.json
以及上面的代码:
// "settings.json"
{
"python.defaultInterpreterPath": "C:\\Users\\kai\\anaconda3\\python.exe",
"window.zoomLevel": 3,
"files.autoSave": "afterDelay",
"breadcrumbs.enabled": false,
"[python]": { // Here
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}
请参阅我的回答 如何找到 vscode 到底使用的是哪个 isort 我在其中描述了查看实际发生情况的步骤。您将看到该命令以及参数。 Microsoft Python 插件内置的 isort 版本不显示为 isort。相反,它是 sortImports.py。它有路径,因此您可以查看代码以获取更多信息。
就我而言,isort 没有按照我想要的方式进行排序。 这是 MWE:
import numpy as np
import pandas as pd
import seaborn as sea_bor_nnnn
import matplotlib.pyplot as plt
import torch
import os
保存文件后,我得到以下输出
import os
# why is it inserting an empty line here?
import numpy as np
import torch
import pandas as pd
import seaborn as sea_bor_nnnn
import matplotlib.pyplot as plt
# here inserts only 1 blank line instead of 2
#actual code goes here
dfdf
dfdfd
ddf
我的首选格式如下
import os
import torch
import numpy as np
import pandas as pd
import seaborn as sea_bor_nnnn
import matplotlib.pyplot as plt
# actual code goes here
注意所有导入是如何根据长度排序的,中间没有空行,并且实际代码在模块导入的 2 个空行之后开始。
有什么想法如何在 vscode 中实现这一点吗?也许可以将
isort
与 autopep8
或 flake8
结合使用,而不是 black