在iPython笔记本代码中验证PEP8

时间:2014-09-30 17:41:28

标签: python ipython ipython-notebook pep8

是否有一种简单的方法可以检查iPython笔记本代码在编写时是否符合PEP8?

5 个答案:

答案 0 :(得分:20)

确保模块pycodestyle能够根据样式指南检查您的代码。然后使用pycodestyle_magic模块(github repo)启用魔术功能:

pip install pycodestyle flake8 pycodestyle_magic
  • 首先在Jupyter Notebook单元格中加载魔法:

%load_ext pycodestyle_magic

  • 然后使用单元格中的功能检查是否符合pycodestyle

%%pycodestyle

enter image description here

编辑(2018-09-11)

pycodestyle_magic版本0.2.2开始,还可以检查flake8样式指南。使用

%%flake8

答案 1 :(得分:13)

使用以下命令为ipython notebook安装pep8扩展:

%install_ext https://raw.githubusercontent.com/SiggyF/notebooks/master/pep8_magic.py

有关详细信息,请参阅the official docs

之后使用%%pep8 Cell magic函数检查你的特定单元格的pep8样式。

请注意,必须将其放在需要执行pep8检查的每个单元格中。

参考this example

答案 2 :(得分:8)

如果这有助于任何人,我正在使用:

conttest "jupyter nbconvert notebook.ipynb --stdout --to script | flake8 - --ignore=W391"

    保存对笔记本的更改时,
  • conttest重新运行
  • flake8 -告诉flake8从stdin
  • 获取输入
  • --ignore=W391 - 这是因为jupyter nbconvert的输出似乎总是在文件末尾有一个“空白行”,所以我不希望flake8抱怨这一点。

我遇到了markdown单元格的问题(但是它的行长度可能合法地很长):ignore markdown cells in `jupyter nbconvert` with `--to script`

答案 3 :(得分:0)

您可以包括我的脚本的某些部分(下面的链接),以查看有关哪些代码行需要特定的PEP8更正的详细信息。您也可以独立运行它。

该脚本将PEP8注释包含在基于flake8的py文件代码中。 这样可以很容易地立即跳转到需要纠正样式的地方。

您可以在这里检查: https://github.com/Softerec/PEP8-commenter

答案 4 :(得分:0)

我建议为此使用 nbQA

pip install -U nbqa flake8
conttest "nbqa flake8 notebook.ipynb"

因为它会跳过 Markdown 单元格并稳健地处理 IPython 魔法。

其他答案的问题是:

  • "jupyter nbconvert" 对魔法不可靠
  • pycodestyle_magic 很遗憾不再维护(最后一次提交是在 2019 年)
  • install_ext 已弃用

免责声明:我是 nbQA 的作者