0

I'm using the Jupyter Notebook to write some Python 3.4 code, but I have to load a class that has been written in Python 2.7.

The class I'm trying to load was not written by me so I can't really (or want) to upgrade all the code to Python 3.4. The use of that class is very limited throughout the rest of the code and is just used to return some data that is compatible with Python 3.4.

I have 2 questions:

  • Is there any way I can run a single cell in Python 2.7 and then use the output of that cell throughout the rest of the notebook script?
  • If not do you have any suggestion?

Desired usage:

+++++ Python 2.7 cell +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In[1]: #load the class
       my_class = MYCLASS()
       #use the class to get 3.4 compatible data
       data_list = my_class.produce_data() 

+++++ Python 3.4 cell ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In[2]: #use the data list in a 3.4 way
       for x in data_list:
           print(x)

I found a similar question, Calling Python 2 script from Python 3, but no real solution was provided besides a couple hacks in the comments.

NOTE: This question is completely unrelated to Using both Python 2.x and Python 3.x in IPython Notebook, which is about how to use both languages and not about how to reference one from the other.

Community
  • 1
  • 1
Matteo
  • 7,924
  • 24
  • 84
  • 129
  • 1
    Can you run `2to3` on your `Python 2.7` class? – davejagoda Nov 17 '15 at 17:23
  • @davejagoda - It's not very intuitive, there are multiple files and also you have to compile using cython in order to use it, and I think that links to some 2.7 libraries. – Matteo Nov 17 '15 at 18:28
  • 2
    If you have both versions of Python installed, you can put `%%python2` at the top of a cell to run it in Python 2. However, that code will be run in a separate process, so you'll need to write the data out (e.g. using [pickle](https://docs.python.org/3/library/pickle.html)) and then read it in again in your Python 3 code. – Thomas K Nov 18 '15 at 09:52
  • @ThomasK - Thanks for your comment, this seems to be the closest I'll get to being able to run both in the same notebook. Could you post an answer and direct me to some documentation about `%%python2` command? – Matteo Nov 19 '15 at 18:35

1 Answers1

1

Reposting as an answer:

If you have both versions of Python installed, you can put %%python2 at the top of a cell to run it in Python 2. However, that code will be run in a separate process, so you'll need to write the data out (e.g. using pickle) and then read it in again in your Python 3 code.

Docs for the %%python2 magic are here:

http://ipython.readthedocs.org/en/stable/interactive/magics.html#cellmagic-python2

Thomas K
  • 39,200
  • 7
  • 84
  • 86