Skip to content
forked from sklam/py2nb

Python script to Jupyter notebook converter

Notifications You must be signed in to change notification settings

blueogive/py2nb

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PY2NB: Python To Notebook Converter

This is a small utility for turning python scripts into Jupyter notebooks and convert module-level multi-line (triple quoted) string literals into Markdown cells. It also converts the specialized comment strings (i.e., #%%) that Don Jayamanne's Jupyter Extension for Visual Studio Code interprets as cell breaks/divisions into cell breaks in the returned notebook.

Why?

I wanted a tool to create user examples that can be executed as normal python scripts so that they can be copy-and-pasted easily and can be rendered as notebook for better readability (e.g., nice styling, results embedded).

Also,

  • Notebooks are nice to look at but slow to write; and
  • They do not play well with version control.

Install

Install using pip:

pip install git+https://github.com/blueogive/py2nb.git

Alternatively, you can create a local clone of this repository and install from it:

git clone https://github.com/blueogive/py2nb.git
pip install py2nb/

Usage

To convert a python script into a notebook:

python -m py2nb input.py output.ipynb

Samples

See tests directory.

How It Works

Uses python tokenize (builtin tokenizer library) for tokenization. String literals with triple quote at column zero are converted into a comment token with special <markdowncell>, <rawcell> and <codecell> to feed into the Python importer in IPython version 3. The processed tokens are untokenized using the tokenize module so that untouched line looks exactly the same as the input.

The beginning of a Python code cells may be denoted with a comment string like this:

#%%

Triple-quoted comments are converted to Markdown cells:

"""
This comment will be converted to a Markdown cell.
"""

However, if the triple-quoted comment begins with the word Raw, the comment will be converted to a raw notebook cell:

"""Raw
// This Javascript will be placed into a Raw cell in the output notebook.
<script>
jQuery(document).ready(function($) {

$(window).load(function(){
$('#preloader').fadeOut('slow',function(){$(this).remove();});
});

});
</script>
"""

About

Python script to Jupyter notebook converter

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • HTML 93.0%
  • Python 4.9%
  • Jupyter Notebook 2.1%