Skip to content
Advertisement

‘Unable to import’ errors for anaconda environment in VS Code

I am trying to solve partial differential equations with Python using FEniCS. I installed it with anaconda and conda-forge and to use it, I activate the fenicsproject environment

source activate fenicsproject

I run my scripts in jupyter (that works), but often it is more convenient to use VS Code for more elaborate code. When I run the scripts written in VS Code in the (built-in) terminal, they run without error as long as I have the fenicsproject environment enabled.

But in the editor I get a lot of errors like this

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

How can I get rid of those errors in the editor, so that the real errors can stand out. What would be even better, make it that auto-complete and suggestions work for the packages like fenics, mshr etc.

Advertisement

Answer

According to the Python in Visual Studio Code docs, this is probably due to Visual Studio Code pointing at the wrong Python version.

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)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement