mireumireu
mireumireu

Reputation: 995

Formatter black is not working on my VSCode...but why?

I have started using Python and Django and I am very new in this field. And, this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue...

When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message.

So what I did was...

  1. manually input 'pipenv install flack --dev --pre' on terminal.

  2. manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder.

  3. Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8

The bottom code is from settings.json (on vscode folder).

{
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.formatting.provider": "black", # input manually
  "python.linting.flake8Args": ["--max-line-length=88"] # input manually
}

I found a 'black formatter' document. https://github.com/psf/black & it stated... python -m black {source_file_or_directory} & I get the following error message.


    Usage: __main__.py [OPTIONS] [SRC]...
Try '__main__.py -h' for help.

Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist.

Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not.

Can I hear your advice? At least some direction to go, please. Thanks..

Upvotes: 80

Views: 168919

Answers (24)

schimmy
schimmy

Reputation: 393

For me, the way to fix was to change the black-formatter.importStrategy to fromEnvironment instead of useBundled. They update the black formatter version in the extension every now and again, and if it's a different version than your command line version they may disagree, so it's better IMO to just use the black from the environment.

enter image description here

Upvotes: 0

user1909643
user1909643

Reputation: 31

As a workaround, install "Run on Save" from emeraldwalk

"VSCode settings.json (open it with Ctrl-P + settings)

add these to the file

"emeraldwalk.runonsave": {

        "commands": [
            {
                "match": "\\.py$",
                "cmd": "black ${file}"
            }
        ]
    },

this is my settings

"emeraldwalk.runonsave": {

        "commands": [
            {
                "match": "\\.hcl$",
                "cmd": "terragrunt hclfmt --terragrunt-hclfmt-file ${file}"
            },
            {
                "match": "\\.tf$",
                "cmd": "terraform fmt ${file}"
            },
            {
                "match": "\\.tfvars$",
                "cmd": "terraform fmt ${file}"
            },
            {
                "match": "\\.py$",
                "cmd": "black ${file}"
            }
        ]
    },

Upvotes: 0

MMJ
MMJ

Reputation: 662

My Bit Defender AV on Windows 11 is blocking the ".\venv\Scripts\black.exe" and keeping it in Sandbox... great!! :(

Thanks to @wisbucky's answer... After trying what he advised, I could see that the that Bit Defender AV was blocking the black.exe in Sandbox. After a few minutes the AV analysis finished and the black.exe file was allowed to run... then, I could see that there was a syntax error that VS Code didn't warn about, and that was preventing Black from working.

After correcting the syntax everything returned to normal.

Upvotes: 0

abnerl
abnerl

Reputation: 783

2024/02/19 updated

The previous solution doesn't work anymore.

There're two issues:

  1. vscode has new official extension
  2. different black output from vscode extension and black in your python virtual environment

If you just want to use 'black' formatter and don't care issue #2. Just install vscode black extension

enter image description here

I revised my solution for issue #2
a. install black extension first
b. set up your virtual environment, install black init and set your project interpreter to it
c. go to user setting, set Black-formatter: Path to "black" in your virtual environment

"black-formatter.path": ["black"]

NOTE: Install 'black' in the python environment you need, remove global 'black'

===== Obselete solution for old vscode =====
Attach my finding for those who still can't solve the Black formatting issue in VS Code.

First, you have to install Black globally or locally (if you use virtual env like conda).

Then, make sure your VS settings as following, set python default formatter provider as 'black':

enter image description here

Finally, open settings.json of your VS Code, add the following segment for it.

"[python]": {
    "editor.defaultFormatter": null,
    "editor.insertSpaces": true,
    "editor.tabSize": 4,
    "editor.formatOnSave": true
}

The key point is:

"editor.defaultFormatter": null

If you still use "editor.defaultFormatter": "black" as many old posts suggest, the Black formatter will not work in newer VS Code.

Upvotes: 67

neves
neves

Reputation: 39133

Update 2023-09-15:

Now VSCode has a Microsoft oficial Black Formatter extension. It will probably solve your problems.

Original answer:

I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from the command line if you need to format a lot of files at once.

First, check if you have this in your VSCode settings.json (open it with Ctrl-P + settings):

"python.formatting.provider": "black",
"editor.formatOnSave": true,

Remember that there may be 2 setting.json files: one in your home dir, and one in your project (.vscode/settings.json). The one inside the project prevails.

That said, these kind of problems usually are about using a python interpreter where black isn't installed. I recommend the use of virtual environments, but first check your python interpreter on the status bar:

Python interpreter in the status bar of VSCode

If you didn't explicitly select an interpreter, do it now clicking on the Python version in your status bar. You can also do it with Ctrl-P + "Python: Select Interpreter". The status bar should change after selecting it.

Now open a new terminal. Since you selected your interpreter, your virtual environment should be automatically activated by VSCode. Run python using your interpreter path and try to import black:

$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import black
>>> 

Failed import? Problem solved. Just install black using the interpreter from the venv: python -m pip install black. You also can install using Conda, but in my experience VSCode works better with pip.

Still not working? Click in the "OUTPUT" tab sibling of the TERMINAL and try to get more info at the "Log" output (if you use the newer Black plugun it may be called "Black Formatter"). Select it in the pull down menu:

log output of vscode

Upvotes: 121

Antoine
Antoine

Reputation: 936

Following the answer above (check the logs in the OUTPUT), I found the following message(s):

[info] Formatting requested before server has started.

The solution was to press CTRL+SHIFT+P and execute the command

BlackFormatter: Restart Server

Upvotes: 1

You can install Black extension to VSCode as shown below. *I use Anaconda on Windows 11:

enter image description here

Then, set the code below to settings.json. *You can see my answer explaning how to open settings.json:

// "settings.json"

"[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
}

