【问题标题】:"pylint (import error)" while import a module in the same folder with VSCode“pylint(导入错误)”同时在与 VSCode 相同的文件夹中导入模块
【发布时间】:2019-09-02 18:14:49
【问题描述】:

我正在使用 python 3.7.3 在 VSCode 中构建我的代码。

文件夹结构:

project 
├── main.py
└── modules
    ├── __init__.py
    ├── foo.py
    └── boo.py

在 foo.py 中:

import boo
boo.printBoo()

当我运行 foo.py 时,它可以工作。我可以得到我期望的结果。

This is boo

但是 VSCode 弹出:

无法导入 'boo' pylint(import-error)

虽然代码有效,但有没有办法摆脱pylint(import-error)


我已尝试将导入语句更改为

from ..modules import boo as Boo

错误:尝试在没有已知父包的情况下进行相对导入

import modules.boo as Boo

错误:没有名为“模块”的模块

是什么问题,是pylint的问题还是我误用了import?

【问题讨论】:

  • 所以在这种情况下我不能在 VSCode 中单独测试我的模块(foo.py)? -m 在 cmd 中工作
  • 尝试在项目根目录下添加空的__init__.py。

标签: python python-3.x visual-studio-code python-import pylint


【解决方案1】:

遇到了完全相同的问题,两个文件共存于同一个子文件夹中,执行得很好,但在 VSCode 中得到了 pylint(import-error)

我的解决方案是将以下文本添加到<projectroot>/.vscode/settings.json

{
    "python.linting.pylintArgs": [
        "--init-hook",
        "import sys; sys.path.insert(0, './modules')"
    ]
}

这会将相关的“模块”子文件夹添加到 pylint 的路径中,除了项目根文件夹

【讨论】:

    【解决方案2】:

    import boo 在 Python 3 中从 foo 工作的唯一方法是直接运行 foo.py。如果是这种情况,那么您需要让 VS Code 打开您的 modules 目录而不是 project

    如果你想打开project,那么把导入改成from . import boo就可以了python3 -m modules.foo

    【讨论】:

      猜你喜欢
      • 2014-06-15
      • 2019-11-09
      • 2015-09-05
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      相关资源
      最近更新 更多