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

我怎么解决这个问题?


当前回答

如果使用vscode,请确保包目录不在_pychache__目录中。

其他回答

Try

if __name__ == '__main__':
    from [whatever the name of your package is] import one
else:
    import one

注意,在Python 3中,else子句中部分的语法为

from .. import one

转念一想,这可能并不能解决你的具体问题。我误解了这个问题,以为two.py是作为主模块运行的,但事实并非如此。并且考虑到Python 2.6(没有从__future__导入absolute_import)和Python 3方式的差异。x句柄导入,你不需要在Python 2.6中这样做,我不认为。

不过,如果你最终切换到Python 3,并计划将一个模块既用作包模块,又用作包中的独立脚本,那么保留它可能是一个好主意 类似的

if __name__ == '__main__':
    from [whatever the name of your package is] import one   # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
    from .. import one

在心里的。

编辑:现在是解决你实际问题的可能方案。要么从包含你的一个模块的目录中运行PyLint(可能是通过命令行),要么在运行PyLint时将以下代码放在某个地方:

import os

olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)

基本上,作为处理PYTHONPATH的另一种方法,只需确保在执行导入时当前工作目录是包含one.py的目录。

(看看Brian的回答,你可能会把前面的代码分配给init_hook,但如果你要这样做,那么你可以简单地追加到sys. hook。路径,这比我的解决方案略优雅。)

关键是将你的项目目录添加到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

1)系统。Path是一个列表。

2)有时问题出在系统。Path不是你的virtualenv。路径,你想在你的virtualenv中使用pylint

3)就像上面说的,使用init-hook(注意' and " pylint的解析是严格的)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

or

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

.. 而且

pylint --rcfile /path/to/pylintrc /path/to/module.py

也许通过手动在PYTHONPATH中追加目录?

sys.path.append(dirname)

如果你在Linux中使用Cython,我决定删除module.cpython-XXm-X-linux-gnu。我的项目目标目录下的文件。