Adding black formatter to PyCharm
This guide will show you how to set up black code formatter for PyCharm.
Nikola Milev
|
26 steps
|
3 minutes
Adding an external tool
1
Go to your Terminal and type [[pip install black]]
2
Click on "PyCharm" in the menu bar and then "Settings"
3
Click this unknown
4
Click "Tools" and then "External Tools"
5
Click +
6
Click on the name field and name your new tool
7
To add the path for the tool, click + next to the Program Field, then select "PyInterpreterDirectory" and add /black at the end
8
To add the arguments for the tool, click + next to the Arguments, then select "FilePath"
9
To add the working directory for the tool, click + next to the Working Directory, then select "ProjectFileDir"
10
Click "OK"
11
Click Apply
12
You've successfully added a tool for formatting files with black
Now you've added a tool, but it doesn't auto-apply on save. For that to happen, follow the rest of the guide.
Running black automatically on file save
13
While in the Settings window, click "File Watchers"
14
Click +
15
Select "<custom>"
16
Name your File Watcher
17
From File type dropdown, select "Python"
18
To add the path for the File Watcher, click + next to the Program field, then select "PyInterpreterDirectory" and add /black at the end
19
To add the arguments for the File Watcher, click + next to the Arguments, then select "FilePath"
20
To add the output for the File Watcher, click + next to the Arguments, then select "FilePath". This will make sure that black output is the same file that was processed.
21
Expand the "Working Directory and Environment Variables" section.
22
To add the working directory for the File Watcher, click + next to the Working Directory, then select "ProjectFileDir"
23
Click OK
24
Click Apply or Ok
25
Type in some incorrectly formatted code and press [[CMD]] + [[S]] to save
26
Voila! Your code was automatically formatted!
You've successfully set up black auto-save formatting with PyCharm!