今天拿到一段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]