如何在 VSCode 中使用 yapf(或 black)

新手上路,请多包涵

我使用以下方法安装了 yapf:

 conda install yapf

并在我的 .vscode/settings.json 文件中添加下一行:

 {
    //"python.linting.pylintEnabled": true,
    //"python.linting.pycodestyleEnabled": false,
    //"python.linting.flake8Enabled": true,
    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        " — style",
        "{based_on_style: pep8, indent_width: 4}"
    ],
    "python.linting.enabled": true,
}

但我不明白如何使用它——它在格式错误的脚本中没有显示任何错误:

 import pandas as pd

class MyClass(object):
    def __init__(self, some_value: int):
        self.value = some_value
    def one_more_function(self, another_value):
        print(another_value)
myObject = MyClass(45)
myObject.one_more_function(2)
my__object2 = MyClass(324)

    print('ok')
def some_foo():
    """
    """
    pass

原文由 Mikhail_Sam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

问题出在错误的设置上。要使用 yapf、black 或 autopep8,您需要:

  1. 安装yapf/black/autopep8(pip install black)
  2. 配置 .vscode/settings.json 以下方式:

文件的一部分:

 {
    "python.linting.enabled": true,
    "python.linting.pylintPath": "pylint",
    "editor.formatOnSave": true,
    "python.formatting.provider": "yapf", // or "black" here
    "python.linting.pylintEnabled": true,
}

关键选项 - "editor.formatOnSave": true, 这意味着 yapf 每次保存时格式化您的文档。

原文由 Mikhail_Sam 发布,翻译遵循 CC BY-SA 4.0 许可协议

扩展 @Mikhail_Sam 答案。您可能想根据需要使用单独的配置文件。通过这种方式,您可以将项目设置与 VS Code IDE 分离。为此,您需要创建 .style.yapf

 type null > .style.yapf   (for windows environment)
touch .style.yapf    (for MacOS, Linux environments)

将规则添加到 .style.yapf ,例如:

 [style]
based_on_style = google
spaces_before_comment = 4
indent_width: 2
split_before_logical_operator = true
column_limit = 80

不要忘记从您的 VS 代码中删除 settings.json 以下设置。他们覆盖 .style.yapf

 "python.formatting.yapfArgs": [
  "--style={based_on_style: google, column_limit: 80, indent_width: 2}"
],

我在 settings.json 中的其他 VS Code 设置:

 "[python]": {
  "editor.defaultFormatter": "ms-python.python",
  "editor.formatOnSave": true
},
"python.formatting.provider": "yapf",
"python.formatting.yapfPath": "C:\\ProgramData\\envCondaPy379\\Scripts\\yapf.exe",
"python.formatting.blackPath": "C:\\ProgramData\\envCondaPy379\\Scripts\\black.exe",
"python.linting.lintOnSave": true,
"python.linting.enabled": true,
"python.linting.pylintPath": "pylint",
"python.linting.pylintEnabled": true,

根据 YAPF 文档:YAPF 将按以下方式搜索格式样式:

  1. 在命令行指定 >> VS Code settings.json
  2. 在当前目录或其父目录之一的 .style.yapf 文件的 [style] 部分中。
  3. 在当前目录或其父目录之一的 setup.cfg 文件的 [yapf] 部分中。
  4. 在主目录中 ~/.config/yapf/style 文件的 [style] 部分。
  5. 如果没有找到这些文件,则使用默认样式 (PEP8)。

原文由 Roman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题