我在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'

我怎么解决这个问题?


当前回答

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.

其他回答

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

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

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

在init-hook中改变路径的解决方案很好,但我不喜欢必须在那里添加绝对路径的事实,因此我不能在项目的开发人员之间共享这个pylintrc文件。这个解决方案使用相对路径pylintrc文件更适合我:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

请注意pylint.config.PYLINTRC也存在,并且具有与find_pylintrc()相同的值。

我发现这在我的本地.pylintrc文件和pipenv虚拟环境中工作得很好:

[MASTER]
init-hook='import site; sys.path += site.getsitepackages()'

有关站点包的信息请参阅这篇文章。

关键是将你的项目目录添加到sys。路径而不考虑env变量。

对于使用VSCode的人,如果你的项目有一个基本目录,这里有一个简单的解决方案:

[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+\/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'

让我来解释一下:

re.search (r”。+\/" + base_dir, os.getcwd()).group():根据编辑文件查找基目录 Os.path.join (os.getcwd(), base_dir):添加CWD到系统。满足命令行环境的路径


供你参考,这是我的.pylintrc:

https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f

我必须更新系统PYTHONPATH变量来添加我的应用程序引擎路径。在我的例子中,我只需要编辑我的~/。Bashrc文件,并添加以下行:

出口到PYTHONPATH = $ PYTHONPATH: /道路/ / google_appengine_folder

事实上,我尝试先设置init-hook,但这并没有在我的代码库中始终解决这个问题(不确定为什么)。一旦我将它添加到系统路径(一般来说可能是一个好主意),我的问题就消失了。