简体   繁体   English

Visual Studio Code - Python - Windows - Black 运行但不格式化代码

[英]Visual Studio Code - Python - Windows - Black runs but does not format code

I am running VS Code on Windows and am trying to set up black to format my Python code when saving.我在 Windows 上运行 VS Code,并尝试设置黑色以在保存时格式化我的 Python 代码。 It looks like black is running whenever I save, but the file is not getting updated.每当我保存时,看起来黑色正在运行,但文件没有得到更新。 When I look at the Output > Python tab in VS Code, it looks like black is running with the --diff flag, which is why I'm assuming that the file does not update.当我查看 VS Code 中的“输出”>“Python”选项卡时,看起来黑色正在使用--diff标志运行,这就是我假设文件没有更新的原因。 Does anyone know how to fix this?有谁知道如何解决这一问题?

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

Here is my .vscode/settings.json in the project:这是我在项目中的 .vscode/settings.json :

{
    "editor.defaultFormatter": "ms-python.python",
    "python.pythonPath": "C:\\Users\\me\\Anaconda3\\python.exe",
    "python.formatting.provider": "black"
}

The fix for me was to install black package in my virtualenv.我的解决方法是在我的 virtualenv 中安装黑色包。 Using the one installed at the system level was not working, even though that one worked from terminal, etc.使用在系统级别安装的那个是行不通的,即使那个是从终端等工作的。

The --diff has no influence on the formatting. --diff对格式没有影响。

You can try to format it directly with black in the terminal to check whether it works or not.您可以尝试在终端中直接用黑色格式化它以检查它是否有效。

If it does not work, you can try to switch to some other formatters.如果它不起作用,您可以尝试切换到其他一些格式化程序。

I had a similar problem (in Ubuntu though) under poetry virtual environment, and I solved by changing the black path to just "black".我在诗歌虚拟环境下遇到了类似的问题(尽管在 Ubuntu 中),我通过将黑色路径更改为“黑色”来解决。

I guess somehow giving a path does not operate well with the virtual environment.我猜想以某种方式提供路径在虚拟环境中效果不佳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM