Converting to (not from) ipython Notebook format











up vote
41
down vote

favorite
23












IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already have materials, and a good workflow, in a different format, but I would like to take advantage of Notebook's interactive environment.



A likely solution: A notebook can be created by importing a .py file, and the documentation states that when nbconvert exports a notebook as a python script, it embeds directives in comments that can be used to recreate the notebook. But the information comes with a disclaimer about the limitations of this method, and the accepted format is not documented anywhere that I could find. (A sample is shown, oddly enough, in the section describing notebook's JSON format). Can anyone provide more information, or a better alternative?



Edit (1 March 2016): The accepted answer no longer works, because for some reason this input format is not supported by version 4 of the Notebook API. I have added a self-answer showing how to import a notebook with the current (v4) API. (I am not un-accepting the current answer, since it solved my problem at the time and pointed me to the resources I used in my self-answer.)










share|improve this question




























    up vote
    41
    down vote

    favorite
    23












    IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already have materials, and a good workflow, in a different format, but I would like to take advantage of Notebook's interactive environment.



    A likely solution: A notebook can be created by importing a .py file, and the documentation states that when nbconvert exports a notebook as a python script, it embeds directives in comments that can be used to recreate the notebook. But the information comes with a disclaimer about the limitations of this method, and the accepted format is not documented anywhere that I could find. (A sample is shown, oddly enough, in the section describing notebook's JSON format). Can anyone provide more information, or a better alternative?



    Edit (1 March 2016): The accepted answer no longer works, because for some reason this input format is not supported by version 4 of the Notebook API. I have added a self-answer showing how to import a notebook with the current (v4) API. (I am not un-accepting the current answer, since it solved my problem at the time and pointed me to the resources I used in my self-answer.)










    share|improve this question


























      up vote
      41
      down vote

      favorite
      23









      up vote
      41
      down vote

      favorite
      23






      23





      IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already have materials, and a good workflow, in a different format, but I would like to take advantage of Notebook's interactive environment.



      A likely solution: A notebook can be created by importing a .py file, and the documentation states that when nbconvert exports a notebook as a python script, it embeds directives in comments that can be used to recreate the notebook. But the information comes with a disclaimer about the limitations of this method, and the accepted format is not documented anywhere that I could find. (A sample is shown, oddly enough, in the section describing notebook's JSON format). Can anyone provide more information, or a better alternative?



      Edit (1 March 2016): The accepted answer no longer works, because for some reason this input format is not supported by version 4 of the Notebook API. I have added a self-answer showing how to import a notebook with the current (v4) API. (I am not un-accepting the current answer, since it solved my problem at the time and pointed me to the resources I used in my self-answer.)










      share|improve this question















      IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already have materials, and a good workflow, in a different format, but I would like to take advantage of Notebook's interactive environment.



      A likely solution: A notebook can be created by importing a .py file, and the documentation states that when nbconvert exports a notebook as a python script, it embeds directives in comments that can be used to recreate the notebook. But the information comes with a disclaimer about the limitations of this method, and the accepted format is not documented anywhere that I could find. (A sample is shown, oddly enough, in the section describing notebook's JSON format). Can anyone provide more information, or a better alternative?



      Edit (1 March 2016): The accepted answer no longer works, because for some reason this input format is not supported by version 4 of the Notebook API. I have added a self-answer showing how to import a notebook with the current (v4) API. (I am not un-accepting the current answer, since it solved my problem at the time and pointed me to the resources I used in my self-answer.)







      python ipython ipython-notebook jupyter-notebook






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 18 at 21:23

























      asked Apr 25 '14 at 11:48









      alexis

      33.3k954113




      33.3k954113
























          8 Answers
          8






          active

          oldest

          votes

















          up vote
          28
          down vote



          accepted










          The following works for IPython 3, but not IPython 4.



          The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py into a notebook test.ipynb.



          import IPython.nbformat.current as nbf
          nb = nbf.read(open('test.py', 'r'), 'py')
          nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')


          Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):



          https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py



          Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py from the IPython 3.2.1 release:



          https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py



          Basically you use special comments such as # <codecell> or # <markdowncell> to separate the individual cells. Look at the line.startswith statements in PyReader.to_notebook for a complete list.






          share|improve this answer























          • That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
            – alexis
            Apr 25 '14 at 14:05






          • 1




            Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
            – alexis
            Apr 25 '14 at 19:37








          • 2




            At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
            – LondonRob
            Jul 15 '15 at 20:53






          • 1




            @Alex see edited version of my answer.
            – CliffordVienna
            Jul 16 '15 at 7:54






          • 2




            @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
            – alexis
            Mar 1 '16 at 19:46


















          up vote
          27
          down vote













          Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (v4) API.



          Input format



          Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desired. Here's a sample input file (original documentation here). The first two lines are ignored, and optional. (In fact, the reader will ignore coding: and <nbformat> lines anywhere in the file.)



          # -*- coding: utf-8 -*-
          # <nbformat>3.0</nbformat>

          # <markdowncell>

          # The simplest notebook. Markdown cells are embedded in comments,
          # so the file is a valid `python` script.
          # Be sure to **leave a space** after the comment character!

          # <codecell>

          print("Hello, IPython")

          # <rawcell>

          # Raw cell contents are not formatted as markdown


          (The API also accepts the obsolete directives <htmlcell> and <headingcell level=...>, which are immediately transformed to other types.)



          How to import it



          For some reason, this format is not supported by version 4 of the Notebook API. It's still a nice format, so it's worth the trouble to support it by importing into version 3 and upgrading. In principle it's just two lines of code, plus i/o:



          from IPython.nbformat import v3, v4

          with open("input-file.py") as fpin:
          text = fpin.read()

          nbook = v3.reads_py(text)
          nbook = v4.upgrade(nbook) # Upgrade v3 to v4

          jsonform = v4.writes(nbook) + "n"
          with open("output-file.ipynb", "w") as fpout:
          fpout.write(jsonform)


          But not so fast! In fact, the notebook API has a nasty bug: If the last cell in the input is a markdown cell, v3.reads_py() will lose it. The simplest work-around is to tack on a bogus <markdown> cell at the end: The bug will delete it, and everyone is happy. So do the following before you pass text to v3.reads_py():



          text += """
          # <markdowncell>

          # If you can read this, reads_py() is no longer broken!
          """





          share|improve this answer



















          • 3




            Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
            – John Smith
            Mar 3 '16 at 14:39












          • Oops! Yeah indeed it's 2016 :-)
            – alexis
            Mar 3 '16 at 15:04










          • Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
            – John Smith
            Mar 3 '16 at 15:21










          • Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
            – John Smith
            Mar 3 '16 at 15:24










          • Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
            – alexis
            Mar 3 '16 at 15:26


















          up vote
          8
          down vote













          Python code example how to build IPython notebook V4:



          # -*- coding: utf-8 -*-
          import os
          from base64 import encodestring

          from IPython.nbformat.v4.nbbase import (
          new_code_cell, new_markdown_cell, new_notebook,
          new_output, new_raw_cell
          )

          # some random base64-encoded *text*
          png = encodestring(os.urandom(5)).decode('ascii')
          jpeg = encodestring(os.urandom(6)).decode('ascii')

          cells =
          cells.append(new_markdown_cell(
          source='Some NumPy Examples',
          ))


          cells.append(new_code_cell(
          source='import numpy',
          execution_count=1,
          ))

          cells.append(new_markdown_cell(
          source='A random array',
          ))

          cells.append(new_raw_cell(
          source='A random array',
          ))

          cells.append(new_markdown_cell(
          source=u'## My Heading',
          ))

          cells.append(new_code_cell(
          source='a = numpy.random.rand(100)',
          execution_count=2,
          ))
          cells.append(new_code_cell(
          source='a = 10nb = 5n',
          execution_count=3,
          ))
          cells.append(new_code_cell(
          source='a = 10nb = 5',
          execution_count=4,
          ))

          cells.append(new_code_cell(
          source=u'print "ünîcødé"',
          execution_count=3,
          outputs=[new_output(
          output_type=u'execute_result',
          data={
          'text/plain': u'<array a>',
          'text/html': u'The HTML rep',
          'text/latex': u'$a$',
          'image/png': png,
          'image/jpeg': jpeg,
          'image/svg+xml': u'<svg>',
          'application/json': {
          'key': 'value'
          },
          'application/javascript': u'var i=0;'
          },
          execution_count=3
          ),new_output(
          output_type=u'display_data',
          data={
          'text/plain': u'<array a>',
          'text/html': u'The HTML rep',
          'text/latex': u'$a$',
          'image/png': png,
          'image/jpeg': jpeg,
          'image/svg+xml': u'<svg>',
          'application/json': {
          'key': 'value'
          },
          'application/javascript': u'var i=0;'
          },
          ),new_output(
          output_type=u'error',
          ename=u'NameError',
          evalue=u'NameError was here',
          traceback=[u'frame 0', u'frame 1', u'frame 2']
          ),new_output(
          output_type=u'stream',
          text='foorbarrn'
          ),new_output(
          output_type=u'stream',
          name='stderr',
          text='rfoorbarn'
          )]
          ))

          nb0 = new_notebook(cells=cells,
          metadata={
          'language': 'python',
          }
          )

          import IPython.nbformat as nbf
          import codecs
          f = codecs.open('test.ipynb', encoding='utf-8', mode='w')
          nbf.write(nb0, f, 4)
          f.close()





          share|improve this answer























          • Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
            – alexis
            Oct 7 '15 at 15:15


















          up vote
          5
          down vote













          Given the example by Volodimir Kopey, I put together a bare-bones script to convert a .py obtained by exporting from a .ipynb back into a V4 .ipynb.



          I hacked this script together when I edited (in a proper IDE) a .py I had exported from a Notebook and I wanted to go back to Notebook to run it cell by cell.



          The script handles only code cells. The exported .py does not contain much else, anyway.



          import nbformat
          from nbformat.v4 import new_code_cell,new_notebook

          import codecs

          sourceFile = "changeMe.py" # <<<< change
          destFile = "changeMe.ipynb" # <<<< change


          def parsePy(fn):
          """ Generator that parses a .py file exported from a IPython notebook and
          extracts code cells (whatever is between occurrences of "In[*]:").
          Returns a string containing one or more lines
          """
          with open(fn,"r") as f:
          lines =
          for l in f:
          l1 = l.strip()
          if l1.startswith('# In[') and l1.endswith(']:') and lines:
          yield "".join(lines)
          lines =
          continue
          lines.append(l)
          if lines:
          yield "".join(lines)

          # Create the code cells by parsing the file in input
          cells =
          for c in parsePy(sourceFile):
          cells.append(new_code_cell(source=c))

          # This creates a V4 Notebook with the code cells extracted above
          nb0 = new_notebook(cells=cells,
          metadata={'language': 'python',})

          with codecs.open(destFile, encoding='utf-8', mode='w') as f:
          nbformat.write(nb0, f, 4)


          No guarantees, but it worked for me






          share|improve this answer























          • Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
            – alexis
            Oct 7 '15 at 15:09




















          up vote
          3
          down vote













          Took the liberty of taking and modifying the code of P.Toccateli and alexis so that it will also work with pycharm and spyder like cell markers and released it on github.






          share|improve this answer























          • Thanks. Should be useful for anyone working with these formats.
            – alexis
            Mar 3 '16 at 15:02


















          up vote
          2
          down vote













          I wrote an extension for vscode that might help. It converts the python files to ipython notebooks. It's in early stages so if any error occurs, feel free to submit an issue.



          Jupyter Notebook Converter






          share|improve this answer




























            up vote
            2
            down vote













            very old question, i know. but there is jupytext (also available on pypi) that can convert from ipynb to several formats and back.



            when jupytext is installed you can use



            $ jupytext --to notebook test.py


            in order to generate test.ipynb.



            jupytext has a lot more interesting features that can come in handy when working with notebooks.






            share|improve this answer





















            • Nice to know, thanks for the update! I'll check it out.
              – alexis
              Nov 20 at 9:37


















            up vote
            -1
            down vote













            You can use the script py2nb from https://github.com/sklam/py2nb



            You will have to use a certain syntax for your *.py but it's rather simple to use (look at the example in the 'samples' folder)






            share|improve this answer

















            • 2




              What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
              – alexis
              Mar 9 at 8:41













            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23292242%2fconverting-to-not-from-ipython-notebook-format%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            28
            down vote



            accepted










            The following works for IPython 3, but not IPython 4.



            The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py into a notebook test.ipynb.



            import IPython.nbformat.current as nbf
            nb = nbf.read(open('test.py', 'r'), 'py')
            nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')


            Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):



            https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py



            Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py from the IPython 3.2.1 release:



            https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py



            Basically you use special comments such as # <codecell> or # <markdowncell> to separate the individual cells. Look at the line.startswith statements in PyReader.to_notebook for a complete list.






            share|improve this answer























            • That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
              – alexis
              Apr 25 '14 at 14:05






            • 1




              Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
              – alexis
              Apr 25 '14 at 19:37








            • 2




              At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
              – LondonRob
              Jul 15 '15 at 20:53






            • 1




              @Alex see edited version of my answer.
              – CliffordVienna
              Jul 16 '15 at 7:54






            • 2




              @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
              – alexis
              Mar 1 '16 at 19:46















            up vote
            28
            down vote



            accepted










            The following works for IPython 3, but not IPython 4.



            The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py into a notebook test.ipynb.



            import IPython.nbformat.current as nbf
            nb = nbf.read(open('test.py', 'r'), 'py')
            nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')


            Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):



            https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py



            Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py from the IPython 3.2.1 release:



            https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py



            Basically you use special comments such as # <codecell> or # <markdowncell> to separate the individual cells. Look at the line.startswith statements in PyReader.to_notebook for a complete list.






            share|improve this answer























            • That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
              – alexis
              Apr 25 '14 at 14:05






            • 1




              Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
              – alexis
              Apr 25 '14 at 19:37








            • 2




              At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
              – LondonRob
              Jul 15 '15 at 20:53






            • 1




              @Alex see edited version of my answer.
              – CliffordVienna
              Jul 16 '15 at 7:54






            • 2




              @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
              – alexis
              Mar 1 '16 at 19:46













            up vote
            28
            down vote



            accepted







            up vote
            28
            down vote



            accepted






            The following works for IPython 3, but not IPython 4.



            The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py into a notebook test.ipynb.



            import IPython.nbformat.current as nbf
            nb = nbf.read(open('test.py', 'r'), 'py')
            nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')


            Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):



            https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py



            Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py from the IPython 3.2.1 release:



            https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py



            Basically you use special comments such as # <codecell> or # <markdowncell> to separate the individual cells. Look at the line.startswith statements in PyReader.to_notebook for a complete list.






            share|improve this answer














            The following works for IPython 3, but not IPython 4.



            The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py into a notebook test.ipynb.



            import IPython.nbformat.current as nbf
            nb = nbf.read(open('test.py', 'r'), 'py')
            nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')


            Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):



            https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py



            Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py from the IPython 3.2.1 release:



            https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py



            Basically you use special comments such as # <codecell> or # <markdowncell> to separate the individual cells. Look at the line.startswith statements in PyReader.to_notebook for a complete list.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 17 at 19:12









            Jean-François Corbett

            28.3k22107157




            28.3k22107157










            answered Apr 25 '14 at 12:08









            CliffordVienna

            5,4411936




            5,4411936












            • That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
              – alexis
              Apr 25 '14 at 14:05






            • 1




              Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
              – alexis
              Apr 25 '14 at 19:37








            • 2




              At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
              – LondonRob
              Jul 15 '15 at 20:53






            • 1




              @Alex see edited version of my answer.
              – CliffordVienna
              Jul 16 '15 at 7:54






            • 2




              @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
              – alexis
              Mar 1 '16 at 19:46


















            • That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
              – alexis
              Apr 25 '14 at 14:05






            • 1




              Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
              – alexis
              Apr 25 '14 at 19:37








            • 2




              At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
              – LondonRob
              Jul 15 '15 at 20:53






            • 1




              @Alex see edited version of my answer.
              – CliffordVienna
              Jul 16 '15 at 7:54






            • 2




              @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
              – alexis
              Mar 1 '16 at 19:46
















            That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
            – alexis
            Apr 25 '14 at 14:05




            That's good to know, thanks. I had no plans to generate JSON directly, but rather to generate python with the right directives and let notebook import it; your code makes it possible to do this automatically rather than manually. But the question remains: what notebook directives can the python script contain?
            – alexis
            Apr 25 '14 at 14:05




            1




            1




            Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
            – alexis
            Apr 25 '14 at 19:37






            Thanks! That and the sample .py file I linked to in my question seem like a sufficient reference. For completeness, the current directives are <nbformat> (3.0), <codecell>, <htmlcell>, <markdowncell>, <rawcell>, and <headincell level=N>. (I'm ignoring the deprecated <plaintextcell>.)
            – alexis
            Apr 25 '14 at 19:37






            2




            2




            At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
            – LondonRob
            Jul 15 '15 at 20:53




            At least on my installation, this import statement gives UserWarning: IPython.nbformat.current is deprecated.
            – LondonRob
            Jul 15 '15 at 20:53




            1




            1




            @Alex see edited version of my answer.
            – CliffordVienna
            Jul 16 '15 at 7:54




            @Alex see edited version of my answer.
            – CliffordVienna
            Jul 16 '15 at 7:54




            2




            2




            @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
            – alexis
            Mar 1 '16 at 19:46




            @Alex, I have added a self-answer showing how to import notebooks and save them in v4 format immediately. (Also how to get around a nasty bug...)
            – alexis
            Mar 1 '16 at 19:46












            up vote
            27
            down vote













            Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (v4) API.



            Input format



            Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desired. Here's a sample input file (original documentation here). The first two lines are ignored, and optional. (In fact, the reader will ignore coding: and <nbformat> lines anywhere in the file.)



            # -*- coding: utf-8 -*-
            # <nbformat>3.0</nbformat>

            # <markdowncell>

            # The simplest notebook. Markdown cells are embedded in comments,
            # so the file is a valid `python` script.
            # Be sure to **leave a space** after the comment character!

            # <codecell>

            print("Hello, IPython")

            # <rawcell>

            # Raw cell contents are not formatted as markdown


            (The API also accepts the obsolete directives <htmlcell> and <headingcell level=...>, which are immediately transformed to other types.)



            How to import it



            For some reason, this format is not supported by version 4 of the Notebook API. It's still a nice format, so it's worth the trouble to support it by importing into version 3 and upgrading. In principle it's just two lines of code, plus i/o:



            from IPython.nbformat import v3, v4

            with open("input-file.py") as fpin:
            text = fpin.read()

            nbook = v3.reads_py(text)
            nbook = v4.upgrade(nbook) # Upgrade v3 to v4

            jsonform = v4.writes(nbook) + "n"
            with open("output-file.ipynb", "w") as fpout:
            fpout.write(jsonform)


            But not so fast! In fact, the notebook API has a nasty bug: If the last cell in the input is a markdown cell, v3.reads_py() will lose it. The simplest work-around is to tack on a bogus <markdown> cell at the end: The bug will delete it, and everyone is happy. So do the following before you pass text to v3.reads_py():



            text += """
            # <markdowncell>

            # If you can read this, reads_py() is no longer broken!
            """





            share|improve this answer



















            • 3




              Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
              – John Smith
              Mar 3 '16 at 14:39












            • Oops! Yeah indeed it's 2016 :-)
              – alexis
              Mar 3 '16 at 15:04










            • Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
              – John Smith
              Mar 3 '16 at 15:21










            • Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
              – John Smith
              Mar 3 '16 at 15:24










            • Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
              – alexis
              Mar 3 '16 at 15:26















            up vote
            27
            down vote













            Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (v4) API.



            Input format



            Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desired. Here's a sample input file (original documentation here). The first two lines are ignored, and optional. (In fact, the reader will ignore coding: and <nbformat> lines anywhere in the file.)



            # -*- coding: utf-8 -*-
            # <nbformat>3.0</nbformat>

            # <markdowncell>

            # The simplest notebook. Markdown cells are embedded in comments,
            # so the file is a valid `python` script.
            # Be sure to **leave a space** after the comment character!

            # <codecell>

            print("Hello, IPython")

            # <rawcell>

            # Raw cell contents are not formatted as markdown


            (The API also accepts the obsolete directives <htmlcell> and <headingcell level=...>, which are immediately transformed to other types.)



            How to import it



            For some reason, this format is not supported by version 4 of the Notebook API. It's still a nice format, so it's worth the trouble to support it by importing into version 3 and upgrading. In principle it's just two lines of code, plus i/o:



            from IPython.nbformat import v3, v4

            with open("input-file.py") as fpin:
            text = fpin.read()

            nbook = v3.reads_py(text)
            nbook = v4.upgrade(nbook) # Upgrade v3 to v4

            jsonform = v4.writes(nbook) + "n"
            with open("output-file.ipynb", "w") as fpout:
            fpout.write(jsonform)


            But not so fast! In fact, the notebook API has a nasty bug: If the last cell in the input is a markdown cell, v3.reads_py() will lose it. The simplest work-around is to tack on a bogus <markdown> cell at the end: The bug will delete it, and everyone is happy. So do the following before you pass text to v3.reads_py():



            text += """
            # <markdowncell>

            # If you can read this, reads_py() is no longer broken!
            """





            share|improve this answer



















            • 3




              Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
              – John Smith
              Mar 3 '16 at 14:39












            • Oops! Yeah indeed it's 2016 :-)
              – alexis
              Mar 3 '16 at 15:04










            • Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
              – John Smith
              Mar 3 '16 at 15:21










            • Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
              – John Smith
              Mar 3 '16 at 15:24










            • Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
              – alexis
              Mar 3 '16 at 15:26













            up vote
            27
            down vote










            up vote
            27
            down vote









            Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (v4) API.



            Input format



            Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desired. Here's a sample input file (original documentation here). The first two lines are ignored, and optional. (In fact, the reader will ignore coding: and <nbformat> lines anywhere in the file.)



            # -*- coding: utf-8 -*-
            # <nbformat>3.0</nbformat>

            # <markdowncell>

            # The simplest notebook. Markdown cells are embedded in comments,
            # so the file is a valid `python` script.
            # Be sure to **leave a space** after the comment character!

            # <codecell>

            print("Hello, IPython")

            # <rawcell>

            # Raw cell contents are not formatted as markdown


            (The API also accepts the obsolete directives <htmlcell> and <headingcell level=...>, which are immediately transformed to other types.)



            How to import it



            For some reason, this format is not supported by version 4 of the Notebook API. It's still a nice format, so it's worth the trouble to support it by importing into version 3 and upgrading. In principle it's just two lines of code, plus i/o:



            from IPython.nbformat import v3, v4

            with open("input-file.py") as fpin:
            text = fpin.read()

            nbook = v3.reads_py(text)
            nbook = v4.upgrade(nbook) # Upgrade v3 to v4

            jsonform = v4.writes(nbook) + "n"
            with open("output-file.ipynb", "w") as fpout:
            fpout.write(jsonform)


            But not so fast! In fact, the notebook API has a nasty bug: If the last cell in the input is a markdown cell, v3.reads_py() will lose it. The simplest work-around is to tack on a bogus <markdown> cell at the end: The bug will delete it, and everyone is happy. So do the following before you pass text to v3.reads_py():



            text += """
            # <markdowncell>

            # If you can read this, reads_py() is no longer broken!
            """





            share|improve this answer














            Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (v4) API.



            Input format



            Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desired. Here's a sample input file (original documentation here). The first two lines are ignored, and optional. (In fact, the reader will ignore coding: and <nbformat> lines anywhere in the file.)



            # -*- coding: utf-8 -*-
            # <nbformat>3.0</nbformat>

            # <markdowncell>

            # The simplest notebook. Markdown cells are embedded in comments,
            # so the file is a valid `python` script.
            # Be sure to **leave a space** after the comment character!

            # <codecell>

            print("Hello, IPython")

            # <rawcell>

            # Raw cell contents are not formatted as markdown


            (The API also accepts the obsolete directives <htmlcell> and <headingcell level=...>, which are immediately transformed to other types.)



            How to import it



            For some reason, this format is not supported by version 4 of the Notebook API. It's still a nice format, so it's worth the trouble to support it by importing into version 3 and upgrading. In principle it's just two lines of code, plus i/o:



            from IPython.nbformat import v3, v4

            with open("input-file.py") as fpin:
            text = fpin.read()

            nbook = v3.reads_py(text)
            nbook = v4.upgrade(nbook) # Upgrade v3 to v4

            jsonform = v4.writes(nbook) + "n"
            with open("output-file.ipynb", "w") as fpout:
            fpout.write(jsonform)


            But not so fast! In fact, the notebook API has a nasty bug: If the last cell in the input is a markdown cell, v3.reads_py() will lose it. The simplest work-around is to tack on a bogus <markdown> cell at the end: The bug will delete it, and everyone is happy. So do the following before you pass text to v3.reads_py():



            text += """
            # <markdowncell>

            # If you can read this, reads_py() is no longer broken!
            """






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 3 '16 at 20:35

























            answered Mar 1 '16 at 10:08









            alexis

            33.3k954113




            33.3k954113








            • 3




              Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
              – John Smith
              Mar 3 '16 at 14:39












            • Oops! Yeah indeed it's 2016 :-)
              – alexis
              Mar 3 '16 at 15:04










            • Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
              – John Smith
              Mar 3 '16 at 15:21










            • Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
              – John Smith
              Mar 3 '16 at 15:24










            • Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
              – alexis
              Mar 3 '16 at 15:26














            • 3




              Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
              – John Smith
              Mar 3 '16 at 14:39












            • Oops! Yeah indeed it's 2016 :-)
              – alexis
              Mar 3 '16 at 15:04










            • Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
              – John Smith
              Mar 3 '16 at 15:21










            • Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
              – John Smith
              Mar 3 '16 at 15:24










            • Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
              – alexis
              Mar 3 '16 at 15:26








            3




            3




            Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
            – John Smith
            Mar 3 '16 at 14:39






            Nice. Check also this script I've written that works with spyder and pycharm cell markers plus some extra candies for slide making. PS: Might want to this to your edit (and i think you meant 2016) :)
            – John Smith
            Mar 3 '16 at 14:39














            Oops! Yeah indeed it's 2016 :-)
            – alexis
            Mar 3 '16 at 15:04




            Oops! Yeah indeed it's 2016 :-)
            – alexis
            Mar 3 '16 at 15:04












            Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
            – John Smith
            Mar 3 '16 at 15:21




            Hmm tried quickly your script above but getting an error message ValueError: dictionary update sequence element #0 has length 1; 2 is required. That is on the fpout.write statement.
            – John Smith
            Mar 3 '16 at 15:21












            Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
            – John Smith
            Mar 3 '16 at 15:24




            Using python 2.7.11 :: Anaconda 2.4.1 (x86_64), jupyter 4.0.6 and notebook 4.1.0. What about you?
            – John Smith
            Mar 3 '16 at 15:24












            Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
            – alexis
            Mar 3 '16 at 15:26




            Oops! I forgot a call to v4.writes(), which generates json. Fixed now, thanks for catching it!
            – alexis
            Mar 3 '16 at 15:26










            up vote
            8
            down vote













            Python code example how to build IPython notebook V4:



            # -*- coding: utf-8 -*-
            import os
            from base64 import encodestring

            from IPython.nbformat.v4.nbbase import (
            new_code_cell, new_markdown_cell, new_notebook,
            new_output, new_raw_cell
            )

            # some random base64-encoded *text*
            png = encodestring(os.urandom(5)).decode('ascii')
            jpeg = encodestring(os.urandom(6)).decode('ascii')

            cells =
            cells.append(new_markdown_cell(
            source='Some NumPy Examples',
            ))


            cells.append(new_code_cell(
            source='import numpy',
            execution_count=1,
            ))

            cells.append(new_markdown_cell(
            source='A random array',
            ))

            cells.append(new_raw_cell(
            source='A random array',
            ))

            cells.append(new_markdown_cell(
            source=u'## My Heading',
            ))

            cells.append(new_code_cell(
            source='a = numpy.random.rand(100)',
            execution_count=2,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5n',
            execution_count=3,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5',
            execution_count=4,
            ))

            cells.append(new_code_cell(
            source=u'print "ünîcødé"',
            execution_count=3,
            outputs=[new_output(
            output_type=u'execute_result',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            execution_count=3
            ),new_output(
            output_type=u'display_data',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            ),new_output(
            output_type=u'error',
            ename=u'NameError',
            evalue=u'NameError was here',
            traceback=[u'frame 0', u'frame 1', u'frame 2']
            ),new_output(
            output_type=u'stream',
            text='foorbarrn'
            ),new_output(
            output_type=u'stream',
            name='stderr',
            text='rfoorbarn'
            )]
            ))

            nb0 = new_notebook(cells=cells,
            metadata={
            'language': 'python',
            }
            )

            import IPython.nbformat as nbf
            import codecs
            f = codecs.open('test.ipynb', encoding='utf-8', mode='w')
            nbf.write(nb0, f, 4)
            f.close()





            share|improve this answer























            • Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
              – alexis
              Oct 7 '15 at 15:15















            up vote
            8
            down vote













            Python code example how to build IPython notebook V4:



            # -*- coding: utf-8 -*-
            import os
            from base64 import encodestring

            from IPython.nbformat.v4.nbbase import (
            new_code_cell, new_markdown_cell, new_notebook,
            new_output, new_raw_cell
            )

            # some random base64-encoded *text*
            png = encodestring(os.urandom(5)).decode('ascii')
            jpeg = encodestring(os.urandom(6)).decode('ascii')

            cells =
            cells.append(new_markdown_cell(
            source='Some NumPy Examples',
            ))


            cells.append(new_code_cell(
            source='import numpy',
            execution_count=1,
            ))

            cells.append(new_markdown_cell(
            source='A random array',
            ))

            cells.append(new_raw_cell(
            source='A random array',
            ))

            cells.append(new_markdown_cell(
            source=u'## My Heading',
            ))

            cells.append(new_code_cell(
            source='a = numpy.random.rand(100)',
            execution_count=2,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5n',
            execution_count=3,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5',
            execution_count=4,
            ))

            cells.append(new_code_cell(
            source=u'print "ünîcødé"',
            execution_count=3,
            outputs=[new_output(
            output_type=u'execute_result',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            execution_count=3
            ),new_output(
            output_type=u'display_data',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            ),new_output(
            output_type=u'error',
            ename=u'NameError',
            evalue=u'NameError was here',
            traceback=[u'frame 0', u'frame 1', u'frame 2']
            ),new_output(
            output_type=u'stream',
            text='foorbarrn'
            ),new_output(
            output_type=u'stream',
            name='stderr',
            text='rfoorbarn'
            )]
            ))

            nb0 = new_notebook(cells=cells,
            metadata={
            'language': 'python',
            }
            )

            import IPython.nbformat as nbf
            import codecs
            f = codecs.open('test.ipynb', encoding='utf-8', mode='w')
            nbf.write(nb0, f, 4)
            f.close()





            share|improve this answer























            • Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
              – alexis
              Oct 7 '15 at 15:15













            up vote
            8
            down vote










            up vote
            8
            down vote









            Python code example how to build IPython notebook V4:



            # -*- coding: utf-8 -*-
            import os
            from base64 import encodestring

            from IPython.nbformat.v4.nbbase import (
            new_code_cell, new_markdown_cell, new_notebook,
            new_output, new_raw_cell
            )

            # some random base64-encoded *text*
            png = encodestring(os.urandom(5)).decode('ascii')
            jpeg = encodestring(os.urandom(6)).decode('ascii')

            cells =
            cells.append(new_markdown_cell(
            source='Some NumPy Examples',
            ))


            cells.append(new_code_cell(
            source='import numpy',
            execution_count=1,
            ))

            cells.append(new_markdown_cell(
            source='A random array',
            ))

            cells.append(new_raw_cell(
            source='A random array',
            ))

            cells.append(new_markdown_cell(
            source=u'## My Heading',
            ))

            cells.append(new_code_cell(
            source='a = numpy.random.rand(100)',
            execution_count=2,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5n',
            execution_count=3,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5',
            execution_count=4,
            ))

            cells.append(new_code_cell(
            source=u'print "ünîcødé"',
            execution_count=3,
            outputs=[new_output(
            output_type=u'execute_result',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            execution_count=3
            ),new_output(
            output_type=u'display_data',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            ),new_output(
            output_type=u'error',
            ename=u'NameError',
            evalue=u'NameError was here',
            traceback=[u'frame 0', u'frame 1', u'frame 2']
            ),new_output(
            output_type=u'stream',
            text='foorbarrn'
            ),new_output(
            output_type=u'stream',
            name='stderr',
            text='rfoorbarn'
            )]
            ))

            nb0 = new_notebook(cells=cells,
            metadata={
            'language': 'python',
            }
            )

            import IPython.nbformat as nbf
            import codecs
            f = codecs.open('test.ipynb', encoding='utf-8', mode='w')
            nbf.write(nb0, f, 4)
            f.close()





            share|improve this answer














            Python code example how to build IPython notebook V4:



            # -*- coding: utf-8 -*-
            import os
            from base64 import encodestring

            from IPython.nbformat.v4.nbbase import (
            new_code_cell, new_markdown_cell, new_notebook,
            new_output, new_raw_cell
            )

            # some random base64-encoded *text*
            png = encodestring(os.urandom(5)).decode('ascii')
            jpeg = encodestring(os.urandom(6)).decode('ascii')

            cells =
            cells.append(new_markdown_cell(
            source='Some NumPy Examples',
            ))


            cells.append(new_code_cell(
            source='import numpy',
            execution_count=1,
            ))

            cells.append(new_markdown_cell(
            source='A random array',
            ))

            cells.append(new_raw_cell(
            source='A random array',
            ))

            cells.append(new_markdown_cell(
            source=u'## My Heading',
            ))

            cells.append(new_code_cell(
            source='a = numpy.random.rand(100)',
            execution_count=2,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5n',
            execution_count=3,
            ))
            cells.append(new_code_cell(
            source='a = 10nb = 5',
            execution_count=4,
            ))

            cells.append(new_code_cell(
            source=u'print "ünîcødé"',
            execution_count=3,
            outputs=[new_output(
            output_type=u'execute_result',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            execution_count=3
            ),new_output(
            output_type=u'display_data',
            data={
            'text/plain': u'<array a>',
            'text/html': u'The HTML rep',
            'text/latex': u'$a$',
            'image/png': png,
            'image/jpeg': jpeg,
            'image/svg+xml': u'<svg>',
            'application/json': {
            'key': 'value'
            },
            'application/javascript': u'var i=0;'
            },
            ),new_output(
            output_type=u'error',
            ename=u'NameError',
            evalue=u'NameError was here',
            traceback=[u'frame 0', u'frame 1', u'frame 2']
            ),new_output(
            output_type=u'stream',
            text='foorbarrn'
            ),new_output(
            output_type=u'stream',
            name='stderr',
            text='rfoorbarn'
            )]
            ))

            nb0 = new_notebook(cells=cells,
            metadata={
            'language': 'python',
            }
            )

            import IPython.nbformat as nbf
            import codecs
            f = codecs.open('test.ipynb', encoding='utf-8', mode='w')
            nbf.write(nb0, f, 4)
            f.close()






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 26 '15 at 18:56

























            answered Jul 26 '15 at 17:21









            Volodimir Kopey

            410410




            410410












            • Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
              – alexis
              Oct 7 '15 at 15:15


















            • Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
              – alexis
              Oct 7 '15 at 15:15
















            Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
            – alexis
            Oct 7 '15 at 15:15




            Thanks for the effort. It doesn't really fit the question (importing a file), but it could be useful to other aspiring notebook hackers.
            – alexis
            Oct 7 '15 at 15:15










            up vote
            5
            down vote













            Given the example by Volodimir Kopey, I put together a bare-bones script to convert a .py obtained by exporting from a .ipynb back into a V4 .ipynb.



            I hacked this script together when I edited (in a proper IDE) a .py I had exported from a Notebook and I wanted to go back to Notebook to run it cell by cell.



            The script handles only code cells. The exported .py does not contain much else, anyway.



            import nbformat
            from nbformat.v4 import new_code_cell,new_notebook

            import codecs

            sourceFile = "changeMe.py" # <<<< change
            destFile = "changeMe.ipynb" # <<<< change


            def parsePy(fn):
            """ Generator that parses a .py file exported from a IPython notebook and
            extracts code cells (whatever is between occurrences of "In[*]:").
            Returns a string containing one or more lines
            """
            with open(fn,"r") as f:
            lines =
            for l in f:
            l1 = l.strip()
            if l1.startswith('# In[') and l1.endswith(']:') and lines:
            yield "".join(lines)
            lines =
            continue
            lines.append(l)
            if lines:
            yield "".join(lines)

            # Create the code cells by parsing the file in input
            cells =
            for c in parsePy(sourceFile):
            cells.append(new_code_cell(source=c))

            # This creates a V4 Notebook with the code cells extracted above
            nb0 = new_notebook(cells=cells,
            metadata={'language': 'python',})

            with codecs.open(destFile, encoding='utf-8', mode='w') as f:
            nbformat.write(nb0, f, 4)


            No guarantees, but it worked for me






            share|improve this answer























            • Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
              – alexis
              Oct 7 '15 at 15:09

















            up vote
            5
            down vote













            Given the example by Volodimir Kopey, I put together a bare-bones script to convert a .py obtained by exporting from a .ipynb back into a V4 .ipynb.



            I hacked this script together when I edited (in a proper IDE) a .py I had exported from a Notebook and I wanted to go back to Notebook to run it cell by cell.



            The script handles only code cells. The exported .py does not contain much else, anyway.



            import nbformat
            from nbformat.v4 import new_code_cell,new_notebook

            import codecs

            sourceFile = "changeMe.py" # <<<< change
            destFile = "changeMe.ipynb" # <<<< change


            def parsePy(fn):
            """ Generator that parses a .py file exported from a IPython notebook and
            extracts code cells (whatever is between occurrences of "In[*]:").
            Returns a string containing one or more lines
            """
            with open(fn,"r") as f:
            lines =
            for l in f:
            l1 = l.strip()
            if l1.startswith('# In[') and l1.endswith(']:') and lines:
            yield "".join(lines)
            lines =
            continue
            lines.append(l)
            if lines:
            yield "".join(lines)

            # Create the code cells by parsing the file in input
            cells =
            for c in parsePy(sourceFile):
            cells.append(new_code_cell(source=c))

            # This creates a V4 Notebook with the code cells extracted above
            nb0 = new_notebook(cells=cells,
            metadata={'language': 'python',})

            with codecs.open(destFile, encoding='utf-8', mode='w') as f:
            nbformat.write(nb0, f, 4)


            No guarantees, but it worked for me






            share|improve this answer























            • Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
              – alexis
              Oct 7 '15 at 15:09















            up vote
            5
            down vote










            up vote
            5
            down vote









            Given the example by Volodimir Kopey, I put together a bare-bones script to convert a .py obtained by exporting from a .ipynb back into a V4 .ipynb.



            I hacked this script together when I edited (in a proper IDE) a .py I had exported from a Notebook and I wanted to go back to Notebook to run it cell by cell.



            The script handles only code cells. The exported .py does not contain much else, anyway.



            import nbformat
            from nbformat.v4 import new_code_cell,new_notebook

            import codecs

            sourceFile = "changeMe.py" # <<<< change
            destFile = "changeMe.ipynb" # <<<< change


            def parsePy(fn):
            """ Generator that parses a .py file exported from a IPython notebook and
            extracts code cells (whatever is between occurrences of "In[*]:").
            Returns a string containing one or more lines
            """
            with open(fn,"r") as f:
            lines =
            for l in f:
            l1 = l.strip()
            if l1.startswith('# In[') and l1.endswith(']:') and lines:
            yield "".join(lines)
            lines =
            continue
            lines.append(l)
            if lines:
            yield "".join(lines)

            # Create the code cells by parsing the file in input
            cells =
            for c in parsePy(sourceFile):
            cells.append(new_code_cell(source=c))

            # This creates a V4 Notebook with the code cells extracted above
            nb0 = new_notebook(cells=cells,
            metadata={'language': 'python',})

            with codecs.open(destFile, encoding='utf-8', mode='w') as f:
            nbformat.write(nb0, f, 4)


            No guarantees, but it worked for me






            share|improve this answer














            Given the example by Volodimir Kopey, I put together a bare-bones script to convert a .py obtained by exporting from a .ipynb back into a V4 .ipynb.



            I hacked this script together when I edited (in a proper IDE) a .py I had exported from a Notebook and I wanted to go back to Notebook to run it cell by cell.



            The script handles only code cells. The exported .py does not contain much else, anyway.



            import nbformat
            from nbformat.v4 import new_code_cell,new_notebook

            import codecs

            sourceFile = "changeMe.py" # <<<< change
            destFile = "changeMe.ipynb" # <<<< change


            def parsePy(fn):
            """ Generator that parses a .py file exported from a IPython notebook and
            extracts code cells (whatever is between occurrences of "In[*]:").
            Returns a string containing one or more lines
            """
            with open(fn,"r") as f:
            lines =
            for l in f:
            l1 = l.strip()
            if l1.startswith('# In[') and l1.endswith(']:') and lines:
            yield "".join(lines)
            lines =
            continue
            lines.append(l)
            if lines:
            yield "".join(lines)

            # Create the code cells by parsing the file in input
            cells =
            for c in parsePy(sourceFile):
            cells.append(new_code_cell(source=c))

            # This creates a V4 Notebook with the code cells extracted above
            nb0 = new_notebook(cells=cells,
            metadata={'language': 'python',})

            with codecs.open(destFile, encoding='utf-8', mode='w') as f:
            nbformat.write(nb0, f, 4)


            No guarantees, but it worked for me







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 10 '15 at 10:21

























            answered Oct 7 '15 at 13:56









            P.Toccaceli

            15114




            15114












            • Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
              – alexis
              Oct 7 '15 at 15:09




















            • Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
              – alexis
              Oct 7 '15 at 15:09


















            Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
            – alexis
            Oct 7 '15 at 15:09






            Thanks! I already have a whole toolchain using the # <...cell> format, but your solution could be useful to others-- especially since your format is generated when Notebook exports. Could you document it better (parsePy returns lists of lines? One per cell? How can you tell markup from code cells?) and add a sample input file to the answer text?
            – alexis
            Oct 7 '15 at 15:09












            up vote
            3
            down vote













            Took the liberty of taking and modifying the code of P.Toccateli and alexis so that it will also work with pycharm and spyder like cell markers and released it on github.






            share|improve this answer























            • Thanks. Should be useful for anyone working with these formats.
              – alexis
              Mar 3 '16 at 15:02















            up vote
            3
            down vote













            Took the liberty of taking and modifying the code of P.Toccateli and alexis so that it will also work with pycharm and spyder like cell markers and released it on github.






            share|improve this answer























            • Thanks. Should be useful for anyone working with these formats.
              – alexis
              Mar 3 '16 at 15:02













            up vote
            3
            down vote










            up vote
            3
            down vote









            Took the liberty of taking and modifying the code of P.Toccateli and alexis so that it will also work with pycharm and spyder like cell markers and released it on github.






            share|improve this answer














            Took the liberty of taking and modifying the code of P.Toccateli and alexis so that it will also work with pycharm and spyder like cell markers and released it on github.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 4 '16 at 14:47

























            answered Feb 23 '16 at 12:08









            John Smith

            781318




            781318












            • Thanks. Should be useful for anyone working with these formats.
              – alexis
              Mar 3 '16 at 15:02


















            • Thanks. Should be useful for anyone working with these formats.
              – alexis
              Mar 3 '16 at 15:02
















            Thanks. Should be useful for anyone working with these formats.
            – alexis
            Mar 3 '16 at 15:02




            Thanks. Should be useful for anyone working with these formats.
            – alexis
            Mar 3 '16 at 15:02










            up vote
            2
            down vote













            I wrote an extension for vscode that might help. It converts the python files to ipython notebooks. It's in early stages so if any error occurs, feel free to submit an issue.



            Jupyter Notebook Converter






            share|improve this answer

























              up vote
              2
              down vote













              I wrote an extension for vscode that might help. It converts the python files to ipython notebooks. It's in early stages so if any error occurs, feel free to submit an issue.



              Jupyter Notebook Converter






              share|improve this answer























                up vote
                2
                down vote










                up vote
                2
                down vote









                I wrote an extension for vscode that might help. It converts the python files to ipython notebooks. It's in early stages so if any error occurs, feel free to submit an issue.



                Jupyter Notebook Converter






                share|improve this answer












                I wrote an extension for vscode that might help. It converts the python files to ipython notebooks. It's in early stages so if any error occurs, feel free to submit an issue.



                Jupyter Notebook Converter







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 27 at 17:05









                YigitOzgumus

                211




                211






















                    up vote
                    2
                    down vote













                    very old question, i know. but there is jupytext (also available on pypi) that can convert from ipynb to several formats and back.



                    when jupytext is installed you can use



                    $ jupytext --to notebook test.py


                    in order to generate test.ipynb.



                    jupytext has a lot more interesting features that can come in handy when working with notebooks.






                    share|improve this answer





















                    • Nice to know, thanks for the update! I'll check it out.
                      – alexis
                      Nov 20 at 9:37















                    up vote
                    2
                    down vote













                    very old question, i know. but there is jupytext (also available on pypi) that can convert from ipynb to several formats and back.



                    when jupytext is installed you can use



                    $ jupytext --to notebook test.py


                    in order to generate test.ipynb.



                    jupytext has a lot more interesting features that can come in handy when working with notebooks.






                    share|improve this answer





















                    • Nice to know, thanks for the update! I'll check it out.
                      – alexis
                      Nov 20 at 9:37













                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    very old question, i know. but there is jupytext (also available on pypi) that can convert from ipynb to several formats and back.



                    when jupytext is installed you can use



                    $ jupytext --to notebook test.py


                    in order to generate test.ipynb.



                    jupytext has a lot more interesting features that can come in handy when working with notebooks.






                    share|improve this answer












                    very old question, i know. but there is jupytext (also available on pypi) that can convert from ipynb to several formats and back.



                    when jupytext is installed you can use



                    $ jupytext --to notebook test.py


                    in order to generate test.ipynb.



                    jupytext has a lot more interesting features that can come in handy when working with notebooks.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 20 at 7:09









                    hiro protagonist

                    18k63760




                    18k63760












                    • Nice to know, thanks for the update! I'll check it out.
                      – alexis
                      Nov 20 at 9:37


















                    • Nice to know, thanks for the update! I'll check it out.
                      – alexis
                      Nov 20 at 9:37
















                    Nice to know, thanks for the update! I'll check it out.
                    – alexis
                    Nov 20 at 9:37




                    Nice to know, thanks for the update! I'll check it out.
                    – alexis
                    Nov 20 at 9:37










                    up vote
                    -1
                    down vote













                    You can use the script py2nb from https://github.com/sklam/py2nb



                    You will have to use a certain syntax for your *.py but it's rather simple to use (look at the example in the 'samples' folder)






                    share|improve this answer

















                    • 2




                      What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
                      – alexis
                      Mar 9 at 8:41

















                    up vote
                    -1
                    down vote













                    You can use the script py2nb from https://github.com/sklam/py2nb



                    You will have to use a certain syntax for your *.py but it's rather simple to use (look at the example in the 'samples' folder)






                    share|improve this answer

















                    • 2




                      What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
                      – alexis
                      Mar 9 at 8:41















                    up vote
                    -1
                    down vote










                    up vote
                    -1
                    down vote









                    You can use the script py2nb from https://github.com/sklam/py2nb



                    You will have to use a certain syntax for your *.py but it's rather simple to use (look at the example in the 'samples' folder)






                    share|improve this answer












                    You can use the script py2nb from https://github.com/sklam/py2nb



                    You will have to use a certain syntax for your *.py but it's rather simple to use (look at the example in the 'samples' folder)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 8 at 11:18









                    valbarriere

                    11




                    11








                    • 2




                      What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
                      – alexis
                      Mar 9 at 8:41
















                    • 2




                      What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
                      – alexis
                      Mar 9 at 8:41










                    2




                    2




                    What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
                    – alexis
                    Mar 9 at 8:41






                    What would be the benefit of this ad hoc solution (with an ad hoc format and unknown bugs and limitations), instead of the format supported by notebook itself?
                    – alexis
                    Mar 9 at 8:41




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23292242%2fconverting-to-not-from-ipython-notebook-format%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python