三步搞定python代码Linter

写一手漂亮的代码是一件重要,但却不容易的事。编程除了用代码实现需求功能之外,代码的格式风格需要符合公司的开发规范,这不仅可以让同事能轻松读懂你写的代码,而且对自己也是大有裨益,想象一下一个月之后再回来改自己写的代码。如何保证来代码风格的一致性和正确性?有一个强大的工具Linter可以辅助我们完成这项工作。

什么是Lint ?


在计算机科学中,lint是一种工具程序的名称,它用来标记源代码中,某些可疑的、不具结构性(可能造成bug)的段落。它是一种静态程序分析工具,最早适用于C语言,在UNIX平台上开发出来。后来它成为通用术语,可用于描述在任何一种计算机程序语言中,用来标记源代码中有疑义段落的工具。

本文重点介绍如何在Sublime这个编辑器中引入linter 来提高python项目的代码质量.

环境


本文介绍的工具是在mac os环境下安装。

  1. mac os 10.13
  2. Sublime Text 3 build 3176
  3. Python 3.6.2

步骤一: 安装Flake8


众所周知python领域的代码规范为PEP8,目前有几大Linter工具Pylint,Flake8。考虑到配置使用的方便性笔者选用了Flake8

我们需要在系统级别安装flake8。

$ pip3 install flake8

检查是否安装正确,执行which命令。

$ which flake8
/Users/hqman/.pyenv/shims/flake8

然后我写一段超简单的python代码来试试linter。

#!/usr/bin/env python

def talk(text=None):
    return '说话:' + text


name = '某人'
age = 30
my_string = f"他叫 {name} , 今年 {age} 岁了."

print(my_string)  #random comment

name != unknown  # this is wrong
print(talk('你好!'))
flake8 test.py
test.py:3:1: E302 expected 2 blank lines, found 1
test.py:11:19: E262 inline comment should start with '# '
test.py:13:9: F821 undefined name 'unknown'
test.py:17:1: E303 too many blank lines (3)
test.py:17:19: W292 no newline at end of file

运行后看到linter结果提示,说明已经可以工作了。

步骤二: 安装SublimeLinter 和 SublimeLinter-Flake8


打开Sublime Text分别安装SublimeLinter 和 SublimeLinter-Flake8这两个插件。
然后打开Preferences > Package preferences > SublimeLinter > Settings 。
写配置文件。

// SublimeLinter Settings - User  
{
    "linters": {
        "flake8": {
            "args": [
                "--max-line-length", "120",
                "--ignore", "E133,E226",
            ],
        },
    },
    "paths": {
        "linux": [],
        "osx": ["/Users/snow/.pyenv/shims/"],
        "windows": []
    }
}

步骤三: 开始写代码


恭喜你!在完成以上几个步骤以后,我们可以使用强大的linter了。


三步搞定python代码Linter_第1张图片
linter.jpg

参考


  • Three steps to lint Python 3.6 in Sublime Text
  • Flake8 docs
  • SublimeLinter-flake8

你可能感兴趣的:(三步搞定python代码Linter)