本文整理匯總了Python中nbformat.write方法的典型用法代碼示例。如果您正苦於以下問題:Python nbformat.write方法的具體用法?Python nbformat.write怎麽用?Python nbformat.write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類nbformat
的用法示例。
在下文中一共展示了nbformat.write方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_timeseries_controls
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def test_timeseries_controls(self):
nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
abs_path = Path(_NB_FOLDER).absolute()
with open(nb_path) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
try:
ep.preprocess(nb, {"metadata": {"path": abs_path}})
except CellExecutionError:
nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
msg = f"Error executing the notebook '{nb_path}'.\n"
msg += f"See notebook '{nb_err}' for the traceback."
print(msg)
with open(nb_err, mode="w", encoding="utf-8") as f:
nbformat.write(nb, f)
raise
示例2: main
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def main():
parser = argparse.ArgumentParser(
description="Jupyter Notebooks to markdown"
)
parser.add_argument("notebook", nargs=1, help="The notebook to be converted.")
parser.add_argument("-o", "--output", help="output markdown file")
args = parser.parse_args()
old_ipynb = args.notebook[0]
new_ipynb = 'tmp.ipynb'
md_file = args.output
print(md_file)
if not md_file:
md_file = os.path.splitext(old_ipynb)[0] + '.md'
clear_notebook(old_ipynb, new_ipynb)
os.system('jupyter nbconvert ' + new_ipynb + ' --to markdown --output ' + md_file)
with open(md_file, 'a') as f:
f.write('<!-- INSERT SOURCE DOWNLOAD BUTTONS -->')
os.system('rm ' + new_ipynb)
示例3: export_html
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def export_html(nb, f):
config = {
'Exporter': {'template_file': 'embed',
'template_path': ['./sphinxext/']},
'ExtractOutputPreprocessor': {'enabled': True},
'CSSHTMLHeaderPreprocessor': {'enabled': True}
}
exporter = HTMLExporter(config)
body, resources = exporter.from_notebook_node(
nb, resources={'output_files_dir': f['nbname']})
for fn, data in resources['outputs'].items():
bfn = os.path.basename(fn)
with open("{destdir}/{fn}".format(fn=bfn, **f), 'wb') as res_f:
res_f.write(data)
return body
示例4: export_html
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def export_html(nb, f):
config = {
'Exporter': {
'template_file': 'basic',
'template_path': ['./sphinxext/']
},
'ExtractOutputPreprocessor': {
'enabled': True
},
'CSSHTMLHeaderPreprocessor': {
'enabled': True
}
}
exporter = HTMLExporter(config)
body, resources = exporter.from_notebook_node(
nb, resources={'output_files_dir': f['nbname']})
for fn, data in resources['outputs'].items():
bfn = os.path.basename(fn)
with open("{destdir}/{fn}".format(fn=bfn, **f), 'wb') as res_f:
res_f.write(data)
return body
示例5: test_clustering_nbdisplay_notebook
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def test_clustering_nbdisplay_notebook(self):
nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
abs_path = Path(_NB_FOLDER).absolute()
with open(nb_path) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
try:
ep.preprocess(nb, {"metadata": {"path": abs_path}})
except CellExecutionError:
nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
msg = f"Error executing the notebook '{nb_path}'.\n"
msg += f"See notebook '{nb_err}' for the traceback."
print(msg)
with open(nb_err, mode="w", encoding="utf-8") as f:
nbformat.write(nb, f)
raise
示例6: test_process_tree_notebook
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def test_process_tree_notebook():
nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
abs_path = Path(_NB_FOLDER).absolute()
with open(nb_path) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
try:
ep.preprocess(nb, {"metadata": {"path": abs_path}})
except CellExecutionError:
nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
msg = f"Error executing the notebook '{nb_path}'.\n"
msg += f"See notebook '{nb_err}' for the traceback."
print(msg)
with open(nb_err, mode="w", encoding="utf-8") as f:
nbformat.write(nb, f)
raise
示例7: test_geoip_notebook
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def test_geoip_notebook(self):
nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
abs_path = Path(_NB_FOLDER).absolute()
with open(nb_path, "rb") as f:
nb_bytes = f.read()
nb_text = nb_bytes.decode("utf-8")
nb = nbformat.reads(nb_text, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
try:
ep.preprocess(nb, {"metadata": {"path": abs_path}})
except CellExecutionError:
nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
msg = f"Error executing the notebook '{nb_path}'.\n"
msg += f"See notebook '{nb_err}' for the traceback."
print(msg)
with open(nb_err, mode="w", encoding="utf-8") as f:
nbformat.write(nb, f)
raise
示例8: test_timeline_controls
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def test_timeline_controls(self):
nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
abs_path = Path(_NB_FOLDER).absolute()
with open(nb_path) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
try:
ep.preprocess(nb, {"metadata": {"path": abs_path}})
except CellExecutionError:
nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
msg = f"Error executing the notebook '{nb_path}'.\n"
msg += f"See notebook '{nb_err}' for the traceback."
print(msg)
with open(nb_err, mode="w", encoding="utf-8") as f:
nbformat.write(nb, f)
raise
示例9: test_widgets_notebook
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def test_widgets_notebook(self):
nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
abs_path = Path(_NB_FOLDER).absolute()
with open(nb_path) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
try:
ep.preprocess(nb, {"metadata": {"path": abs_path}})
except CellExecutionError:
nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
msg = f"Error executing the notebook '{nb_path}'.\n"
msg += f"See notebook '{nb_err}' for the traceback."
print(msg)
with open(nb_err, mode="w", encoding="utf-8") as f:
nbformat.write(nb, f)
raise
示例10: main
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def main(args=None):
parser = argparse.ArgumentParser(
"Convert LaTeX beamer slides to IPython notebooks + RISE"
)
parser.add_argument("input", nargs=1, help="Input file (.tex)")
parser.add_argument("output", nargs=1, help="Output file (.ipynb)")
parser.add_argument(
"-c", "--converter", action="store", dest="converter", default='',
help="Path to a Python file which defines a subclass of Tex2Cells."
)
args = parser.parse_args(args)
converter = None
if len(args.converter) > 0:
with open(args.converter) as fp:
converter = get_tex2cells_subclass(fp, args.converter)
if converter is None:
converter = Tex2Cells
with open(args.input[0]) as f:
code = f.read()
nb = tex2ipy(code, converter)
with open(args.output[0], 'w') as f:
nbformat.write(nb, f)
示例11: run_notebook
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def run_notebook(filename):
run_path = os.path.split(filename)[0]
with open(filename) as f:
nb = nbformat.read(f, as_version=4)
try:
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
ep.preprocess(nb, {'metadata': {'path': run_path}})
# FIXME: use tempfile and mv to avoid interruption
# better split the source code of the notebook and the compiled targets.
with open(filename, 'wt') as f:
nbformat.write(nb, f)
except Exception as e:
print('processing', filename, e)
示例12: create_jupyter_notebook_random_question
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def create_jupyter_notebook_random_question(destination_filename='100_Numpy_random.ipynb'):
""" Programmatically create jupyter notebook with the questions (and hints and solutions if required)
saved under source files """
# Create cells sequence
nb = nbf.v4.new_notebook()
nb['cells'] = []
# - Add header:
nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["header"]))
nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["sub_header"]))
nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["jupyter_instruction_rand"]))
# - Add initialisation
nb['cells'].append(nbf.v4.new_code_cell('%run initialise.py'))
nb['cells'].append(nbf.v4.new_code_cell("pick()"))
# Delete file if one with the same name is found
if os.path.exists(destination_filename):
os.remove(destination_filename)
# Write sequence to file
nbf.write(nb, destination_filename)
示例13: buildNotebook
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def buildNotebook(appName, result, notebookPath, dataFilePath, runId):
"""
Method to build .ipynb notebook with init code
cell for profiles and one report cell per category.
"""
begin = time.time()
LOGGER.info('generating notebook %s -> ', os.path.basename(notebookPath))
nb = nbf.new_notebook()
numOfCategories, d3Flots = buildReportCells(nb, result, dataFilePath)
buildInitCell(nb, numOfCategories, d3Flots, appName, runId)
try:
with open(notebookPath, 'w') as reportFile:
nbformat.write(nb, reportFile)
notebookSize = formatHumanReadable(os.path.getsize(notebookPath))
elapsed = time.time() - begin
LOGGER.completed('completed %s in %0.2f sec.', notebookSize, elapsed)
return True
except IOError:
LOGGER.exception('Could not write to the notebook(.ipynb) file')
return False
示例14: py2ipynb
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def py2ipynb(input, output, cellmark_style, other_ignores=[]):
"""Converts a .py file to a V.4 .ipynb notebook usiing `parsePy` function
:param input: Input .py filename
:param output: Output .ipynb filename
:param cellmark_style: Determines cell marker based on IDE, see parsePy documentation for values
:param other_ignores: Other lines to ignore
"""
# Create the code cells by parsing the file in input
cells = []
for c in parsePy(input, cellmark_style, other_ignores):
codecell, metadata, code = c
cell = new_code_cell(source=code, metadata=metadata) if codecell else new_markdown_cell(source=code, metadata=metadata)
cells.append(cell)
# This creates a V4 Notebook with the code cells extracted above
nb0 = new_notebook(cells=cells,
metadata={'language': 'python',})
with codecs.open(output, encoding='utf-8', mode='w') as f:
nbformat.write(nb0, f, 4)
示例15: append_scrapbook_commands
# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import write [as 別名]
def append_scrapbook_commands(input_nb_path, output_nb_path, scrap_specs):
notebook = nbf.read(input_nb_path, as_version=nbf.NO_CONVERT)
scrapbook_cells = []
# Always need to import nteract-scrapbook
scrapbook_cells.append(nbf.v4.new_code_cell(source="import scrapbook as sb"))
# Create a cell to store each key and value in the scrapbook
for k, v in scrap_specs.items():
source = "sb.glue(\"{0}\", {1})".format(k, v.code)
scrapbook_cells.append(nbf.v4.new_code_cell(source=source))
# Append the cells to the notebook
[notebook['cells'].append(c) for c in scrapbook_cells]
# Write out the new notebook
nbf.write(notebook, output_nb_path)