python 代码格式化工具:pep8ify
资料: https://github.com/spulec/pep8ify
安装
$ pip install pep8ify
用法
Usage: 2to3 [options] file|dir ... Options: -h, --help show this help message and exit -d, --doctests_only Fix up doctests only -f FIX, --fix=FIX Each FIX specifies a transformation; default: all -j PROCESSES, --processes=PROCESSES Run 2to3 concurrently -x NOFIX, --nofix=NOFIX Prevent a transformation from being run -l, --list-fixes List available transformations -p, --print-function Modify the grammar so that print() is a function -v, --verbose More verbose logging --no-diffs Don't show diffs of the refactoring -w, --write Write back modified files -n, --nobackups Don't write backups for modified files -o OUTPUT_DIR, --output-dir=OUTPUT_DIR Put output files in this directory instead of overwriting the input files. Requires -n. -W, --write-unchanged-files Also write files even if no changes were required (useful with --output-dir); implies -w. --add-suffix=ADD_SUFFIX Append this string to all output filenames. Requires -n if non-empty. ex: --add-suffix='3' will generate .py3 files.
修复的问题
Available transformations for the -f/--fix option: blank_lines compound_statements extraneous_whitespace imports_on_separate_lines indentation maximum_line_length missing_newline missing_whitespace tabs trailing_blank_lines trailing_whitespace whitespace_around_operator whitespace_before_inline_comment whitespace_before_parameters
具体使用方法
假设当前路径下有一个文件夹a,a目录下有一个源文件a.py,a.py内容如下:
import math, sys;
def example1():
####This is a long comment. This should be wrapped to fit within 72 characters.
some_tuple=( 1,2, 3,'a' );
some_variable={'long':'Long code lines should be wrapped within 79 characters.',
'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
20,300,40000,500000000,60000000000000000]}}
return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3( object ):
def __init__ ( self, bar ):
#Comments should have a space after the hash.
if bar : bar+=1; bar=bar* bar ; return bar
else:
some_string = """
Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
return (sys.path, some_string)
1. 查看需要更改的diff信息。
备注:该操作执行之后,不会有任何真正意义上的变化,只是在终端打印出一些源文件和更改之后的文件的diff信息,源文件并没有变化。
D:\Python3\Scripts\pep8ify.exe a
2. 格式化文件/路径
备注: 该操作会在终端打印出源文件和更改之后的文件的diff信息,同时更新源文件,并且在路径下生成一个“文件名.bak”文件。
执行如下命令:
D:\Python3\Scripts\pep8ify.exe -w a
可以看到a.py内容更新,a路径下有一个a.py.bak文件,a.py.bak的内容为源文件内容。
3. 不生成bak文件
-n 选项不会生成备份。
如果没有使用版本控制系统,不要使用这个选项。
D:\Python3\Scripts\pep8ify.exe -w -n a
4. 应用指定的修复
-f 可以指定应用的特定修复
默认是all,但是all不包括“maximum_line_length”。
如果想应用 all + maximum_line_length:
$ pep8ify -f all -f maximum_line_length example.py
作者:微微微笑
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.