¿Cómo convierto un Notebook IPython en un archivo Python a través de la línea de comandos?


Estoy usando el *.los archivos ipynb como fuente de verdad y 'compilarlos' programáticamente en archivos .py para trabajos/tareas programados.

La única manera que entiendo para hacer esto es a través de la GUI. ¿Hay alguna forma de hacerlo a través de la línea de comandos?

Author: Cristian Ciupitu, 2013-06-13

9 answers

Iniciar notebook con --script la bandera guardará .py el archivo junto con .ipynb en cada guardado. Echa un vistazo a github/ipython/nbconvert que actualmente se está fusionando con IPython, así que no esperes que el documento sea preciso y nbconvert funcione fuera de la caja sin trabajar un poco. (./ nbconvert ) en el momento de escribir esto, in [python , latex, markdown, full_html,...])

También puede (como ipynb es json), cargarlo, bucle a través de él y eval codecell en el espacio de nombres actual. Encontrará ejemplos aquí y allá en Internet o IPython wiki en github.

Esta respuesta es demasiado vieja ver la respuesta de @williampli abajo.

 37
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-06 20:22:56

Si no desea generar un script Python cada vez que guarde, o no desea reiniciar el núcleo IPython:

En la línea de comandos , puede usar nbconvert:

$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb

Como un poco de truco, incluso puede llamar al comando anterior en un cuaderno IPython pre-pendiente ! (utilizado para cualquier argumento de línea de comandos). Dentro de un cuaderno:

!jupyter nbconvert --to script config_template.ipynb

Antes de que --to script se agregara , la opción era --to python o --to=python, pero era renombrado en el movimiento hacia un sistema de cuaderno agnóstico del lenguaje.

 230
Author: williampli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-09 16:59:25

Aquí hay una forma rápida y sucia de extraer el código de V3 o V4 ipynb sin usar ipython. No comprueba los tipos de células, etc.

import sys,json

f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w') #output.py
if j["nbformat"] >=4:
        for i,cell in enumerate(j["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["source"]:
                        of.write(line)
                of.write('\n\n')
else:
        for i,cell in enumerate(j["worksheets"][0]["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["input"]:
                        of.write(line)
                of.write('\n\n')

of.close()
 10
Author: Valentas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-11 09:10:20

Si desea convertir todos los archivos *.ipynb del directorio actual al script python, puede ejecutar el comando así:

jupyter nbconvert --to script *.ipynb
 9
Author: Břetislav Hájek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-22 12:07:28

Siguiendo el ejemplo anterior pero con la nueva versión lib de nbformat :

import nbformat
from nbconvert import PythonExporter

def convertNotebook(notebookPath, modulePath):

  with open(notebookPath) as fh:
    nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)

  exporter = PythonExporter()
  source, meta = exporter.from_notebook_node(nb)

  with open(modulePath, 'w+') as fh:
    fh.writelines(source.encode('utf-8'))
 7
Author: Spawnrider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-07 14:30:01

Puede hacer esto desde la API de IPython.

from IPython.nbformat import current as nbformat
from IPython.nbconvert import PythonExporter

filepath = 'path/to/my_notebook.ipynb'
export_path = 'path/to/my_notebook.py'

with open(filepath) as fh:
    nb = nbformat.reads_json(fh.read())

exporter = PythonExporter()

# source is a tuple of python source code
# meta contains metadata
source, meta = exporter.from_notebook_node(nb)

with open(export_path, 'w+') as fh:
    fh.writelines(source)
 4
Author: justanr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 07:40:18

La última línea de código de@Spawnrider,

fh.writelines(source.encode('utf-8'))

Da 'TypeError: write() el argumento debe ser str, no int'

fh.writelines(source) 

Funciona sin embargo.

 3
Author: BarryC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-18 05:43:03

Para convertir todos *.archivos de formato ipynb en el directorio actual a scripts python recursivamente:

for i in *.ipynb **/*.ipynb; do 
    echo "$i"
    jupyter nbconvert  "$i" "$i"
done
 2
Author: Don Smythe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-23 01:53:28

Tuve este problema y traté de encontrar la solución en línea. Aunque he encontrado algunas soluciones, todavía tienen algunos problemas, por ejemplo, la molesta Untitled.txt auto-creación cuando se inicia un nuevo cuaderno desde el tablero.

Así que finalmente escribí mi propia solución :

import io
import os
import re
from nbconvert.exporters.script import ScriptExporter
from notebook.utils import to_api_path


def script_post_save(model, os_path, contents_manager, **kwargs):
    """Save a copy of notebook to the corresponding language source script.

    For example, when you save a `foo.ipynb` file, a corresponding `foo.py`
    python script will also be saved in the same directory.

    However, existing config files I found online (including the one written in
    the official documentation), will also create an `Untitile.txt` file when
    you create a new notebook, even if you have not pressed the "save" button.
    This is annoying because we usually will rename the notebook with a more
    meaningful name later, and now we have to rename the generated script file,
    too!

    Therefore we make a change here to filter out the newly created notebooks
    by checking their names. For a notebook which has not been given a name,
    i.e., its name is `Untitled.*`, the corresponding source script will not be
    saved. Note that the behavior also applies even if you manually save an
    "Untitled" notebook. The rationale is that we usually do not want to save
    scripts with the useless "Untitled" names.
    """
    # only process for notebooks
    if model["type"] != "notebook":
        return

    script_exporter = ScriptExporter(parent=contents_manager)
    base, __ = os.path.splitext(os_path)

    # do nothing if the notebook name ends with `Untitled[0-9]*`
    regex = re.compile(r"Untitled[0-9]*$")
    if regex.search(base):
        return

    script, resources = script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')

    log = contents_manager.log
    log.info("Saving script at /%s",
             to_api_path(script_fname, contents_manager.root_dir))

    with io.open(script_fname, "w", encoding="utf-8") as f:
        f.write(script)

c.FileContentsManager.post_save_hook = script_post_save

Para usar este script, puede agregarlo a ~/.jupyter/jupyter_notebook_config.py :)

Tenga en cuenta que es posible que deba reiniciar el jupyter notebook / lab para que funcione.

 0
Author: Jiren Jin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-10 11:16:57