是否可以将 Black 作为 API 调用?

lai*_*e9m 11 python python-black

假设我想使用黑色作为 API,并执行以下操作:

import black

black.format("some python code")
Run Code Online (Sandbox Code Playgroud)

通过调用black二进制文件来格式化代码Popen是另一种选择,但这不是我要问的。

Hal*_*and 11

您可以尝试使用format_str

from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)
Run Code Online (Sandbox Code Playgroud)


Olu*_*ule 6

使用black.format_file_contents

例如

import black

mode = black.FileMode()
fast = False
out = black.format_file_contents("some python code", fast, mode)
Run Code Online (Sandbox Code Playgroud)

https://github.com/psf/black/blob/19.3b0/black.py#L642