Как конвертировать IPython Notebook в файл Python с помощью командной строки?



Я смотрю на использование *.ipynb файлы как источник истины и программно "компилировать" их в файлы .py для запланированных заданий/задач.



единственный способ, который я понимаю, чтобы сделать это через GUI. Есть ли способ сделать это через командную строку?

917   9  

9 ответов:

запустить ноутбук с --script флаг будет сохранить вместе с .ipynb при каждом сохранении. Взгляните на github / ipython / nbconvert который в настоящее время сливается с самим IPython, поэтому не ожидайте, что документ будет точным, а nbconvert будет работать из коробки, не работая немного. (./nbconvert ) на момент написания статьи, в [python, latex, markdown, full_html,...])

вы можете также (поскольку ipynb-это json), загрузите его, выполните цикл через него и eval кодовая ячейка в текущем пространстве имен. Вы найдете пример здесь и там в интернете или IPython wiki на github.

этот ответ слишком стар см. ответ @ williampli ниже.

если вы не хотите выводить скрипт Python каждый раз, когда вы сохраняете, или вы не хотите перезапускать ядро IPython:

на командная строка, вы можете использовать nbconvert:

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

как взломать, вы даже можете вызвать вышеуказанную команду на IPython ноутбук по предварительной записи ! (используется для любого аргумента командной строки). Внутри Блокнота:

!jupyter nbconvert --to script config_template.ipynb

до --to script был добавил параметр был --to python или --to=python, но это переименован в движении к языковой агностической записной книжке.

вот быстрый и грязный способ извлечь код из V3 или V4 ipynb без использования ipython. Он не проверяет типы ячеек и т. д.

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()

Если вы хотите конвертировать все *.ipynb файлы из текущего каталога в скрипт python, вы можете запустить команду следующим образом:

jupyter nbconvert --to script *.ipynb

следуя предыдущему примеру, но с новая версия nbformat lib:

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'))

вы можете сделать это из API 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)

последняя строка кода @ Spawnrider,

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

дает'TypeError: write() аргумент должен быть str, а не int'

fh.writelines(source) 

хотя работает.

для конвертации *.файлы формата ipynb в текущем каталоге для скриптов python рекурсивно:

for i in *.ipynb **/*.ipynb; do 
    echo "$i"
    jupyter nbconvert  "$i" "$i"
done

у меня была эта проблема, и я попытался найти решение в интернете. Хотя я нашел некоторые решения, у них все еще есть некоторые проблемы, например, раздражающий Untitled.txt автоматическое создание при запуске нового ноутбука от приборной панели.

Так что в конце концов я написал мое собственное решение:

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

чтобы использовать этот скрипт, вы можете добавить его в ~/.jupyter/jupyter_notebook_config.py :)

обратите внимание, что вам может потребоваться перезагрузить ноутбук / лабораторию jupyter для его работы.

Comments

    Ничего не найдено.