This below is my full settings.json with the code above:

// "settings.json"

{
    "python.defaultInterpreterPath": "C:\\Users\\kai\\anaconda3\\python.exe",
    "window.zoomLevel": 3,
    "files.autoSave": "afterDelay",
    "breadcrumbs.enabled": false,
    "[python]": { // Here
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true
    }
}

Upvotes: 5

Joep
Joep

Reputation: 834

Check if the formatter is configured correctly by calling the 'Format Document' action (ctrl+shift+p). This prompted me with a message to choose the formatter. After that everything worked as expected.

format document

Upvotes: -2

Matt Najarian
Matt Najarian

Reputation: 181

It was a challenging issue for me to resolve. I even reinstalled my VSCode and Black-Formatter several times. Finally I found the issue using the following method. In the VSCode click on OUTOUT and from the dropdown menu select Black-Formatter. There in the logs you will see the issue (as in screenshot below). Here for me it was that I had the following items in my .gitignore file. Disabling the last two items solved the issue for me (still doesn't make sense that it broke the black formatter)

__pycache__/
*/__pycache__/
*\__pycache__\

enter image description here

Upvotes: 1

Brad
Brad

Reputation: 170

In my case I had accidentally uninstalled one of black's dependencies, mypy-extensions. Vscode did not show an error in the UI or the output logs. Try reinstalling black with pip install black --force-reinstall.

Upvotes: 2

wisbucky
wisbucky

Reputation: 37797

Another possibility is that a syntax error is preventing Black from working. Black will not apply any formatting changes if there is a syntax error.

However, VS Code still displays "Formatting with Black" in the status bar and silently fails.

You can verify this by running Black from the command line, which will show the error if there is one:

$ black foo.py
error: cannot format foo.py: Cannot parse: 328:4:     :

Oh no! 💥 💔 💥
1 file failed to reformat.

Upvotes: 4

mobeen ali
mobeen ali

Reputation: 105

If you are working on dev container then you might need to install Black Formatter extension. It worked for me, here is the link:

https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter

Upvotes: 2

yemy
yemy

Reputation: 838

Probably you have conflicts with your default formatter just add "[python]": { "editor.defaultFormatter": null } to your Open User Settings in VSC.

"editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "python.formatting.provider": "black",
  "[python]": { "editor.defaultFormatter": null }

Upvotes: 3

John Targaryen
John Targaryen

Reputation: 1194

Nothing in this question worked for my black. I gave up and switched default formatter in Settings > UI to autopep8 instead and everything worked.

Upvotes: 1

brocla
brocla

Reputation: 187

Yet another reason that black may stop working when run from vs code...

Perhaps you have started using Python 3.10

Black will fail if new features like Structural Pattern Matching are used. VS Code fails silently. No formatting happens. It appears that black isn't working.

Try running black from the command line to see if there are error messages.

This is what I got:

$ black my_code.py 
error: cannot format my_code.py: Cannot parse: 57:14:         match rec.split():
Consider using --target-version py310 to parse Python 3.10 code.
Oh no! 💥 💔 💥
1 file failed to reformat.

I had to add --target-version=py310 to VS Code's blackArgs, like this:

"python.formatting.blackArgs": ["--target-version=py310"]

Note the equals (=) sign.

Upvotes: 2

Stephen Herr
Stephen Herr

Reputation: 111

Another possibility is that you have added incorrectly formatted black arguments. The plugin wants every space-separated option to be added as a it's own "item" in the Settings UI like so: black args setting

You should be able to see the args pass through correctly into the Output->Python console like so: good black command

It should not look like this:

bad black command

Upvotes: 6

Mark
Mark

Reputation: 180531

There is a new extension, currently pre-release, for formatting with black. See v1.67 Release Notes, Python Black formatting.

From the README (vscode Marketplace: Black Formatter):

Usage

Once installed in Visual Studio Code, "Black Formatter" will be available as a formatter for python files. Please select "Black Formatter" (extension id:ms-python.black-formatter) as the default formatter. You can do this either by using the context menu (right click on a open python file in the editor) and select "Format Document With...", or you can add the following to your settings:

  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter"
  }

