How To Get Black Working in PyCharm in 2021

tl;dr install this plugin and have PyCharm start blackd via a shell script on launch. Reassign the “reformat code” keyboard shortcut to call the plugin.

Immediate Performance Issues

Whilst making my yearly pilgrimage from vim to PyCharm (I usually go back to vim after a bit), I found it less than straightforward to apply the black formatter instead of using PyCharm’s built-in “reformat code” settings.

For those who don’t know what black is, it’s a way to never think about formatting in Python ever again.

After following the Black docs about setting black up in PyCharm, I found the file watcher for it to be incredibly slow, interrupting the flow of my work while I waited for it to format a single file.

So I instead turned off the file watcher and remapped the “reformat code” keyboard shortcut to instead call black on the currently displayed file. This is great, but it also opens a terminal and displays the executed command as well as

Process finished with <span>exit </span>code 0
Process finished with <span>exit </span>code 0
Process finished with exit code 0

Enter fullscreen mode Exit fullscreen mode

every single time the code is reformatted. A little research yielded a --quiet parameter to black, but for whatever reason this didn’t silence the output, at least not when executed via PyCharm.

Plugin?

Jetbrains IDEs have a pretty decent plugin marketplace and community. Maybe not on par with VSCode by now, but then again there’s a lot more (nice) batteries included in Jetbrains IDEs than VSCode.

A quick search yielded BlackConnect, which glues PyCharm to a blackd daemon. It requires installing and running blackd (pip install black[d]), but it’s nice and fast and doesn’t bring attention to itself. I remapped the “reformat code” keyboard shortcut to invoke BlackConnect.

A Little Bit of Configuration

Making it work on startup requires an extra step, though: I made an on_pycharm_startup.sh file containing a single command blackd, did chmod +x on it, then added it to Tools>Startup Tasks. Boom! Black works quickly and silently when manually called via keyboard shortcut.

A note: BlackConnect has a “reformat on save” option, but it’s just as slow as and less reliable than running black from a file watcher. Maybe this will change at some point.

原文链接:How To Get Black Working in PyCharm in 2021

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
Aim for the moon. If you miss, you may hit a star.
把月亮作为你的目标。如果你没打中,也许你还能打中星星
评论 抢沙发

请登录后发表评论

    暂无评论内容