[python] Using both Python 2.x and Python 3.x in IPython Notebook

I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.

I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uninstalled Anaconda and now have set up my own installation using MacPorts and PiP. It seems that I still have to use

port select --set python <python version> 

to toggle between python 2.x and 3.x. which is no better than the anaconda solution.

Is there a way to select what version of python you want to use after you start an IPython notebook, preferably with my current MacPorts build?

This question is related to python python-2.7 python-3.x ipython ipython-notebook

The answer is


The idea here is to install multiple ipython kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added instructions using pure virtualenvs.

Anaconda >= 4.1.0

Since version 4.1.0, anaconda includes a special package nb_conda_kernels that detects conda environments with notebook kernels and automatically registers them. This makes using a new python version as easy as creating new conda environments:

conda create -n py27 python=2.7 ipykernel
conda create -n py36 python=3.6 ipykernel

After a restart of jupyter notebook, the new kernels are available over the graphical interface. Please note that new packages have to be explicitly installed into the new environments. The Managing environments section in conda's docs provides further information.

Manually registering kernels

Users who do not want to use nb_conda_kernels or still use older versions of anaconda can use the following steps to manually register ipython kernels.

configure the python2.7 environment:

conda create -n py27 python=2.7
conda activate py27
conda install notebook ipykernel
ipython kernel install --user

configure the python3.6 environment:

conda create -n py36 python=3.6
conda activate py36
conda install notebook ipykernel
ipython kernel install --user

After that you should be able to choose between python2
and python3 when creating a new notebook in the interface.

Additionally you can pass the --name and --display-name options to ipython kernel install if you want to change the names of your kernels. See ipython kernel install --help for more informations.


With a current version of the Notebook/Jupyter, you can create a Python3 kernel. After starting a new notebook application from the command line with Python 2 you should see an entry „Python 3“ in the dropdown menu „New“. This gives you a notebook that uses Python 3. So you can have two notebooks side-by-side with different Python versions.

The Details

  1. Create this directory: mkdir -p ~/.ipython/kernels/python3
  2. Create this file ~/.ipython/kernels/python3/kernel.json with this content:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
    
  3. Restart the notebook server.

  4. Select „Python 3“ from the dropdown menu „New“
  5. Work with a Python 3 Notebook
  6. Select „Python 2“ from the dropdown menu „New“
  7. Work with a Python 2 Notebook

If you’re running Jupyter on Python 3, you can set up a Python 2 kernel like this:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html


Use sudo pip3 install jupyter for installing jupyter for python3 and sudo pip install jupyter for installing jupyter notebook for python2. Then, you can call ipython kernel install command to enable both types of notebook to choose from in jupyter notebook.


From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.

Reference:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


UPDATE:

The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install


I looked at this excellent info and then wondered, since

  1. i have python2, python3 and IPython all installed,
  2. i have PyCharm installed,
  3. PyCharm uses IPython for its Python Console,

if PyCharm would use

  1. IPython-py2 when Menu>File>Settings>Project>Project Interpreter == py2 AND
  2. IPython-py3 when Menu>File>Settings>Project>Project Interpreter == py3

ANSWER: Yes!

P.S. i have Python Launcher for Windows installed as well.


Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p


These instructions explain how to install a python2 and python3 kernel in separate virtual environments for non-anaconda users. If you are using anaconda, please find my other answer for a solution directly tailored to anaconda.

I assume that you already have jupyter notebook installed.


First make sure that you have a python2 and a python3 interpreter with pip available.

On ubuntu you would install these by:

sudo apt-get install python-dev python3-dev python-pip python3-pip

Next prepare and register the kernel environments

python -m pip install virtualenv --user

# configure python2 kernel
python -m virtualenv -p python2 ~/py2_kernel
source ~/py2_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py2 --user
deactivate

# configure python3 kernel
python -m virtualenv -p python3 ~/py3_kernel
source ~/py3_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py3 --user
deactivate

To make things easier, you may want to add shell aliases for the activation command to your shell config file. Depending on the system and shell you use, this can be e.g. ~/.bashrc, ~/.bash_profile or ~/.zshrc

alias kernel2='source ~/py2_kernel/bin/activate'
alias kernel3='source ~/py3_kernel/bin/activate'

After restarting your shell, you can now install new packages after activating the environment you want to use.

kernel2
python -m pip install <pkg-name>
deactivate

or

kernel3
python -m pip install <pkg-name>
deactivate

Under Windows 7 I had anaconda and anaconda3 installed. I went into \Users\me\anaconda\Scripts and executed

sudo .\ipython kernelspec install-self

then I went into \Users\me\anaconda3\Scripts and executed

sudo .\ipython kernel install

(I got jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.)

After starting jupyter notebook (in anaconda3) I got a neat dropdown menu in the upper right corner under "New" letting me choose between Python 2 odr Python 3 kernels.


  • If you are running anaconda in virtual environment.
  • And when you create a new notebook but i's not showing to select the virtual environment kernel.
  • Then you have to set it into the ipykernel using the following command
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to ipython

How to increase image size of pandas.DataFrame.plot in jupyter notebook? Importing .py files in Google Colab Selection with .loc in python IOPub data rate exceeded in Jupyter notebook (when viewing image) Purpose of "%matplotlib inline" Installing a pip package from within a Jupyter Notebook not working convert json ipython notebook(.ipynb) to .py file In which conda environment is Jupyter executing? How to make inline plots in Jupyter Notebook larger? %matplotlib line magic causes SyntaxError in Python script

Examples related to ipython-notebook

collapse cell in jupyter notebook Simple way to measure cell execution time in ipython notebook Using both Python 2.x and Python 3.x in IPython Notebook How do I add python3 kernel to jupyter (IPython) How to hide code from cells in ipython notebook visualized with nbviewer? Show DataFrame as table in iPython Notebook How to show PIL Image in ipython notebook ipython notebook clear cell output in code Format certain floating dataframe columns into percentage in pandas Pandas - Plotting a stacked Bar Chart