Format on save

You can enable format on save for python by having the following values in your settings:

  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  }

Upvotes: 10

hi2meuk
hi2meuk

Reputation: 2014

For me the problem was not black directly, but an invalid project settings file that it reads to find config settings. The root cause was not logged anywhere.

I found the cause by checking the OUTPUT tab with Python extension selected. It showed black being called with apparently no problems reported:

./.venv/bin/python -m black --diff --quiet ./myfile.py
cwd: .

However when I ran the same command in the terminal I got the error reported:

Error: Could not open file './pyproject.toml': Error reading configuration file: Invalid value (at line 18, column 10)

When this was fixed I could format my code manually and format on save was back too.

Upvotes: 2

CentAu
CentAu

Reputation: 11160

For those who see this and none of the above solutions work. If you set the black path to its absolute location it might solve the problem.

enter image description here

Upvotes: 9

Furkan
Furkan

Reputation: 59

I had that same problem and only cure was to remove

   "python.formatting.blackArgs": ["--skip-numeric-underscore-normalization"],  

from setting.json. It doesn't make sense but it works.

Upvotes: 3

nocibambi
nocibambi

Reputation: 2431

For those who have tried it all :).

Black will not work in VSCode if you have

  • a syntax error,
  • an IPython magic (e.g., %matplotlib inline).

Running black from the terminal on the file reveals these issues.

Upvotes: 14

Md. Sahaib Mridha
Md. Sahaib Mridha

Reputation: 61

If you are using windows operating system, then there is a simplest solution:

  1. Find out where you have installed black package. It can be on AppData/python/scripts
  2. Click on start menu and type "Edit the system environment variables" and select it.
  3. now click on environment variable and double click on 'path' from 'System Variable' portion to edit.
  4. now add the package path here like "Appdata/path/scripts;"

Hopefully now black will work fine on every save.

This solution works fine for me.

Note: Now you can use black from CLI.

Upvotes: 1

maxprehl
maxprehl

Reputation: 108

Like camab said, you can totally run it from the command line:

$ black file.py

You can also run it on a whole folder (directory) of python files:

ex if I have:

src/
| - module/
|   | - moduleFile.py
|   \ - __init__.py
|
\ - script.py

and run

$ black src

it would format moduleFile.py, __init__.py, and script.py.

As far as your VSCode config goes, I also like to have in settings.json

{
    "editor.formatOnSave": true,
    "python.linting.lintOnSave": true,
}

to make sure that every time I press save the file is getting linted and formatted.

If you ever have issues with linting/formatting in VSCode you can use the "Command Palette" (Ctrl+Shift+P) to force the following commands:

  • Python: Run Linting
  • Python: Select Linter
  • Format Document
  • Format Document With...

Which should produce a visual pop-up style error if there's actually a problem.

Hope this helps and happy coding!

Upvotes: 9

camab
camab

Reputation: 11

The best way to use black is through terminal in my opinion. All you need to do is install it on pip on terminal using: pip install black Then when it's installed you go onto terminal and type: black filename.py

the full line would be: black filepath/file.py So for a file called test.py located on desktop if on mac: black desktop/test.py If you want to do it on multiple files than do it individually to each file.

Upvotes: -3

Related Questions