-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjupyter_notebook_config_post_save.py
More file actions
42 lines (32 loc) · 1.38 KB
/
Copy pathjupyter_notebook_config_post_save.py
File metadata and controls
42 lines (32 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def post_save(model, os_path, contents_manager):
"""Post-save hook to automatically convert notebooks to .py scripts and .html files
Base on the : https://github.com/ipython/ipython/issues/8009
"""
import os
import shutil
from datetime import datetime
from subprocess import check_call
if model["type"] != "notebook":
return # only do this for notebooks
def convert_and_copy(target_format, os_path):
"""Convert and copy"""
nbconvert_mapping = {"html": "html", "py": "python"}
if target_format not in nbconvert_mapping:
print("[x] Wrong format for conversion")
return
d, fname = os.path.split(os_path)
fname_target = f"{fname[:-6]}.{target_format.lower()}"
dir_target = os.path.join(d, target_format.upper())
if not os.path.exists(dir_target):
os.makedirs(dir_target)
check_call(
["jupyter", "nbconvert", "--to", nbconvert_mapping[target_format], fname],
cwd=d,
)
shutil.move(
os.path.join(d, fname_target), os.path.join(dir_target, fname_target)
)
print(f"{datetime.now()} save into {os.path.join(dir_target, fname_target)}")
convert_and_copy(target_format="html", os_path=os_path)
convert_and_copy(target_format="py", os_path=os_path)
c.FileContentsManager.post_save_hook = post_save