如果目录不包含 __init__.py 文件,pylint 会引发错误

pylint raises error if directory doesn't contain __init__.py file

我的文件夹只包含 python 个要执行的脚本。没有必要保留 __init__.py 文件。那么我可以忽略这样的错误吗?

$ pylint /app
Using config file /app/pylintrc
************* 
F:  1, 0: error while code parsing: Unable to load file /app/__init__.py:
[Errno 2] No such file or directory: '/app/__init__.py' (parse-error)

这是 PyLint 的一个已知未决问题:

lint all files in a directory (打开)

Consider supporting a folder of python files which is not a package (重复,关闭)

不幸的是,正如我们在讨论中看到的那样,没有人继续致力于此。

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.13.6
BuildVersion:   17G65

$ pylint --version
pylint 2.1.1
astroid 2.0.3
Python 3.7.0 (default, Jul 23 2018, 20:22:55) 
[Clang 9.1.0 (clang-902.0.39.2)]

更新

我通过尝试使它起作用:

$ cd /app
$ pylint *.py

或尝试:

$ pylint /path/to/app/*.py

并使整个工作正常进行。

...
Report
======
************* Module <yourmodname>
...
X statements analysed.

Statistics by type
------------------

+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
...

错误

我曾经尝试过:

$ pylint .
************* Module .
__init__.py:1:0: F0010: error while code parsing: Unable to load file 
__init__.py:
[Errno 2] No such file or directory: '__init__.py' (parse-error)

这个问题出现在我们的一些项目中。

在其中一个项目中,我们最近成功构建,但突然间一切都开始无故失败。我们查看了我们的 CI 日志到最后一次成功构建,复制了所有安装的确切版本。以这种方式构建时,一切正常。新版本会失败。

此项目的成功构建来自 23.02.2019,失败的构建来自 25.02.2019。没有引入实质性的变化。 运行和之前一样的状态,又失败了...

为此投入了更多的时间,我们发现:

  • 调试时,开始出现其他错误。原来astroidreleased version 2.2.0 in 27.02.2019 and this basically broke pylint. Pinning astroid back to version 2.1.0 solves this problem. We'll keep it like this until they release a patch or pylint starts to deal with the new version. There's an issue上Github关于这个

  • 随着 astroid 问题的解决,我们又回到了由于某些目录中缺少 __init__.py 文件而导致的失败(这些是 Python 3.7 项目我们不需要空 __init__.py 文件...)

  • 进行了多次尝试以找出旧组合有效而新组合无效的原因。在大量失败的构建之后,我们发现 PATCH update 的另一个依赖项 pylint -- isort -- 来自 4.3.44.3.5,于 25.02.2019 发布,引入了错误。将它固定回版本 4.3.4 工作得很好。上面的任何东西都失败了。老实说,该更新没有遵循语义版本控制规则(绝对 不是 补丁版本...它更可能是 主要 !) .

为什么 isort 会造成这种情况,我还没有找到,但我决定在这里分享这些发现,这样您就可以节省几个小时的反复试验。

TL;DR:

将此添加到您的 requirements.txt(至少在 pylint 的下一个版本之前):

# astroid 2.2.0 seems to break everything in pylint
astroid==2.1.0
# isort above 4.3.4 introduces the "__init__.py not found" issue
isort==4.3.4

我想到了这个解决方案(不适用于 Windows):

pylint $(echo -n /app/*.py && echo -n ' ' && find /app -type d -maxdepth 1 -exec test -e '{}'/__init__.py \; -print | grep -v '^/app/\.')

因此这将包括 /app 目录中的所有 .py 文件作为参数,以及 /app 目录中包含 __init__.py 文件的所有目录作为参数. grep 管道正在删除 /app 中以点开头的所有目录名称。