1.代码规范
在Python中,import 应该一次只导入一个模块。
import os
import sys
--从一个模块导入多个API;
from subprocess import Popen,PIPE
import语句应该处于源码文件的顶部,位于模块注释和文档字符串之后,
全局变量和常量之前。
导入不同的库时,应该按以下顺序分组,各个分组之间以空行分隔:
1)导入标准库模块
2)导入相关第三方库模块
3)导入当前应用程序、库模块。
import time
import json
import yaml
import psutil
from mongo_agent.action.common import kill_mongod,start_mongo_node
--python中支持相对导入和绝对导入,推荐使用绝对导入。
无论合适避免使用通配符导入。
2.pep8 自带的编码规范器
pep8重命名为 pycodestyle
pip install pycodestyle
pycodestyle --first xxx.py
[root@mysql1 shell]# pip3 install pep8
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting pep8
Downloading https://files.pythonhosted.org/packages/42/3f/669429ce58de2c22d8d2c542752e137ec4b9885fff398d3eceb1a7f5acb4/pep8-1.7.1-py2.py3-none-any.whl (41kB)
100% |████████████████████████████████| 51kB 282kB/s
Installing collected packages: pep8
Successfully installed pep8-1.7.1
[root@mysql1 shell]# pep8 jisuan2.py
/usr/local/lib/python3.6/site-packages/pep8.py:2124: UserWarning:
pep8 has been renamed to pycodestyle (GitHub issue #466)
Use of the pep8 tool will be removed in a future release.
Please install and use `pycodestyle` instead.
$ pip install pycodestyle
$ pycodestyle ...
'\n\n'
jisuan2.py:1:1: E265 block comment should start with '# '
jisuan2.py:1:17: W291 trailing whitespace
jisuan2.py:2:38: W291 trailing whitespace
jisuan2.py:3:12: W291 trailing whitespace
jisuan2.py:4:1: E302 expected 2 blank lines, found 0
jisuan2.py:5:6: E225 missing whitespace around operator
jisuan2.py:5:8: W291 trailing whitespace
jisuan2.py:8:15: W291 trailing whitespace
[root@mysql1 shell]# pip3 install pycodestyle
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting pycodestyle
Downloading https://files.pythonhosted.org/packages/a2/54/001fdc0d69e8d0bb86c3423a6fa6dfada8cc26317c2635ab543e9ac411bd/pycodestyle-2.10.0-py2.py3-none-any.whl (41kB)
100% |████████████████████████████████| 51kB 135kB/s
Installing collected packages: pycodestyle
Successfully installed pycodestyle-2.10.0
3.pycodestyle 检查编码规范
pycodestyle --first jisuan2.py
[root@mysql1 shell]# pycodestyle --first jisuan2.py
jisuan2.py:1:1: E265 block comment should start with '# '
jisuan2.py:1:17: W291 trailing whitespace
jisuan2.py:4:1: E302 expected 2 blank lines, found 0
jisuan2.py:5:6: E225 missing whitespace around operator
jisuan2.py:10:1: E305 expected 2 blank lines after class or function definition, found 0
(2)使用 pycodestyle 的 --show-source
显示不符合规范的源码:
--原代码显示:
[root@mysql1 shell]# cat jisuan2.py
#/usr/bin/python
from __future__ import print_function
import ipdb
import sys,os
def sum_nums(n):
s=0
for i in range(n):
s += i
print(s)
if __name__ == '__main__':
sum_nums(5)
--检查代码规范性。
[root@mysql1 shell]# pycodestyle --show-source --show-pep8 jisuan2.py
jisuan2.py:1:1: E265 block comment should start with '# '
#/usr/bin/python
^
Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement.
Inline comments should be separated by at least two spaces from the
statement. They should start with a # and a single space.
Each line of a block comment starts with a # and one or multiple
spaces as there can be indented text inside the comment.
Okay: x = x + 1 # Increment x
Okay: x = x + 1 # Increment x
Okay: # Block comments:
Okay: # - Block comment list
Okay: # - Block comment list
E261: x = x + 1 # Increment x
E262: x = x + 1 #Increment x
E262: x = x + 1 # Increment x
E262: x = x + 1 # Increment x
E265: #Block comment
E266: ### Block comment
jisuan2.py:1:17: W291 trailing whitespace
#/usr/bin/python
^
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
jisuan2.py:2:38: W291 trailing whitespace
from __future__ import print_function
^
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
jisuan2.py:3:12: W291 trailing whitespace
import ipdb
^
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
jisuan2.py:4:11: E231 missing whitespace after ','
import sys,os
^
Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[3,] = 1
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}]
jisuan2.py:4:11: E401 multiple imports on one line
import sys,os
^
Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import foo.bar.yourclass
jisuan2.py:5:1: E302 expected 2 blank lines, found 0
def sum_nums(n):
^
Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical
sections.
Okay: def a():\n pass\n\n\ndef b():\n pass
Okay: def a():\n pass\n\n\nasync def b():\n pass
Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
Okay: default = 1\nfoo = 1
Okay: classify = 1\nfoo = 1
E301: class Foo:\n b = 0\n def bar():\n pass
E302: def a():\n pass\n\ndef b(n):\n pass
E302: def a():\n pass\n\nasync def b(n):\n pass
E303: def a():\n pass\n\n\n\ndef b(n):\n pass
E303: def a():\n\n\n\n pass
E304: @decorator\n\ndef a():\n pass
E305: def a():\n pass\na()
E306: def a():\n def b():\n pass\n def c():\n pass
jisuan2.py:6:6: E225 missing whitespace around operator
s=0
^
Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
Booleans (and, or, not).
- If operators with different priorities are used, consider adding
whitespace around the operators with the lowest priorities.
Okay: i = i + 1
Okay: submitted += 1
Okay: x = x * 2 - 1
Okay: hypot2 = x * x + y * y
Okay: c = (a + b) * (a - b)
Okay: foo(bar, key='word', *args, **kwargs)
Okay: alpha[:-i]
E225: i=i+1
E225: submitted +=1
E225: x = x /2 - 1
E225: z = x **y
E225: z = 1and 1
E226: c = (a+b) * (a-b)
E226: hypot2 = x*x + y*y
E227: c = a|b
E228: msg = fmt%(errno, errmsg)
jisuan2.py:6:8: W291 trailing whitespace
s=0
^
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
jisuan2.py:8:15: W291 trailing whitespace
s += i
^
Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
jisuan2.py:10:1: E305 expected 2 blank lines after class or function definition, found 0
if __name__ == '__main__':
^
Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical
sections.
Okay: def a():\n pass\n\n\ndef b():\n pass
Okay: def a():\n pass\n\n\nasync def b():\n pass
Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
Okay: default = 1\nfoo = 1
Okay: classify = 1\nfoo = 1
E301: class Foo:\n b = 0\n def bar():\n pass
E302: def a():\n pass\n\ndef b(n):\n pass
E302: def a():\n pass\n\nasync def b(n):\n pass
E303: def a():\n pass\n\n\n\ndef b(n):\n pass
E303: def a():\n\n\n\n pass
E304: @decorator\n\ndef a():\n pass
E305: def a():\n pass\na()
E306: def a():\n def b():\n pass\n def c():\n pass
--按要求修改后,没有任何输出。
[root@mysql1 shell]# pycodestyle --show-source --show-pep8 jisuan2.py
--修改后的源码为:
[root@mysql1 shell]# cat jisuan2.py
# /usr/bin/python
from __future__ import print_function
import ipdb
import sys
import os
def sum_nums(n):
s = 0
for i in range(n):
s += i
print(s)
if __name__ == '__main__':
sum_nums(5)
--要求:函数定义前后必须有两个空行。
--每次只能导入一个模块。
--符号两边必须有空格。
--第一行#后面必须有空格。
4.使用 autopep8 将代码格式化
(1)安装 autopep8
[root@mysql1 shell]# pip3 install autopep8
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting autopep8
Downloading https://files.pythonhosted.org/packages/d8/f2/e63c9f9c485cd90df8e4e7ae90fa3be2469c9641888558c7b45fa98a76f8/autopep8-2.0.4-py2.py3-none-any.whl (45kB)
100% |████████████████████████████████| 51kB 62kB/s
Requirement already satisfied: tomli; python_version < "3.11" in /usr/local/lib/python3.6/site-packages (from autopep8)
Requirement already satisfied: pycodestyle>=2.10.0 in /usr/local/lib/python3.6/site-packages (from autopep8)
Installing collected packages: autopep8
Successfully installed autopep8-2.0.4
(1)将格式话后的文件输入到源码文件中。
--查看原文件
[root@mysql1 shell]# cat jisuan.py
#/usr/bin/python
from __future__ import print_function
import pdb
def sum_nums(n):
s=0
for i in range(n):
pdb.set_trace()
s += i
print(s)
if __name__ == '__main__':
sum_nums(5)
--对文件进行格式化。
--使用--in-place 直接将格式化后的源码输入到原文件中。
autopep8 --in-place jisuan.py
--查看格式化后的内容。
[root@mysql1 shell]# cat jisuan.py
# /usr/bin/python
from __future__ import print_function
import pdb
def sum_nums(n):
s = 0
for i in range(n):
pdb.set_trace()
s += i
print(s)
if __name__ == '__main__':
sum_nums(5)
---现在开起来美观很多。
5.工具。
pep8 :检查代码规范性
pycodestyle :检查代码规范性。
autopep8: 重新格式化不规范的代码。