有没有一种方法可以删除VS Code中未使用的Python导入文件?

Ree*_*ez0 8 python visual-studio-code

我真的很想知道Visual Studio Code中是否有一些Extension或其他手段可以帮助识别和删除任何未使用的导入。

我有很多这样的进口商品,并且已经接近40行。我知道其中一些未被使用,问题在于安全地将其删除。

from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from rest_framework import routers, serializers, viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
Run Code Online (Sandbox Code Playgroud)

小智 20

现在可以使用新版本的 pylance 扩展(我假设大多数在 VS Code 中使用 python 的人都会有)。

应该注意的是,optimizeImports使用ctrl + alt/option + o键绑定只会排序,不会删除未使用的导入(请参阅github 问题)。

我有自动保存功能,所以我更喜欢键盘快捷键。如果您有 pylance 扩展,您可以将以下内容添加到 keybindings.json 中

    {
        "key": "shift+alt+r",
        "command": "editor.action.codeAction",
        "args": {
            "kind": "source.unusedImports",
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以将键绑定更改为您想要的任何内容,但基本上当您按下键绑定(即shift + option/alt + r)时,它应该删除所有未使用的导入。

我相信如果您希望像上面那样自动保存,您可以将以下内容添加到您的settings.json中:

    "[python]": {
        "editor.codeActionsOnSave": {
          "source.organizeImports": "explicit",
          "source.unusedImports": "explicit",
        }
    }
Run Code Online (Sandbox Code Playgroud)


dan*_*ild 19

有趣的是,接受的答案没有解决问题 - 如何删除未使用的导入。

Pylint 不会修改代码,它会进行 linting。

诚然,仍然没有找到一个很好的 python 解决方案,但这是我所看到的:

1.

正如此答案中所述,VSCode 有一个基本的内置选项来自动组织导入,但对我来说效果不太好 - 您的情况可能会有所不同:

option+ Shift+O适用于 Mac

Alt+ Shift+O

如果这对您有用,您还可以使用以下命令在 VSCodes 设置中保存时执行此操作:

"editor.codeActionsOnSave": {
  "source.organizeImports": true
}
Run Code Online (Sandbox Code Playgroud)

2.

一个名为autoflake的模块可以做到这一点,例如:

autoflake --in-place --remove-unused-variables example.py
Run Code Online (Sandbox Code Playgroud)

但同样,里程可能会有所不同。

笔记

在 vscode github 中看到一个问题,指出“快速修复”功能已损坏,并且 vscode 团队表示这是 vscode python 插件的问题..可能很快就会修复..?


car*_*org 12

  • 确认您已在扩展中启用 Pylance。它附带了 Microsoft 的 vscode Python 扩展。

  • 在您的 .vscode/settings.json 中,添加以下内容

    "python.analysis.fixAll" : ["source.unusedImports"]
Run Code Online (Sandbox Code Playgroud)

现在,当您执行 Ctrl+Shift+P(命令面板)->“修复全部”时,这将清理未使用的导入。

  • 要在保存时自动清理,请添加以下内容:
    "editor.codeActionsOnSave": {
        "source.unusedImports": true,
    }
Run Code Online (Sandbox Code Playgroud)

您还可以在其中添加 "source.organizeImports": true 以便在保存时对导入进行排序。

  • 如果这不起作用,请尝试使用以下命令覆盖任何其他已安装的语言服务器:
    "python.languageServer": "Pylance",
Run Code Online (Sandbox Code Playgroud)

文档在这里


use*_*389 11

autoflake vscode 扩展会删除未使用的导入(而不仅仅是突出显示它们或对它们进行排序)。

该怎么办:

  1. 例如通过安装autoflake python 包pip install autoflake(这将由扩展使用)。
  2. 通过 vscode 中的扩展选项卡安装autoflake vscode 扩展。
  3. 可选:保存时运行 autoflake)安装Save and Run Ext vscode 扩展并将这些设置添加到settings.json
{
    "saveAndRunExt": {
        "commands": [
            {
                "match": ".*\\.py",
                "isShellCommand": false,
                "cmd": "autoflake.removeUnused"
            },
        ]
    },
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您向我展示“保存并运行”。但是一旦从 PyPI 安装,您就不需要 VSCode 扩展;你可以只输入 `"cmd": "autoflake -i --remove-all-unused-imports --remove-unused-variables ${file}"` (或任何你想要的选项)。请注意[内联`#noqa`](https://github.com/myint/autoflake#exclusion-specific-lines)排除特定导入自动删除的能力。 (4认同)
  • @NathanielJones 谢谢;好点!这样做的一个好处是直接使用 autoflake 为使用该包提供了额外的灵活性。对于那些有兴趣使用该方法的人,请注意,它需要 (1) 将设置的名称更改为“saveAndRun”(与“saveAndRunExt”),(2) 删除“isShellCommand”选项,并且( 3)使用“cmd”调用autoflake。然而,到目前为止,我实际上更喜欢“autoflake”扩展,因为它不会用命令污染我的终端和终端历史记录(当我按照建议使用“saveAndRun”时,命令在我的活动终端中运行)。 (2认同)

mik*_*ikm 10

你可以自己创建一个这样的VSCode Task 。

1.安装autoflake

pip install autoflake
Run Code Online (Sandbox Code Playgroud)

2.创建Vscode任务

  • 创建“.vscode/tasks.json”。

  • 添加以下设置。

选项 1. 不带activate

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "autoflake.removeUnusedImports",
            "command": "${command:python.interpreterPath}",
            // in Git Bash, "'${command:python.interpreterPath}'",
            "args": [
                "-m"
                "autoflake",
                "--in-place",
                "--remove-all-unused-imports",
                "${file}", 
                // in Git Bash, "'${file}'",
                // to run on all files in the working directory, replace "${file}", with "--recursive", "."
            ],
            "presentation": {
                "echo": true,
                "reveal": "silent",
                "focus": false,
                "panel": "dedicated",
                "showReuseMessage": false,
                "clear": false,
                "close": true
            },
            "problemMatcher": []
        },
    ]
}
Run Code Online (Sandbox Code Playgroud)

