|
2 | 2 | import glob
|
3 | 3 |
|
4 | 4 | import nbformat
|
5 |
| -from nbconvert import RSTExporter, preprocessors |
| 5 | +from nbconvert import RSTExporter |
| 6 | +from nbconvert.preprocessors import ExecutePreprocessor |
6 | 7 |
|
7 | 8 |
|
8 |
| -def cache(nbfile): |
| 9 | +def convert(nbfile): |
9 | 10 | basename, _ = os.path.splitext(nbfile)
|
10 |
| - bakfile = basename + '.bak' |
11 |
| - with open(nbfile, 'r') as nb, open(bakfile, 'w') as bak: |
12 |
| - bak.write(nb.read()) |
13 |
| - return bakfile |
14 |
| - |
15 | 11 |
|
16 |
| -def process(nbfile, processor): |
17 | 12 | meta = {'metadata': {'path': '.'}}
|
18 |
| - with open(nbfile, 'r') as nbf: |
19 |
| - nbook = nbformat.read(nbf, as_version=4) |
20 |
| - |
21 |
| - runner = processor(timeout=600, kernel_name='probscale') |
22 |
| - runner.preprocess(nbook, meta) |
23 |
| - |
24 |
| - with open(nbfile, 'w') as nbf: |
25 |
| - nbformat.write(nbook, nbf) |
| 13 | + with open(nbfile, 'r', encoding='utf-8') as nbf: |
| 14 | + nbdata = nbformat.read(nbf, as_version=4, encoding='utf-8') |
26 | 15 |
|
| 16 | + runner = ExecutePreprocessor(timeout=600, kernel_name='probscale') |
| 17 | + runner.preprocess(nbdata, meta) |
27 | 18 |
|
28 |
| -def convert(nbfile): |
29 |
| - basename, _ = os.path.splitext(nbfile) |
30 | 19 | img_folder = basename + '_files'
|
31 |
| - os.makedirs(img_folder, exist_ok=True) |
32 |
| - print("\tconverting " + nbfile) |
33 |
| - |
34 |
| - with open(nbfile, 'r') as nb: |
35 |
| - nbdata = nbformat.reads(nb.read(), as_version=4) |
36 |
| - |
37 |
| - rst = RSTExporter() |
38 |
| - body_raw, images = rst.from_notebook_node(nbdata) |
| 20 | + body_raw, images = RSTExporter().from_notebook_node(nbdata) |
39 | 21 | body_final = body_raw.replace('.. image:: ', '.. image:: {}/'.format(img_folder))
|
40 | 22 |
|
41 |
| - with open(basename + '.rst', 'w') as rst_out: |
| 23 | + with open(basename + '.rst', 'w', encoding='utf-8') as rst_out: |
42 | 24 | rst_out.write(body_final)
|
43 | 25 |
|
44 | 26 | for img_name, img_data in images['outputs'].items():
|
45 | 27 | img_path = os.path.join(img_folder, img_name)
|
46 | 28 | with open(img_path, 'wb') as img:
|
47 |
| - print('\twriting ' + img_path) |
48 | 29 | img.write(img_data)
|
49 | 30 |
|
50 | 31 |
|
51 | 32 | if __name__ == '__main__':
|
52 | 33 | for nbfile in glob.glob('*.ipynb'):
|
53 |
| - bak = cache(nbfile) |
54 |
| - success = False |
55 |
| - try: |
56 |
| - process(nbfile, preprocessors.ExecutePreprocessor) |
57 |
| - convert(nbfile) |
58 |
| - success = True |
59 |
| - finally: |
60 |
| - process(nbfile, preprocessors.ClearOutputPreprocessor) |
61 |
| - if success: |
62 |
| - os.remove(bak) |
| 34 | + convert(nbfile) |
0 commit comments