假设我想将 black 作为 API 使用,并执行以下操作:
import black
black.format("some python code")
通过调用Popen
二进制文件使用black
格式化代码是一种替代方案,但这不是我所要求的。
假设我想将 black 作为 API 使用,并执行以下操作:
import black
black.format("some python code")
通过调用Popen
二进制文件使用black
格式化代码是一种替代方案,但这不是我所要求的。
format_str
:from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)
black.format_file_contents
。import black
mode = black.FileMode()
fast = False
out = black.format_file_contents("some python code", fast, mode)
虽然官方不支持, 但你可以像在black.format_stdin_to_stdout
函数中看到的那样调用black.format_file_contents
。
简化后,只有以下几行:
import black # version: 22.10.0
BLACK_MODE = black.Mode(target_versions={black.TargetVersion.PY311}, line_length=120)
code = ... # some python code to reformat
try:
code = black.format_file_contents(code, fast=False, mode=BLACK_MODE)
except black.NothingChanged:
pass
finally:
# Make sure there's a newline after the content
if code and code[-1] != "\n":
code += "\n"
print(code) # print result