Python ImportError: No module named pygments

Viewed 9138

I ran the following code

# Allows the use of display() for displaying 
from IPython.display import display DataFrames

It displayed the following error:

 File "/usr/lib64/python2.7/site-packages/IPython/utils/colorable.py", line 13, in <module>
    import pygments
ImportError: No module named pygments

So I tried installing pygments:

pip install pygments

and it says:

Requirement already satisfied: pygments in /home/rico/downloads/hgvs-0.1.2/Pygments-2.1.3-py2.7.egg (2.1.3)

Do you have an idea how to resolve this issue? Thanks.

1 Answers

It seems that you installed the Pygments module on the global scope instead of installing inside a virtualenv.

What is a virtual environment?

Virtual environments are a way to keep your dependencies inline for your app or service.
virtualenv is a tool to create isolated Python environments, in which you can now install dependencies specific for that environment rather than installing them globally.

Virtual environments help create consistency in your development and deployment process, which in turn will help build a better app or service.

Installing virtualenv

First, Install virtual env:

pip install virtualenv

To create a virtualenv first run this command:

$ virtualenv -p python3 {name-of-virtual-env} 

Lets call it my_venv, so ran the following command:

$ virtualenv -p python3 my_venv 

Once you create the virtual environment, run the following to activate it:

$ source my_venv/bin/activate 

After running the activate command you should see the name of your virtual env at the beginning of your terminal like this:

(my_venv) $ source my_venv/bin/activate 

Installing modules locally

Navigate inside the my_venv folder and install the Pygments module:

cd my_venv && pip3 install pygments

You should see it was installed localy under lib/python3.8/site-packages inside the my_venv folder:

`-- my_venv
    |-- bin
    |-- lib
    |   `-- python3.8
    |       `-- site-packages
    |           |-- chardet
    |           |-- chardet-3.0.4.dist-info
    |           |-- idna
    |           |-- pip
    |           |-- pip-21.0.1.dist-info
    |           |-- pip-21.0.1.virtualenv
    |           |-- pkg_resources
    |           |-- pygments #<--------- Here
    |           |-- pygments_promql            
    |           |-- pygments_promql-0.0.5.dist-info
    |           |-- regex
    `-- pyvenv.cfg

Deactivate virtualenv

When you are done running your app or service, you can shutdown your virtualenv by running the deactivate command:

(my_venv) $ deactivate

Read more in here.

Related