Ich möchte die *. Ipynb -Dateien als Quelle der Wahrheit verwenden und sie programmgesteuert in .py-Dateien für geplante Jobs/Aufgaben 'kompilieren'.
Ich verstehe dies nur über die GUI. Gibt es eine Möglichkeit, dies über die Befehlszeile zu tun?
Wenn Sie nicht bei jedem Speichern ein Python Skript ausgeben möchten oder den IPython-Kernel nicht neu starten möchten:
In der Befehlszeile können Sie nbconvert
verwenden:
$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
Als kleiner Hack können Sie sogar den obigen Befehl in ein IPython-Notizbuch aufrufen, indem Sie !
(Wird für jedes Befehlszeilenargument verwendet). In einem Notizbuch:
!jupyter nbconvert --to script config_template.ipynb
Vor --to script
War hinzugefügt , die Option war --to python
Oder --to=python
, Aber es war mbenannt in Richtung a Sprachunabhängiges Notebook-System.
Wenn Sie alle *.ipynb
- Dateien aus dem aktuellen Verzeichnis in das Skript python) konvertieren möchten, können Sie den Befehl folgendermaßen ausführen:
jupyter nbconvert --to script *.ipynb
Hier ist eine schnelle und unkonventionelle Möglichkeit, den Code aus V3 oder V4 ipynb zu extrahieren, ohne ipython zu verwenden. Es werden keine Zelltypen usw. überprüft.
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()
Nach dem vorherigen Beispiel aber mit dem neue Version von 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'))
@ Spawnriders letzte Codezeile,
fh.writelines(source.encode('utf-8'))
gibt 'TypeError: write () Argument muss str sein, nicht int'
fh.writelines(source)
funktioniert aber.
Sie können dies über die IPython-API tun.
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)
Zum rekursiven Konvertieren aller Dateien im * .ipynb-Format im aktuellen Verzeichnis in python scripts:
for i in *.ipynb **/*.ipynb; do
echo "$i"
jupyter nbconvert "$i" "$i"
done
Ich hatte dieses Problem und habe versucht, die Lösung online zu finden. Obwohl ich einige Lösungen gefunden habe, haben sie immer noch einige Probleme, z. B. die lästige automatische Erstellung Untitled.txt
, Wenn Sie ein neues Notizbuch über das Dashboard starten.
Also schrieb ich schließlich meine eigene Lösung :
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
Um dieses Skript zu verwenden, können Sie es zu ~/.jupyter/jupyter_notebook_config.py
Hinzufügen :)
Beachten Sie, dass Sie das jupyter notebook/lab möglicherweise neu starten müssen, damit es funktioniert.