'Unable to import' VS Code 中 anaconda 环境的错误

'Unable to import' errors for anaconda environment in VS Code

我正在尝试使用 FEniCS 求解 Python 的偏微分方程。我使用 anacondaconda-forge 安装它并使用它,我激活了 fenicsproject 环境

source activate fenicsproject

我 运行 我的脚本在 jupyter 中(有效),但通常使用 VS Code 来编写更详细的代码会更方便。当我 运行 在(内置)终端中用 VS Code 编写的脚本时,只要我启用了 fenicsproject 环境,它们就会 运行 没有错误。

但是在编辑器中我遇到了很多这样的错误

[pylint] Unable to import '...' [E0401]'
[pylint] Undefined variable '...' [E0602]

我怎样才能去掉编辑器中的那些错误,以便真正的错误能够脱颖而出。 更好的是,使自动完成和建议适用于 fenicsmshr 等包

根据 the Python in Visual Studio Code docs,这可能是由于 Visual Studio 代码指向错误的 Python 版本。

1. Unable to import (pylint)

  • Scenario: You have a module installed, however the linter in the IDE is complaining about; not being able to import the module, hence error messages such as the following are displayed as linter errors:

    .. unable to import 'xxx' ..
    
  • Cause: The Python extension is most likely using the wrong version of Pylint.
Solution 1: (configure workspace settings to point to fully qualified python executable):
  1. Open the workspace settings (settings.json)
  2. Identify the fully qualified path to the python executable (this could even be a virtual environment)
  3. Ensure Pylint is installed for the above python environment
  4. Configure the setting "pythonPath" to point to (previously identified) the fully qualified python executable.

    "python.pythonPath": "/users/xxx/bin/python" ```
    
Solution 2: (open VS Code from an activated virtual environment):
  1. Open the terminal window
  2. Activate the relevant python virtual environment
  3. Ensure Pylint is installed within this virtual environment

    pip install pylint
    
  4. Close all instances of VS Code
  5. Launch VS Code from within this terminal window
    (this will ensure the VS Code process will inherit all of the Virtual Env environment settings)