Created
February 24, 2022 21:08
-
-
Save hamelsmu/f15bc3f036c5102b35f8b2f582d231cf to your computer and use it in GitHub Desktop.
How to use nbconvertExecutePreprocessor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#From nbdev.export2html | |
class ExecuteShowDocPreprocessor(ExecutePreprocessor): | |
"An `ExecutePreprocessor` that only executes `show_doc` and `import` cells" | |
def preprocess_cell(self, cell, resources, index): | |
if not check_re(cell, _re_notebook2script): | |
if check_re(cell, _re_show_doc): | |
return super().preprocess_cell(cell, resources, index) | |
elif check_re_multi(cell, [_re_import, _re_lib_import.re]): | |
if check_re_multi(cell, [_re_export, 'show_doc', '^\s*#\s*import']): | |
# r = list(filter(_non_comment_code, cell['source'].split('\n'))) | |
# if r: print("You have import statements mixed with other code", r) | |
return super().preprocess_cell(cell, resources, index) | |
# try: return super().preprocess_cell(cell, resources, index) | |
# except: pass | |
return cell, resources | |
#export | |
def _import_show_doc_cell(mods=None): | |
"Add an import show_doc cell." | |
source = f"from nbdev.showdoc import show_doc" | |
if mods is not None: | |
for mod in mods: source += f"\nfrom {get_config().lib_name}.{mod} import *" | |
return {'cell_type': 'code', | |
'execution_count': None, | |
'metadata': {'hide_input': True}, | |
'outputs': [], | |
'source': source} | |
def execute_nb(nb, mod=None, metadata=None, show_doc_only=True): | |
"Execute `nb` (or only the `show_doc` cells) with `metadata`" | |
mods = ([] if mod is None else [mod]) + _gather_export_mods(nb['cells']) | |
nb['cells'].insert(0, _import_show_doc_cell(mods)) | |
ep_cls = ExecuteShowDocPreprocessor if show_doc_only else ExecutePreprocessor | |
ep = ep_cls(timeout=600, kernel_name='python3') | |
metadata = metadata or {} | |
pnb = nbformat.from_dict(nb) | |
ep.preprocess(pnb, metadata) | |
return pnb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment