有没有一种简单的方法可以在编写iPython笔记本代码时检查其是否符合PEP8标准?
有没有一种简单的方法可以在编写iPython笔记本代码时检查其是否符合PEP8标准?
确保你已经安装了模块pycodestyle
或flake8
以便检查你的代码是否符合风格指南。然后使用pycodestyle_magic
模块(github repo)来启用魔术函数:
pip install flake8 pycodestyle_magic
%load_ext pycodestyle_magic
%pycodestyle_on
或 %flake8_on
具体使用哪个命令取决于你要检查哪个代码风格指南。
若要关闭自动合规性检查,请运行:
%pycodestyle_off
或 %flake8_off
如果有人需要帮助,我使用以下命令:
conttest "jupyter nbconvert notebook.ipynb --stdout --to script | flake8 - --ignore=W391"
conttest
将在保存笔记本更改时重新运行flake8 -
告诉flake8从stdin中获取输入--ignore=W391
- 这是因为jupyter nbconvert
的输出似乎总是有一个"文件末尾的空行",所以我不想让flake8抱怨。我遇到了一个问题,即markdown单元格(其行长度可能合法地相当长):忽略“ jupyter nbconvert”中的markdown单元格与`--to script`。
conttest "nbqa flake8 notebook.ipynb --extend-ignore=W391"
。这也会忽略Markdown单元格。 - ignoring_gravity我建议使用nbQA进行此操作:
pip install -U nbqa flake8
conttest "nbqa flake8 notebook.ipynb"
这样做能够跳过Markdown单元格并且可以稳健地处理IPython魔法方法。
其他回答存在的问题:
pycodestyle_magic
很不幸已经不再维护(最后一次提交是2019年)install_ext
已被废弃免责声明:我是nbQA的作者
我喜欢使用black
代码检查工具和pre-commit
git钩子(每次提交时自动进行代码检查)来保持我的笔记本整洁。
pip install pre-commit "black[jupyter]"
# <-- create your .pre-commit-config.yaml
pre-commit install
black {source_file_or_directory}
# your notebooks will be linted whenever you commit now
如需设置.pre-commit-config.yaml
的说明,请参阅black文档和pre-commit文档。
如果你想要从代码或程序中解放出来,避免过多关注EPE8,那么请同时安装两个纠错程序。
我们进行安装:
pip install nb_black
pip install flake8 pycodestyle_magic
将其粘贴到代码开头:
%load_ext nb_black
%load_ext pycodestyle_magic
%pycodestyle_on
注意,顺序很重要。
nb_black
,以及为什么顺序很重要吗? - frederick-douglas-pearce
%flake8_on
或%pycodestyle_off
时,出现了一个奇怪的错误:TypeError: auto_run_flake8() missing 1 required positional argument: 'result'
和TypeError: auto_run_pycodestyle() missing 1 required positional argument: 'result'
。 - Taylor D. Edmiston