在Ipython中使用Pylint(Jupyter-Notebook)

oax*_*att 13 python pylint python-3.x flake8 jupyter-notebook

我想在使用Jupyter-Notebook时运行Pylint或任何等效项.有没有办法以这种方式安装和运行Pylint?

leo*_*irz 15

我建议您考虑nbQA工具:

pip install nbqa pylint
nbqa pylint my_notebook.ipynb
Run Code Online (Sandbox Code Playgroud)

此外pylintnbqa还可以轻松运行其他几个格式化程序和 linter 工具,并且可以通过其专用的预提交挂钩轻松集成到您的开发工作流程中。


小智 8

pycodestyle相当于pylintJupyter Notebook,可以根据PEP8样式指南检查代码.

首先,您需要通过键入此命令来安装pycodestylein jupyter notebook,

!pip install pycodestyle pycodestyle_magic
Run Code Online (Sandbox Code Playgroud)

在jupyter笔记本的单元格中运行此命令.安装成功后,你必须在这样的Jupyter Notebook单元中加载魔法,

%load_ext pycodestyle_magic
Run Code Online (Sandbox Code Playgroud)

然后,您必须pycodestyle在要根据PEP8标准调查代码的单元格中使用.

以下是一些更加清晰理解的例子,

%%pycodestyle
a=1
Run Code Online (Sandbox Code Playgroud)

输出:pycodestyle会给你这条消息,

2:2: E225 missing whitespace around operator
Run Code Online (Sandbox Code Playgroud)

另一个例子,

%%pycodestyle
def square_of_number(
     num1, num2, num3, 
     num4):
    return num1**2, num2**2, num3**2, num4**2
Run Code Online (Sandbox Code Playgroud)

输出:

2:1: E302 expected 2 blank lines, found 0
3:23: W291 trailing whitespace
Run Code Online (Sandbox Code Playgroud)

  • Pylint所做的不只是检查样式,还有很多人想使用Pylint的静态分析错误检测功能,这个库还能做到吗? (2认同)

de1*_*de1 5

更具体地回答有关 的问题pylint。在开发/ci 环境(即命令行)中实现这一目标的一种相对简单的方法是将笔记本转换为 Python,然后运行 ​​linting。

假设您的文件夹中有笔记本,并且路径中./notebooksjupyter和命令,您可以运行以下命令:pylint

jupyter nbconvert \
    --to=script \
    --output-dir=/tmp/converted-notebooks/ \
    ./notebooks/*.ipynb
pylint /tmp/converted-notebooks/*.py
Run Code Online (Sandbox Code Playgroud)

您可能需要配置 pylint,因为笔记本样式与一般 Python 模块略有不同。

您可能想要禁用的一些规则:

  • 无意义的陈述
  • 表达式未分配
  • 尾随换行符
  • 错误的导入位置
  • 重新定义的外部名称
  • 无效名称

单元格中的最大字符数(水平滚动之前)似乎也为,116但这可能取决于其他因素。

(例如,可以使用--max-line-length--disablepylint 参数或通过.pylintrc文件配置这些选项)