Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2d1c243

Browse files
committed
Populate notebook metadata when exporting with %notebook magic
1 parent eeb177f commit 2d1c243

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

IPython/core/magics/basic.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from logging import error
55
import io
66
import os
7+
import platform
78
from pprint import pformat
89
import sys
910
from warnings import warn
@@ -603,7 +604,28 @@ def notebook(self, s):
603604
)
604605
cells.append(cell)
605606

606-
nb = v4.new_notebook(cells=cells)
607+
nb = v4.new_notebook(
608+
cells=cells,
609+
metadata={
610+
"kernelspec": {
611+
"display_name": "Python 3 (ipykernel)",
612+
"language": "python",
613+
"name": "python3",
614+
},
615+
"language_info": {
616+
"codemirror_mode": {
617+
"name": "ipython",
618+
"version": 3
619+
},
620+
"file_extension": ".py",
621+
"mimetype": "text/x-python",
622+
"name": "python",
623+
"nbconvert_exporter": "python",
624+
"pygments_lexer": "ipython3",
625+
"version": platform.python_version()
626+
}
627+
}
628+
)
607629
with io.open(outfname, "w", encoding="utf-8") as f:
608630
write(nb, f, version=4)
609631

tests/test_magic.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33

44
import gc
55
import io
6+
import json
67
import os
8+
import platform
79
import re
810
import shlex
911
import signal
@@ -928,6 +930,17 @@ def test_notebook_export_json():
928930
with TemporaryDirectory() as td:
929931
outfile = os.path.join(td, "nb.ipynb")
930932
_ip.run_line_magic("notebook", "%s" % outfile)
933+
with open(outfile) as f:
934+
exported = json.load(f)
935+
936+
# check metadata
937+
language_info = exported["metadata"]["language_info"]
938+
assert language_info["name"] == "python"
939+
assert language_info["file_extension"] == ".py"
940+
assert language_info["version"] == platform.python_version()
941+
942+
kernelspec = exported["metadata"]["kernelspec"]
943+
assert kernelspec["language"] == "python"
931944

932945

933946
def test_notebook_export_json_with_output():

0 commit comments

Comments
 (0)