我在Windows上的Wing IDE内部运行PyLint。我有一个子目录(包)在我的项目和包内,我从顶层导入一个模块,即。

__init__.py
myapp.py
one.py
subdir\
    __init__.py
    two.py

在two.py中,我导入了一个,这在运行时工作得很好,因为顶层目录(myapp.py从其中运行)在Python路径中。然而,当我在two.py上运行PyLint时,它会给我一个错误:

F0401: Unable to import 'one'

我怎么解决这个问题?


当前回答

如果您想从交给pylint的当前模块/文件开始查找模块的根,可以使用这个方法。

[MASTER]
init-hook=sys.path += [os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i])) for i, _ in enumerate(sys.argv[-1].split(os.sep)) if os.path.isdir(os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i], '.git')))][::-1]

如果你有一个python模块~/code/mymodule/,它的顶级目录布局是这样的

~/code/mymodule/
├── .pylintrc
├── mymodule/
│   └── src.py
└── tests/
    └── test_src.py

然后这将把~/code/mymodule/添加到你的python路径中,并允许pylint在你的IDE中运行,即使你正在导入mymodule。SRC在tests/test_src.py中。

你可以用.pylintrc来代替检查,但当涉及到python模块的根目录时,git目录通常是你想要的。

在你问之前

使用import sys, os;Sys.path.append(…)缺少一些东西来证明我的答案的格式。我通常不这样写代码,但在这种情况下,您将受困于处理pylintrc配置解析器和求值器的局限性。它实际上是在init_hook回调的上下文中运行exec,因此任何导入pathlib的尝试,使用多行语句,将一些东西存储到变量中,等等,都不会工作。

我的代码的一种不那么恶心的形式可能是这样的:

import os
import sys

def look_for_git_dirs(filename):
    has_git_dir = []
    filename_parts = filename.split(os.sep)
    for i, _ in enumerate(filename_parts):
        filename_part = os.path.abspath(os.path.join(os.path.sep, *filename_parts[:i]))
        if os.path.isdir(os.path.join(filename_part, '.git')):
            has_git_dir.append(filename_part)
    return has_git_dir[::-1]

# don't use .append() in case there's < 1 or > 1 matches found
sys.path += look_for_git_dirs(sys.argv[-1])

我希望我可以使用pathlib.Path(文件名)。父母们,这样事情就容易多了。

其他回答

我刚刚发现的一个解决办法是,实际上只对整个包运行PyLint,而不是对单个文件运行PyLint。以某种方式,它设法找到导入的模块。

把另一个可能的答案扔到堆里。我尝试了这里提供的许多解决方案。要么是我做错了,要么是我的pylint导入错误是由其他原因引起的。不管怎样,我的解决方法非常简单。

解决方案:重新安装包含您无法导入的所有模块的包(PyPi包而不是pip包),然后重新安装pylint,以便pylint和这些模块由相同的pip安装。

对我来说,拥有正确的目录并不管用。我从另一个关于他的问题的帖子中得到了这个想法。

这个问题可以通过在venv下配置pylint路径来解决: $ cat .vscode/settings.json

{
    "python.pythonPath": "venv/bin/python",
    "python.linting.pylintPath": "venv/bin/pylint"
}

I have been struggling with this a lot and eventually found out something that was not described here. Here are my 2 cents to this issue: I am using VS Code on Windows, using virtual env. For some reasons, the pylint executable is called epylint and not pylint. In my script or from CLI prompt, I was running pylint ./xxx and the system was launching a pylint it found somewhere else but not the appropriate one. I just added an e in my shell script and my 'Unable to import' issues eventually vanished.

Mac用户:如果你正在使用Anaconda 3 w/ vsCode,并且有多个环境,通过设置指向以下路径。json for vsCode也可以:

{
  "python.pythonPath": "/Users/username/opt/anaconda3/bin/python",
  "python.linting.pylintPath": "/Users/username/opt/anaconda3/bin/python"
}