Reputation: 8132
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:
Python 2.7
and then use the output of that cell throughout the rest of the notebook script?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.
Upvotes: 0
Views: 444
Reputation: 40340
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
Upvotes: 1