Using Both Python 2.X and Python 3.X in Ipython Notebook

Using both Python 2.x and Python 3.x in IPython Notebook

A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.

Requirements:

  • MacPorts is installed in the usual /opt directory
  • python 2.7 is installed through macports
  • python 3.4 is installed through macports
  • Ipython is installed for python 2.7
  • Ipython is installed for python 3.4

For python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

For python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

Now you can open an Ipython notebook and then choose a python 2.x or a python 3.x notebook.

Choose your python!

Jupyter notebook with Python 2 and Python3 Kernel

  1. Make sure you have pip version greater than 9.0
$ python2 -m pip --version

  1. Then do this
$ python2 -m pip install ipykernel OR python2 -m pip install ipykernel --user
$ python2 -m ipykernel install --user

  1. Start or restart Jupyter and you should be done.

This solution is from the ipython docs by the way.

Using both python3 and python2 in a Jupyter Notebook Document

Use the %%python2 cell magic at the top of the cell to make the rest of the cell run in python2. Same with %%python3 for python3. You should only really need to use one though, as the one which is the native kernel shouldn't need to have it's magic declared.

In a python2 notebook:

Cell1:

%%python3
print("Hello world!")

Cell2:

print "Hello world!"


Related Topics



Leave a reply



Submit