在pycharm中使用black

安装

建议全局安装,这样只要安装一次就行了

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键保存的同时格式化

  1. 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)
  2. In the top menu you click: Code > Optimize Imports (you’ll see the option being selected in the lower right corner)
  3. In the top menu you click: Tools -> External Tools -> black (you’ll see the option being selected in the lower right corner)
  4. In the top menu you click: File > Save All
  5. In the top menu you click: Edit > Macros > Stop Macro Recording
  6. You name the macro: “Format Code, Organize Imports, Save”
  7. In the top menu you clock: File > Settings. In the settings windows you click Keymap
  8. 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”
  9. Remove your search text from the box, press on the Collapse All button (Second button from the top left)
  10. 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.
  11. Restart your IDE and try it.

参考

editor_integration
Intellij reformat on file save
在PYCHARM中设置ISORT和BLACK格式化代码

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值