--- title: export: nb2py keywords: fastai sidebar: home_sidebar summary: "Code that allows you to export a notebook (.ipynb) as a python script( .py) to a target folder." description: "Code that allows you to export a notebook (.ipynb) as a python script( .py) to a target folder." nb_path: "nbs/000_export.ipynb" ---
{% raw %}
{% endraw %}

nb2py will allow you to convert the notebook (.ipynb) where the function is executed to a python script.

The conversion applies these rules:

  • The notebook will be automatically saved when the function is executed.
  • Only code cells will be converted (not markdown cells).
  • A header will be added to indicate the script has been automatically generated. It also indicates where the original ipynb is.
  • Cells with a #hide flag won't be converted. Flag variants like # hide, #Hide, #HIDE, ... are also acceptable.
  • Empty cells and unnecessary empty lines within cells will be removed.
  • By default the script will be created with the same name and in the same folder of the original notebook. But you can pass a dir folder and a different name if you wish.
  • If a script with the same name already exists, it will be overwriten.
{% raw %}
{% endraw %}

This code is required to identify flags in the notebook. We are looking for #hide flags.

{% raw %}

maybe_mount_gdrive[source]

maybe_mount_gdrive()

{% endraw %} {% raw %}
{% endraw %} {% raw %}
{% endraw %}

This code automatically gets the name of the notebook. It's been tested to work on Jupyter notebooks, Jupyter Lab and Google Colab.

{% raw %}

get_nb_name[source]

get_nb_name()

Returns the short name of the notebook w/o the .ipynb extension, or raises a FileNotFoundError exception if it cannot be determined.

{% endraw %} {% raw %}

get_colab_nb_name[source]

get_colab_nb_name()

{% endraw %} {% raw %}

get_nb_path[source]

get_nb_path()

Returns the absolute path of the notebook, or raises a FileNotFoundError exception if it cannot be determined.

{% endraw %} {% raw %}

nb_name_to_py[source]

nb_name_to_py(nb_name)

{% endraw %} {% raw %}

get_script_path[source]

get_script_path(nb_name=None)

{% endraw %} {% raw %}
{% endraw %}

This code is used when trying to save a file to google drive. We first need to mount the drive.

{% raw %}

nb2py[source]

nb2py(nb:"absolute or relative full path to the notebook you want to convert to a python script"=None, folder:"absolute or relative path to folder of the script you will create. Defaults to current nb's directory"=None, name:"name of the script you want to create. Defaults to current nb name .ipynb by .py"=None, save:"saves the nb before converting it to a script"=True, run:"import and run the script"=False, verbose:"controls verbosity"=True)

Converts a notebook to a python script in a predefined folder.

{% endraw %} {% raw %}
{% endraw %}