选项 2. 与activate

上述方法(将 autoflake 作为模块运行)至少适用于 Windows(适用于 PowerShell 和命令提示符、Git Bash),并且可能适用于其他操作系统或环境。(我不知道,因为我没有。请编辑。)或者,您可以使用activate.

电源外壳

"command": "${command:python.interpreterPath}\\..\\activate.ps1\r\n",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}", 
],
Run Code Online (Sandbox Code Playgroud)

命令提示符

"command": "${command:python.interpreterPath}\\..\\activate &&",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}", 
],
Run Code Online (Sandbox Code Playgroud)

重击

在 Bash 中,似乎文件路径必须用引号引起来。

"command": "source",
"args": [
    "\"${command:python.interpreterPath}\\..\\activate\"\r\n"
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "\"${file}\"", 
],
Run Code Online (Sandbox Code Playgroud)

3. 将任务添加到键盘快捷键(可选)

  • CtrlShiftP并选择Preferences: Open Keyboard Shortcuts (JSON)
  • 添加以下设置。
[
    {
        "key": "Shift+Alt+P",//Set this value to any you like.
        "command": "workbench.action.tasks.runTask",
        "args": "autoflake.removeUnusedImports",
    }
]
Run Code Online (Sandbox Code Playgroud)

这样,按下快捷键就会自动删除未使用的导入。

不幸的是,vscode-autoflake由于某种原因,它不适用于我的环境。


sin*_*pan 8

转到用户设置 json文件并添加以下内容:

"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
    "--enable=W0614"
]
Run Code Online (Sandbox Code Playgroud)

这将自动删除未使用的python导入。

这里有更多建议: 如何检查许多Python文件中未使用的导入?

  • Pylint 不会编辑您的代码。该命令只会突出显示未使用的导入。(对我来说,它不会突出显示个别的,只是突出显示行的开头,这不太理想) (7认同)
  • 如果您好奇用户设置在哪里,可以按“CMD/CTRL + SHIFT + P”,然后输入“settings.json”将其打开。 (6认同)
  • 会自动删除代码吗?但这对我不起作用。 (3认同)
  • @Dave:对我来说是一样的。像 from `django.utils import timezone` 这样的导入没有被标记,只有像 `import datetime` 这样的导入。有没有办法来解决这个问题? (2认同)

ruh*_*art 6

目前还没有明确的方法在 VSCode 上执行此操作,但您可以轻松地使用pycln来执行此操作,只需执行以下操作:

pip3 install pycln
pycln path_of_your_file.py -a
Run Code Online (Sandbox Code Playgroud)

然后所有未使用的导入都将被删除!


Had*_*tan 5

我建议添加pycln一个预提交钩子,它专为此任务而设计!

(它仅适用于 Python 3.6+)。

文档:https : //hadialqattan.github.io/pycln

回购:https : //github.com/hadialqattan/pycln

PyPI:https ://pypi.org/project/pycln/