背景

autopep8 会根据 PEP 8 样式文档来格式化 python 代码。它使用 pep8 来决定代码的哪部分需要被格式化。 autopep8 可以修复 pep8汇报的大部分格式问题。

PEP8 是 Python Enhancement Proposal 的缩写,翻译过来就是 python 增强建议书, 是python的一个官方样式指导。它规定了一些比较好的编码方式,比如用4个空格代替缩进等等。

安装

$ pip install --upgrade autopep8

用法

usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename]

[--ignore-local-config] [-r] [-j n] [-p n] [-a]

[--experimental] [--exclude globs] [--list-fixes]

[--ignore errors] [--select errors] [--max-line-length n]

[--line-range line line]

[files [files ...]]

Automatically formats Python code to conform to the PEP8style guide.

positional arguments:

files files to format or'-' for standard inoptional arguments:-h, --help show this help message and exit--version show program's version number and exit

-v, --verbose print verbose messages; multiple -v result in moreverbose messages-d, --diff print the diff forthe fixed source-i, --in-place make changes to files inplace--global-config filename

path to a global pep8 configfile; if this filedoes

not existthenthis is ignored (default:~/.config/pep8)--ignore-local-config

don't look for and apply local config files; if not

passed, defaults are updated with any config files inthe project's root directory

-r, --recursive run recursively over directories; must be used with--in-place or --diff

-j n, --jobs n number of parallel jobs; match CPU count ifvalue isless than 1

-p n, --pep8-passes n

maximum number of additional pep8 passes (default:

infinite)-a, --aggressive enable non-whitespace changes; multiple -a result in

moreaggressive changes--experimental enable experimental fixes--exclude globs exclude file/directory names that match these comma-separated globs--list-fixes list codes for fixes; used by --ignore and --select

--ignore errors do not fix these errors/warnings (default: E24)--select errors fix only these errors/warnings (e.g. E4,W)--max-line-length n set maximum allowed line length (default: 79)--line-range line line, --range line line

only fix errors found within this inclusive range of

line numbers (e.g.1 99); line numbers are indexed at1

特性

autopep8会修复pep8汇报的下列问题:

E101 -Reindent all lines.

E121-Fix indentation to be a multiple of four.

E122- Add absent indentation forhanging indentation.

E123-Align closing bracket to match opening bracket.

E124-Align closing bracket to match visual indentation.

E125-Indent to distinguish line from next logical line.

E126- Fix over-indented hanging indentation.

E127-Fix visual indentation.

E128-Fix visual indentation.

E20-Remove extraneous whitespace.

E211-Remove extraneous whitespace.

E22-Fix extraneous whitespace around keywords.

E224-Remove extraneous whitespace around operator.

E226-Fix missing whitespace around arithmetic operator.

E227- Fix missing whitespace around bitwise/shiftoperator.

E228-Fix missing whitespace around modulo operator.

E231-Add missing whitespace.

E241-Fix extraneous whitespace around keywords.

E242-Remove extraneous whitespace around operator.

E251- Remove whitespace around parameter '='sign.

E26- Fix spacing after comment hash forinline comments.

E265- Fix spacing after comment hash forblock comments.

E27-Fix extraneous whitespace around keywords.

E301-Add missing blank line.

E302- Add missing 2blank lines.

E303-Remove extra blank lines.

E304- Remove blank line following functiondecorator.

E309-Add missing blank line (after class declaration).

E401-Put imports on separate lines.

E501- Try to make lines fit within --max-line-length characters.

E502-Remove extraneous escape of newline.

E701- Put colon-separated compound statement on separate lines.

E70- Put semicolon-separated compound statement on separate lines.

E711-Fix comparison with None.

E712-Fix comparison with boolean.

E721- Use "isinstance()"instead of comparing types directly.

W291-Remove trailing whitespace.

W293-Remove trailing whitespace on blank line.

W391-Remove trailing blank lines.

W601- Use "in" rather than "has_key()".

