文章目录
安装
建议全局安装,这样只要安装一次就行了
pip install black
查看安装位置
- macOS/unix
which black
- windows
where black
在pycharm中集成black
Open External tools in PyCharm/IntelliJ IDEA
- macOS
PyCharm -> Preferences -> Tools -> External Tools - unix/windows
File -> Settings -> Tools -> External Tools
Click the + icon to add a new external tool with the following values
Name: black
Description: Black is the uncompromising Python code formatter.
Program: <black_installation_location>
Arguments: $FilePath$
Working directory: $ProjectFileDir$
Format the currently opened file by selecting Tools -> External Tools -> black.
Alternatively, you can set a keyboard shortcut by navigating to Preferences or Settings -> Keymap -> External Tools -> External Tools - Black.
Optionally, run Black on every file save:
1. Make sure you have the File Watchers plugin installed.
Settings -> Pulgins -> 搜索File Watchers
2. Go to Preferences or Settings -> Tools -> File Watchers
and click +
to add a new watcher:
- Name: Black
- File type: Python
- Scope: Project Files
- Program: <black_installation_location>
- Arguments:
$FilePath$
- Output paths to refresh:
$FilePath$
- Working directory:
$ProjectFileDir$
3. In Advanced Options
- Uncheck “Auto-save edited files to trigger the watcher”
- Uncheck “Trigger the watcher on external changes”
使用ctrl+s键保存的同时格式化
- In the top menu you click: Edit > Macros > Start Macro Recordings (you’ll see a window lower right corner of your screen confirming that macros are being recorded)
- In the top menu you click: Code > Optimize Imports (you’ll see the option being selected in the lower right corner)
- In the top menu you click: Tools -> External Tools -> black (you’ll see the option being selected in the lower right corner)
- In the top menu you click: File > Save All
- In the top menu you click: Edit > Macros > Stop Macro Recording
- You name the macro: “Format Code, Organize Imports, Save”
- In the top menu you clock: File > Settings. In the settings windows you click Keymap
- In the search box on the right you search “save”. You’ll find Save All (Ctrl+S). Right click on it and select “Remove Ctrl+S”
- Remove your search text from the box, press on the Collapse All button (Second button from the top left)
- Go to macros, press on the arrow to expand your macros, find your saved macro and right click on it. Select Add Keyboard Shortcut, and press Ctrl+S and okay.
- Restart your IDE and try it.
参考
editor_integration
Intellij reformat on file save
在PYCHARM中设置ISORT和BLACK格式化代码