Hướng dẫn black, python vscode

Adam Lombard

Posted on Apr 30, 2020 • Updated on May 1, 2020

Black is "the uncompromising Python code formatter." It can be configured to automatically format your code whenever you save a file in VSCode.

Install Black in your virtual environment:

$ pip install black

Enter fullscreen mode Exit fullscreen mode

Install Microsoft's Python extension in VSCode:

Open your VSCode settings, by going 'Code -> Preferences -> Settings'.

Search for "python formatting provider" and select "black" from the dropdown menu:

In the settings, search for "format on save" and enable the "Editor: Format on Save" option:

Black will now format your code whenever you save a *.py file.

Before saving:

After saving:

More: How to set Black line lengths in VSCode

Images from VSCode using Hyper Term Theme.

To setup python black as a formatter for VS-Code workspace you need to install it on your virtual env or in your local python with the command:

$ pip install black

Now install the python extension for VS-Code, open your VS-Code and type “Ctrl + p”, paste the line below and hit enter:

ext install ms-python.python

We are almost there. Go to settings in your VS-Code typing “Ctrl + ,” or clicking at the gear on the bottom left and selecting “Settings [Ctrl+,]” option.

Type “format on save” at the search bar on top of the Settings tab and check the box.

Search for “python formatting provider” and select “black”.

Now open/create a python file, write some code and save[Ctrl+s] it to see the magic happen!

Example

Before saving the file.

After saving the code automatically get formatted

Good to know: if Black is not working maybe your python code has some syntax error, recheck the code and test again.

Contact me: linkedin.com/in/marco-belo/

Chủ Đề