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

我怎么解决这个问题?


当前回答

在这两个目录中都有一个空的__init__.py文件来让python知道dirs是模块吗?

当你不是从文件夹中运行时(比如可能从pylint的文件夹中运行,尽管我没有用过),基本的大纲是:

topdir\
  __init__.py
  functions_etc.py
  subdir\
    __init__.py
    other_functions.py

这就是python解释器如何在不引用当前目录的情况下感知模块,因此如果pylint从它自己的绝对路径运行,它将能够以topdir的身份访问functions_etc.py。Functions_etc或topdir.subdir。other_functions,前提是topdir在PYTHONPATH上。

UPDATE: If the problem is not the __init__.py file, maybe just try copying or moving your module to c:\Python26\Lib\site-packages -- that is a common place to put additional packages, and will definitely be on your pythonpath. If you know how to do Windows symbolic links or the equivalent (I don't!), you could do that instead. There are many more options here: http://docs.python.org/install/index.html, including the option of appending sys.path with the user-level directory of your development code, but in practice I usually just symbolically link my local development dir to site-packages - copying it over has the same effect.

其他回答

如果你使用的是Windows:

获取刚刚创建的虚拟环境中python.exe的路径 它应该像这样Z:\YourProjectFolder\Scripts\python.exe 然后转到vscode,编辑user settings.json 添加这一行:"python。pythonPath环境”:“Z: \ \ YourProjectFolder \ \ \ \ python.exe脚本” 保存它,这应该可以解决问题 注意:在json文件中使用双反斜杠而不是单反斜杠

{
    "python.pythonPath": "Z:\\YourProjectFolder\\Scripts\\python.exe"
}

我找到了一个很好的答案。编辑pylintrc并在master中添加以下内容

init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"

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

我在项目的根目录中添加了一个新文件pylintrc

[MASTER]
init-hook='import sys; sys.path.append(".")'

它在PyCharm IDE中为我工作

如果有人正在寻找一种在PyCharm中运行pylint作为外部工具的方法,并让它在他们的虚拟环境中工作(为什么我想到这个问题),下面是我如何解决它:

在PyCharm > Preferences > Tools > External Tools中,为pylint添加或编辑一个项目。 在“编辑工具”对话框的“工具设置”中,将“程序”设置为使用python解释器目录中的pylint: $PyInterpreterDirectory$/pylint 在parameters字段中设置其他参数,例如:——rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$ 将工作目录设置为$FileDir$

现在使用pylint作为外部工具将在您使用公共配置文件选择的任何目录上运行pylint,并使用为您的项目配置的任何解释器(假设是您的virtualenv解释器)。