How to fix No module named ipykernel in Python

When running Python code in Jupyter Notebook, you might get the following error:

No module named ipykernel

There are two possible causes for this error:

  1. ipykernel is not installed
  2. The path to ipykernel is not defined under the kernel.json file

This tutorial will show you how I fix the error in both scenarios.

1. ipykernel is not installed

The ipykernel package needs to be installed to resolve this error.

You can install the package using pip as follows:

source activate <ANACONDA_ENVIRONMENT_NAME>
pip install ipykernel
python -m ipykernel install --user

Or you can also use conda to install the package:

conda install ipykernel

If you already have ipykernel installed before, then you can try to uninstall and reinstall the package to make it work.

2. The path to ipykernel is not defined

The command to execute ipykernel is stored under the kernel.json file, which is usually found at this path:

~/Library/Jupyter/kernels/<env>/kernel.json

The JSON file contains the following:

{
 "argv": [ "/Users/<username>/.pyenv/versions/<env>/bin/python",
    "-m", 
    "ipykernel", 
    "-f", 
    "{connection_file}"],
 "display_name": "<env>",
 "language": "python"
}

In short, the JSON file contains a command to run python -m ipykernel to the notebook you want to execute.

If you don’t have the kernel.json file, reinstalling the ipykernel package using conda should generate the file as well.

If that doesn’t work, then you need to manually create the kernel.json file at the location your Jupyter Notebook seeks the file.

If you still can’t run the code, then the last option is to create a new virtual environment using conda and run your code there.

conda create --name newenv
conda activate newenv

Install the packages you need in this new environment, then try running Jupyter Notebook there.

If it works, you can safely delete the old environment.

Conclusion

The error No module named ipykernel occurs when you try to import the ipykernel package before installing it, or when you run code using Jupyter Notebook.

To fix this error, you need to make sure that the ipykernel package is installed, and that you have the kernel.json file in your virtual environment.

Usually, reinstalling the ipykernel package or creating a new virtual environment should resolve this error.

I hope this tutorial helps. Happy coding!

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.