在Pycharm中配置autopep8

weixin_34208283發表於2017-01-18

關於PEP 8,Style Guide for Python Code,是Python官方推出的Python編碼風格的約定,雖然這不是硬性的規定,但是如果Python程式設計師都儘量遵循這個文件,那麼編碼風格的統一會讓程式碼的可讀性大大提升。

在Pycharm裡邊預設也是有進行PEP8的檢測,強迫症的人表示,看到程式碼中有黃色波浪線,就一定得先改好它。

關於autopep8官網的描述是:
autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pep8 utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues that can be reported by pep8.

通過它,可以修復大部分PEP8工具中報告的程式碼排版問題。舉個官網的例子:

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)

這是一個比較極端情況的例子,在使用了autopep8自動修復後:

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)

是不是看起來煥然一新了?

Pycharm中使用autopep8作為擴充套件工具

** 1.安裝autopep8 **

    pip install autopep8

** 2.Pycharm進行設定 **

  • Settings–>Tools–>External Tools 點選新增按鈕Name:autopep8(可以自定義)

  • Tools settings:

    • Programs:autopep8(不能修改)
    • Parameters:--in-place --aggressive --aggressive $FilePath$
    • Working directory:$ProjectFileDir$
  • 點選Output Files

    • 點選新增,名稱可以任意填寫
    • Regular expression to match output:$FILE_PATH$:$LINE$:$COLUMN$:.*

** 實際使用 **
在右擊上程式碼–>External Tool–>autopep8
Pycharm自動呼叫了autopep8對當前檔案進行PEP8優化。

** autopep8的一些設定點 **
在上邊說到,在Parameters的設定是:--in-place --aggressive --aggressive $FilePath$

  • –in-place 代表會直接修改原始檔
  • –aggressive autopep8預設只修復空白,對齊相關的PEP8問題,加入--aggressive設定,會增加修復如 x == None 修復為 x is None,{“a”: 1, “b”: 2}.has_key(‘a’) 修復為’a’ in {“a”: 1, “b”: 2}
  • –ignore 忽略PEP8檢查項
    因為我只打算用autopep8來修復空格,空行這一類的排版問題,同時要忽略每一行長度過長的檢測(E501 - Try to make lines fit within –max-line-length characters.),
    所以最終設定是:
    --in-place --ignore=E501 $FilePath$

原文連結:http://jianbing.github.io/2016/06/29/pycharm-autopep8/

相關文章