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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "451c8f58",
"metadata": {},
"outputs": [],
"source": [
"%%capture\n",
"%load_ext autoreload\n",
"%autoreload 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f290d8fb",
"metadata": {},
"outputs": [],
"source": [
"#| default_exp: cli"
]
},
{
"cell_type": "markdown",
"id": "0c27d4d0",
"metadata": {},
"source": [
"# CLI\n",
"\n",
"> Command-line interface for using `nb`"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a62b4fb4",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"import argparse\n",
"from pathlib import Path\n",
"\n",
"import nbformat\n",
"\n",
"from nb import export_nb,clean_nb\n",
"from nb.config import get_config,Config"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12e3162c",
"metadata": {},
"outputs": [],
"source": [
"import contextlib,json,sys,tempfile,uuid\n",
"from nb.core import read_nb\n",
"from nb import test"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "96737c5a",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def main():\n",
" cfg = get_config()\n",
" p = _get_parser()\n",
" args = p.parse_args()\n",
" if not args.cmd:\n",
" p.print_help()\n",
" raise SystemExit(1)\n",
" if args.cmd == 'export':\n",
" nbs = _get_nbs(args.notebooks, cfg)\n",
" exp_dir = args.export_dir or cfg.export_dir or '.'\n",
" if args.clean:\n",
" for nb in nbs: nbformat.write(clean_nb(nb), nb)\n",
" for nb in nbs: export_nb(nb, exp_dir)\n",
" if args.cmd == 'clean':\n",
" nbs = _get_nbs(args.notebooks, cfg)\n",
" for nb in nbs: nbformat.write(clean_nb(nb), nb)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "09b8407e",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def _get_nbs(nbs:list[str], cfg:Config):\n",
" if nbs: return nbs\n",
" if cfg.nb_dir: return list(Path(cfg.nb_dir).glob('*.ipynb'))\n",
" raise SystemExit('No notebooks specified and nb_dir not set in config')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "69b642d9",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def _get_parser():\n",
" parser = argparse.ArgumentParser(prog='nb')\n",
" subparsers = parser.add_subparsers(dest='cmd')\n",
" export_parser = subparsers.add_parser('export', help='Export ipynb notebooks to Python')\n",
" export_parser.add_argument('notebooks', nargs='*', help='Notebook files to export')\n",
" export_parser.add_argument('--export-dir', default=None, help='Directory to export Python files to')\n",
" export_parser.add_argument('--clean', action='store_true', help='Clean the notebooks before exporting')\n",
" clean_parser = subparsers.add_parser('clean', help='Clean notebooks')\n",
" clean_parser.add_argument('notebooks', nargs='*', help='Notebook files to clean')\n",
" return parser"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ce775b53",
"metadata": {},
"outputs": [],
"source": [
"def mk_nb(nb_path, **nb_kwargs):\n",
" nb = nbformat.v4.new_notebook(**nb_kwargs)\n",
" with open(nb_path, mode='w+') as f: nbformat.write(nb, f)\n",
" return nb"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "19889cd7",
"metadata": {},
"outputs": [],
"source": [
"def mk_nb_cfg(cfg_dir:str|Path, nb_dir:str|Path='', export_dir:str|Path=''):\n",
" pyproj = Path(cfg_dir)/'pyproject.toml'\n",
" lines = ['[tool.nb]']\n",
" if nb_dir: lines.append(f'nb_dir=\"{str(nb_dir)}\"')\n",
" if export_dir: lines.append(f'export_dir=\"{str(export_dir)}\"')\n",
" pyproj.write_text('\\n'.join(lines))\n",
" return pyproj"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4f17e8d6",
"metadata": {},
"outputs": [],
"source": [
"def run_cli(*args):\n",
" sys.argv = ['nb', *args]\n",
" main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c93ffa7c",
"metadata": {},
"outputs": [],
"source": [
"@contextlib.contextmanager\n",
"def tmp_nb(cells, nbkwargs={}):\n",
" with tempfile.TemporaryDirectory() as tmp:\n",
" nb_path = tmp + f'/tmp-{uuid.uuid4().hex}.ipynb'\n",
" nb = mk_nb(nb_path, cells=cells, **nbkwargs)\n",
" with contextlib.chdir(tmp): yield (tmp, nb_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "25e8195c",
"metadata": {},
"outputs": [],
"source": [
"def mk_nb_src(cells):\n",
" cells = cells if isinstance(cells, list) else [cells]\n",
" lines = ['# AUTOGENERATED! DO NOT EDIT!\\n']\n",
" for cell in cells:\n",
" if cell['source'].startswith('#| export'):\n",
" lines.append(f'# cell: {cell[\"id\"]}')\n",
" lines.extend([l for l in cell['source'].splitlines() if not l.startswith('#|')])\n",
" lines.append('')\n",
" return '\\n'.join(lines)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7b95c2d4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"usage: nb [-h] {export,clean} ...\n",
"\n",
"positional arguments:\n",
" {export,clean}\n",
" export Export ipynb notebooks to Python\n",
" clean Clean notebooks\n",
"\n",
"options:\n",
" -h, --help show this help message and exit\n"
]
}
],
"source": [
"with test.env(NO_COLOR='1'), test.raises(exc=SystemExit, contains='1'): run_cli()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a23b5af",
"metadata": {},
"outputs": [],
"source": [
"CLEAN_VALID_EXPORTED_CELLS = [\n",
" nbformat.v4.new_code_cell(f'#| default_exp: tmp'),\n",
" nbformat.v4.new_code_cell(f'#| export\\ndef hello(): return \"hi\"'),\n",
" nbformat.v4.new_code_cell('def goodbye(): return \"goodbye\"'),\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0e96c23d",
"metadata": {},
"outputs": [],
"source": [
"err_msg = 'No notebooks specified and nb_dir not set in config'\n",
"for subcmd in ('export', 'clean'):\n",
" with tmp_nb(CLEAN_VALID_EXPORTED_CELLS), test.raises(exc=SystemExit, contains=err_msg):\n",
" run_cli(subcmd)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fc918ca3",
"metadata": {},
"outputs": [],
"source": [
"with tmp_nb(CLEAN_VALID_EXPORTED_CELLS) as (tmp, nb_path):\n",
" run_cli('export', '--export-dir', tmp, nb_path)\n",
" test.equal((Path(tmp)/'tmp.py').read_text(), mk_nb_src(CLEAN_VALID_EXPORTED_CELLS))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "422d92ad",
"metadata": {},
"outputs": [],
"source": [
"with tmp_nb(CLEAN_VALID_EXPORTED_CELLS) as (tmp, nb_path):\n",
" mk_nb_cfg(tmp, nb_dir=tmp, export_dir=tmp)\n",
" run_cli('export')\n",
" test.equal((Path(tmp)/'tmp.py').read_text(), mk_nb_src(CLEAN_VALID_EXPORTED_CELLS))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e6bbc5ad",
"metadata": {},
"outputs": [],
"source": [
"DIRTY_VALID_EXPORTED_CELLS = [\n",
" nbformat.v4.new_code_cell('#| default_exp: tmp'),\n",
" nbformat.v4.new_code_cell('#| export\\nprint(\"hi\")', execution_count=42),\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7fedfaff",
"metadata": {},
"outputs": [],
"source": [
"with tmp_nb(DIRTY_VALID_EXPORTED_CELLS) as (tmp, nb_path):\n",
" mk_nb_cfg(tmp, nb_dir=tmp, export_dir=tmp)\n",
" run_cli('export', '--clean')\n",
" test.equal((Path(tmp)/'tmp.py').read_text(), mk_nb_src(DIRTY_VALID_EXPORTED_CELLS))\n",
" with open(nb_path) as f: cleaned_nb = nbformat.v4.reads(f.read())\n",
" test.equal(cleaned_nb.cells[1].execution_count, None)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f361af2b",
"metadata": {},
"outputs": [],
"source": [
"with tmp_nb(DIRTY_VALID_EXPORTED_CELLS, nbkwargs={'metadata': {'bogus': 'should be removed'}}) as (tmp, nb_path):\n",
" run_cli('clean', nb_path)\n",
" cleaned = read_nb(nb_path)\n",
" test.equal(cleaned.cells[1].execution_count, None)\n",
" test.equal('bogus' not in cleaned.metadata, True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61f3911b",
"metadata": {},
"outputs": [],
"source": [
"with tmp_nb(DIRTY_VALID_EXPORTED_CELLS, nbkwargs={'metadata': {'bogus': 'should be removed'}}) as (tmp, nb_path):\n",
" mk_nb_cfg(tmp, nb_dir=tmp, export_dir=tmp)\n",
" run_cli('clean')\n",
" cleaned = read_nb(nb_path)\n",
" test.equal(cleaned.cells[1].execution_count, None)\n",
" test.equal('bogus' not in cleaned.metadata, True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c086e4b4",
"metadata": {},
"outputs": [],
"source": [
"export_nb('cli.ipynb', src_dir='../nb')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.14.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|