When multiple versions of python are installed in a system along with anaconda3, jupyter kernels might run the wrong python version. Here is an example.

When we start the Python 2 kernel explicitly from the drop-down menu, we expect Jupyter to be running Python 2. But that is not the case as verified below.

The culprit is the kernel.json file in the jupyter kernel folder at /usr/share/jupyter/kernels/python2.

The kernel.json file asks jupyter to run /usr/bin/python. But /usr/bin/python points to python3 and not python2. Therefore, jupyter ends up running python 3 . We will need to replace python with python2 in the kernel.json file (/usr/share/jupyter/kernels/python2).
{
"argv": [
"/usr/bin/python2",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "Python 2",
"language": "python"
}
Save the file and restart jupyter.
I had to repeat a similar procedure with the Sagemath Jupyter kernel. /usr/share/jupyter/kernels/sagemath had the following kernel declaration for jupyter that was causing the kernel to crash.
{
"display_name": "SageMath 8.1",
"argv": [
"/usr/bin/sage",
"--python",
"-m",
"sage.repl.ipython_kernel",
"-f",
"{connection_file}"
]
}
When the python was replaced with python2 it started working.
{
"display_name": "SageMath 8.1",
"argv": [
"/usr/bin/sage",
"--python2",
"-m",
"sage.repl.ipython_kernel",
"-f",
"{connection_file}"
]
}
For Sagemath installed from source this will never happen. However, if Sagemath was installed from the repositories (sudo apt install sagemath sagemath-common) then this error is inevitable due to the dependency of sagemath python 2 (see my article https://bytesofcomputerwisdom.home.blog/2019/03/23/sagemathwont-run-no-module-named-sage-repl/).