W602-Fix deprecated form of raising exception.

W603- Use "!=" instead of "<>"W604- Use "repr()"instead of backticks.

W690- Fix various deprecated code (via lib2to3).

备注:

autopep8 也会忽略一些 pep8 的问题。

1. E112/E113

2. E265

autopep8 也会修复一个非pep8汇报的问题:

1. 纠正弃用的以及非惯用的python代码(通过 lib2to3)。这会让python 2.6 以及 python 2.7 的代码更加与 python3 兼容。(如果 W690 是enable的,这一项修复会被触发)

2. 标准化具有多种行结束符的文件。

3. 在类申明和它的第一个方法申明中间加一个空行。(由 E309 enable)

4. 在类文档和它的第一个方法申明中间加一个空行。(由 E301 enable)

5. 移除方法申明和它的文档之间的空行。 (由 E303 enable )

具体用法

1. 使用 autopep8 更改一个文件。

假设文件名是 a.py,文件内容如下:

importmath, sys;defexample1():####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(''));classExample3( object ):def __init__( self, bar ):#Comments should have a space after the hash.

if bar : bar+=1; bar=bar* bar ; returnbarelse:

some_string= """Indentation in multiline strings should not be touched.

Only actual code should be reindented."""

return (sys.path, some_string)

转到 Python3\Scripts 路径,可以看到 autopep8.exe 文件。

在a.py路径下,打开cmd,执行下列命令:

D:\Python3\Scripts\autopep8 --in-place --aggressive --aggressive a.py

备注:

--in-place: 以更改后的文件直接替代源文件。

--aggressive --aggressive : 以 aggressive 等级2 来更改源文件。

更改之后,a.py内容如下:

importmathimportsysdefexample1():#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 ('' in {'f': 2}) in {'has_key() is deprecated': True}classExample3(object):def __init__(self, bar):#Comments should have a space after the hash.

ifbar:

bar+= 1bar= bar *barreturnbarelse:

some_string= """Indentation in multiline strings should not be touched.

Only actual code should be reindented."""

return (sys.path, some_string)

2. aggressive 等级

默认情况下,autopep8只修复空格问题。所以,默认情况下,autopep8不会修复 E711 和 E712 ,也不会修复弃用的代码 W6。

为了应用这些更加 aggressive 的修复,使用 --aggressive 选项:

autopep8 --aggressive a.py

使用多个 --aggressive 可以增加 aggressiveness 等级。

比如, E712 需要 aggressiveness 等级2.

autopep8 --aggressive  --aggressive a.py

3. 选择修复部分规范

只修复一部分规范,使用 --select 选项。

比如,修复多种缩进问题:

$ autopep8 --select=E1,W1 a.py

仅仅修复弃用代码问题:

$ autopep8 --aggressive --select=W6 a.py

4. 显示详细的过程信息

$ autopep8 -v a.py

5. 以模块的方式使用

>>> importautopep8>>> autopep8.fix_code('x= 123\n')'x = 123\n'

6. 以模块的方式使用,且带有条件

>>> importautopep8>>> autopep8.fix_code('x.has_key(y)\n', options={'aggressive': 1})'y in x\n'

>>> autopep8.fix_code('print( 123 )\n', options={'ignore': ['E']})'print( 123 )\n'

