skip to Main Content

I am using WSL2 to work on some Python project, but black is not auto-formatting in VSCode (Remote – WSL).

System info:

  • Base system: Windows 11 Pro x64
  • WSL2 system: Ubuntu-22.04-LTS
  • settings.json path in WSL: /home/<user>/.vscode-server/data/Machine/settings.json

My settings.json looks like:

{
  // Python linting and formatting customizations..
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.linting.flake8Args": ["--max-line-length=100", "--ignore=E501"],
  "python.formatting.provider": "black",
  "python.formatting.blackArgs": ["--line-length", "100"],
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    },
    "editor.formatOnSave": true
  }
}

This same settings works on my Windows 11 system. In local Windows, whenever I create a virtual environment for a python project and save a python file, vscode automatically asks me to install flake8 and black in the venv. But nothing of the sort happens in WSL.

Even if I install black in WSL Python venv, it does not auto-format the Python code; and there are no logs related to black visible in either Output > Python or Output > Log (Main) tab.

But manual formatting works after I install black in venv:

(venv) asif@MSI:~/vscode/myproject/$ black app_pkg/models.py 
reformatted app_pkg/models.py

All done! ✨ 🍰 ✨
1 file reformatted.

Note: I even tried adding "python.formatting.blackPath": "./venv/bin/black" to settings.json file, but it didn’t work.

Any help would be much appreciated. Thanks in advance!

Edit: As suggested, I have these two settings enabled in my system,
Format on save applied universally:
format on save settings
Python code formatter set as black:
Python default formatter settings

Still I am unable to make the Python formatOnSave work in VSCode-WSL.

2

Answers


  1. But manual formatting works after I install black in venv

    It can be seen that black can work.Now let’s set up automatic formatting for vscode:

    First open the settings of vscode, search for format on save, and then check it. Set this step, and the code will be automatically typeset every time the file is saved.

    enter image description here

    Then search Python formatting provider and select black.

    enter image description here

    Login or Signup to reply.
  2. I think you need to install python first in your WSL.

    had the same issue. now it works!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search