visual-studio-codecode-formattingpython-black

Visual Studio Code - Microsoft Black Formatter from command line?


I have the Microsoft Black Formatter extension in VSCode (in WSL, inside Windows 11). I can format opened python files with no problem, one-by-one, either using keyboard shortcut or right click on the file and select "Format Document". So the extension works as it is supposed to.

My question: can I run the bundled black executable of this extension from the command line (CLI)?

Ps.: I would like to format whole folders, recursively. Of course, I can install a separate black executable from a python (anaconda) package, and use that from the CLI as any other UNIX command, but I would like to at least try to use the bundled version from the extension, if that's possible.

enter image description here


Solution

  • You can reference the extension folder in a command line, but that path will change with updates.

    On Windows cmd:

    SET PYTHONPATH=C:\Users\User\.vscode\extensions\ms-python.black-formatter-2023.6.0\bundled\libs
    python -m black my_file_or_folder.py
    

    Linux/MacOS:

    export PYTHONPATH=~/.vscode/extensions/ms-python.black-formatter-2023.6.0/bundled/libs
    python -m black my_file_or_folder.py
    

    Or you can use the one-liner on a unix-based OS:

    PYTHONPATH=~/.vscode/extensions/ms-python.black-formatter-2023.6.0/bundled/libs python -m black my_file_or_folder.py
    

    On WSL, the path is different, but the method is the same as Linux:

    export PYTHONPATH=/mnt/c/Users/User/.vscode/extensions/ms-python.black-formatter-2023.6.0/bundled/libs
    python -m black my_file_or_folder.py
    

    You can glob the version in smarter shells to avoid issues when updating, but cmd is pretty simple in this regard and doesn't help much.