使用YAPF对python代码进行格式化

    技术2025-08-29  8

    今天拿到一段python代码,格式排版简直乱的没法看,于是找到了python代码格式化的一个开源工具,在这里分享给大家 YAPF是一个开源的python代码格式化工具,项目地址

    https://github.com/google/yapf

    使用方法

    1、安装

    命令行界面输入下面命令

    pip install yapf

    2、使用

    usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN] [--style STYLE] [--style-help] [--no-local-style] [-p] [-vv] [files [files ...]] Formatter for Python code. positional arguments: files optional arguments: -h, --help show this help message and exit -v, --version show version number and exit -d, --diff print the diff for the fixed source -i, --in-place make changes to files in place -r, --recursive run recursively over directories -l START-END, --lines START-END range of lines to reformat, one-based -e PATTERN, --exclude PATTERN patterns for files to exclude from formatting --style STYLE specify formatting style: either a style name (for example "pep8" or "google"), or the name of a file with style settings. The default is pep8 unless a .style.yapf or setup.cfg file located in the same directory as the source or one of its parent directories (for stdin, the current directory is used). --style-help show style settings and exit; this output can be saved to .style.yapf to make your settings permanent --no-local-style don't search for local style definition -p, --parallel Run yapf in parallel when formatting multiple files. Requires concurrent.futures in Python 2.X -vv, --verbose Print out file names while processing

    上面是详细的使用方式

    下面给出几个常用的例子来看看

    如果格式化一个文件

    在命令行输入

    yapf -i xxxx.py

    注意这条命令会替换文件里面的内容哦,如果不想替换文件内容吧 -i 去掉即可

    如果希望遍历一个文件夹下面的所有python文件,并替换里面的内容:

    yapf -i -r .\python_file_folder\

    完成处理后阅读起来就容易一些了。

    文档中给了一个格式化代码的一个案例,可以看看

    An example of the type of formatting that YAPF can do, it will take this ugly code: x = { 'a':37,'b':42, 'c':927} y = 'hello ''world' z = 'hello '+'world' a = 'hello {}'.format('world') class foo ( object ): def f (self ): return 37*-+2 def g(self, x,y=42): return y def f ( a ) : return 37+-+a[42-x : y**3] and reformat it into: x = {'a': 37, 'b': 42, 'c': 927} y = 'hello ' 'world' z = 'hello ' + 'world' a = 'hello {}'.format('world') class foo(object): def f(self): return 37 * -+2 def g(self, x, y=42): return y def f(a): return 37 + -+a[42 - x:y**3]

     

    Processed: 0.022, SQL: 9