python代码格式化工具下载_python 代码格式化工具:autopep8相关推荐

  1. python 喜马拉雅 音乐下载 演示代码

    python 喜马拉雅 音乐下载 演示代码 1.主程序文件 import os import jsonimport requests from contextlib import closing fr ...

  2. python代码质量检查工具_python代码检查工具pylint 让你的python更规范

    复制代码 代码如下: #coding:utf-8 ''' a test function module ''' import urllib import time def fetch(url): '' ...

  3. python代码重构技巧_Python代码重构

    代码重构是一件很是辛苦却很是有意义的事情,代码重构的缘由在于:django 一.代码过于冗余.沉余架构 二.代码过于耦合函数 三.代码过于复杂学习 四.接口调用超出三层优化 此次重构主要在于架构问题, ...

  4. python 爬视频下载_Python爬虫进阶之爬取某视频并下载的实现

    这篇文章我们来讲一下在网站建设中,Python爬虫进阶之爬取某视频并下载的实现.本文对大家进行网站开发设计工作或者学习都有一定帮助,下面让我们进入正文. 这几天在家闲得无聊,意外的挖掘到了一个资源网站 ...

  5. python网站框架下载_Python搭建网站框架

    1. 机器上安装python 在python官网下载python的2.7版本,然后一路next就可以安装了: 安装结束后,开启菜单会有python客户端,但是一般使用cmd命令行模式进行运行: 添加p ...

  6. python交互式解释器下载_Python解释器

    当我们编写Python代码时,我们得到的是一个包含Python代码的以.py为扩展名的文本文件.要运行代码,就需要Python解释器去执行.py文件. 由于整个Python语言从规范到解释器都是开源的 ...

  7. python自动批量下载_Python批量下载鼠标样式,自动化一条龙处理详解

    前情提要 最近发现一款特别好看的壁纸软件,其中提供了鼠标样式,感觉很好看!很精致!心想肯定是请求下载然后启用鼠标样式, 那么发送请求,那不就可以用Python爬虫了吗? 其中鼠标样式下图: 爬虫环境 ...

  8. python爬虫程序下载_Python爬虫之多线程下载程序类电子书

    近段时间,笔者发现一个神奇的网站:http://www.allitebooks.com/ ,该网站提供了大量免费的编程方面的电子书,是技术爱好者们的福音.其页面如下: ![](https://imag ...

  9. python xlrd模块下载_python xlrd模块介绍

    转载自:http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html 一.安装xlrd模块 到python官网下载 二.使用介绍 1.导入 ...

  10. 用python实现bt下载_python实现bt种子 torrent转magnet

    Python实现bt转磁链 参考前人资料主要两种方式 1,利用python的bencode模块 2,安装libtorrent模块 尝试过两种方法特记录 环境:Windows系统 python 3 be ...

最新文章

  1. 学生成绩管理系统数据库设计
  2. 读书笔记:怪侠一枝梅 看后感
  3. 【干货】JMeter BeanShell 应用
  4. 使用python重命名某个文件下的所有的文件
  5. scanf不可以读空格不可以读string
  6. sql网站路径php,如何在源码中找出sql语句的位置呢
  7. QT的QStringView类的使用
  8. OCR系列——文本检测任务
  9. Thrift CentOS安装和使用
  10. 华硕主板无盘启动bios设置_legacy和UEFI启动是什么?电脑BIOS设置开启进入UEFI启动方法...
  11. Tuxedo 8.110gR3 开发环境的安装与配置
  12. Daily Scrum 10.28
  13. c语言延时时间计算器,rc延时电路延时时间计算公式
  14. Visual Studio 2015(C#)编写实现TCP调试助手(服务端+客户端一体)-新手
  15. 黑苹果麦克风无法使用的问题(仅针对自己的配置)
  16. mt6573集成MCP nandflash的详细方法
  17. 硬件工程师成长之路(10)——项目举例
  18. 【C语言程序设计】C语言三色旗问题!
  19. MySQL通过分组计算百分比
  20. Unity基于YooAssets资源管理1

热门文章

  1. Cisco 冗余备份(IRDP)
  2. SAP 采购发票预制 MIR7 <转载>
  3. hexo+yilia添加背景图片
  4. 想知道“照片识别文字”的技巧吗?快看这几个方法
  5. mysql数据库安装过程蜿蜒曲折
  6. 【IoT】产品设计之市场概念:市场定位、产品定位、市场需求、产品需求
  7. 创业板首批企业或节前招股 新公布6家上会公司
  8. python图形化界面设计gui_Python图形界面GUI程序设计
  9. DVWA-low通关
  10. PTGUI 全景图批量拼接