本文整理汇总了Python中nbformat.writes函数的典型用法代码示例。如果您正苦于以下问题:Python writes函数的具体用法?Python writes怎么用?Python writes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了writes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_notebook
def write_notebook(self, include_html=True):
suffix = "_responses_with_names" if self.include_usernames else "_responses"
nb_name = self.nb_name_stem + suffix
output_file = os.path.join(PROCESSED_NOTEBOOK_DIR, nb_name + '.ipynb')
html_output = os.path.join(PROCESSED_NOTEBOOK_DIR, nb_name + '.html')
remove_duplicate_answers = not self.include_usernames
filtered_cells = []
for prompt in self.question_prompts:
filtered_cells += prompt.cells
answers = prompt.answers_without_duplicates if remove_duplicate_answers else prompt.answers
for gh_username, response_cells in answers.items():
if self.include_usernames:
filtered_cells.append(
NotebookUtils.markdown_heading_cell(self.gh_username_to_fullname(gh_username), 4))
filtered_cells.extend(response_cells)
answer_book = deepcopy(self.template)
answer_book['cells'] = filtered_cells
nb = nbformat.from_dict(answer_book)
print "Writing", output_file
with io.open(output_file, 'wt') as fp:
nbformat.write(nb, fp, version=4)
if include_html:
# TODO why is the following necessary?
nb = nbformat.reads(nbformat.writes(nb, version=4), as_version=4)
html_content, _ = nbconvert.export_html(nb)
print "Writing", html_output
with io.open(html_output, 'w') as fp:
fp.write(html_content)
示例2: from_file
def from_file(self, filename):
import nbformat
from nbconvert import MarkdownExporter
from jinja2 import DictLoader
from traitlets.config import Config
c = Config()
# c.ExtractOutputPreprocessor.extract_output_types = set()
c.ExtractOutputPreprocessor.output_filename_template = 'images/{unique_key}_{cell_index}_{index}{extension}'
c.NbConvertBase.display_data_priority = ['application/javascript', 'text/html', 'text/markdown',
'image/svg+xml', 'text/latex', 'image/png', 'image/jpeg',
'text/plain']
nb = nbformat.read(filename, as_version=4)
dl = DictLoader({'full.tpl': TEMPLATE})
md_exporter = MarkdownExporter(config=c, extra_loaders=[
dl], template_file='full.tpl')
(body, resources) = md_exporter.from_notebook_node(nb)
self.kp.write(body, images={name.split(
'images/')[1]: data for name, data in resources.get('outputs', {}).items()})
# Add cleaned ipynb file
for cell in nb['cells']:
if cell['cell_type'] == 'code':
cell['outputs'] = [] # remove output data
cell['execution_count'] = None # reset to not executed
self.kp.write_src(os.path.basename(filename), nbformat.writes(nb))
示例3: fix_notebook
def fix_notebook(filename, grade_id, source):
with io.open(filename, "r", encoding="utf-8") as f:
nb = nbformat.read(f, as_version=4)
for i, cell in enumerate(nb.cells):
if "nbgrader" in cell["metadata"] and cell["metadata"]["nbgrader"]["grade_id"] == grade_id:
nb.cells[i]["source"] = source
return nbformat.writes(nb)
示例4: bundle
def bundle(handler, model):
"""Create a compressed tarball containing the notebook document.
Parameters
----------
handler : tornado.web.RequestHandler
Handler that serviced the bundle request
model : dict
Notebook model from the configured ContentManager
"""
notebook_filename = model['name']
notebook_content = nbformat.writes(model['content']).encode('utf-8')
notebook_name = os.path.splitext(notebook_filename)[0]
tar_filename = '{}.tar.gz'.format(notebook_name)
info = tarfile.TarInfo(notebook_filename)
info.size = len(notebook_content)
with io.BytesIO() as tar_buffer:
with tarfile.open(tar_filename, "w:gz", fileobj=tar_buffer) as tar:
tar.addfile(info, io.BytesIO(notebook_content))
handler.set_attachment_header(tar_filename)
handler.set_header('Content-Type', 'application/gzip')
# Return the buffer value as the response
handler.finish(tar_buffer.getvalue())
示例5: notebook_node_to_string_list
def notebook_node_to_string_list(notebook_node):
"""
Writes a NotebookNode to a list of strings.
:param notebook_node: The notebook as NotebookNode to write.
:return: The notebook as list of strings (linewise).
"""
return nbformat.writes(notebook_node, nbformat.NO_CONVERT).splitlines(True)
示例6: from_notebook_node
def from_notebook_node(self, nb, resources=None, **kw):
nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw)
if self.nbformat_version != nb_copy.nbformat:
resources['output_suffix'] = '.v%i' % self.nbformat_version
else:
resources['output_suffix'] = '.nbconvert'
output = nbformat.writes(nb_copy, version=self.nbformat_version)
return output, resources
示例7: convert_md
def convert_md():
"""Find all markdown files, convert into jupyter notebooks
"""
converted_files = []
reader = notedown.MarkdownReader(match='strict')
files = glob.glob('*/*.md')
# evaluate the newest file first, so we can catchup error ealier
files.sort(key=os.path.getmtime, reverse=True)
do_eval = int(os.environ.get('DO_EVAL', True))
if do_eval:
do_eval = int(os.environ.get('EVAL', True))
if not do_eval:
print('=== Will skip evaluating notebooks')
for fname in files:
new_fname = _get_new_fname(fname)
# parse if each markdown file is actually a jupyter notebook
with open(fname, 'r') as fp:
valid = '```{.python .input' in fp.read()
if not valid:
if new_fname != fname:
print('=== Rename %s -> %s' % (fname, new_fname))
shutil.copyfile(fname, new_fname)
converted_files.append((fname, new_fname))
continue
# read
with open(fname, 'r') as f:
notebook = reader.read(f)
if do_eval and not (_has_output(notebook) or
any([i in fname for i in ignore_execution])):
print('=== Evaluate %s with timeout %d sec'%(fname, timeout))
tic = time.time()
# update from ../data to data
for c in notebook.cells:
if c.get('cell_type', None) == 'code':
c['source'] = c['source'].replace(
'"../data', '"data').replace("'../data", "'data")
notedown.run(notebook, timeout)
print('=== Finished in %f sec'%(time.time()-tic))
# even that we will check it later, but do it ealier so we can see the
# error message before evaluating all notebooks
_check_notebook(notebook)
# write
# need to add language info to for syntax highlight
notebook['metadata'].update({'language_info':{'name':'python'}})
new_fname = _replace_ext(new_fname, 'ipynb')
print('=== Convert %s -> %s' % (fname, new_fname))
with open(new_fname, 'w') as f:
f.write(nbformat.writes(notebook))
converted_files.append((fname, new_fname))
return converted_files
示例8: test_write_downgrade_2
def test_write_downgrade_2(self):
"""dowgrade a v3 notebook to v2"""
# Open a version 3 notebook.
with self.fopen(u'test3.ipynb', 'r') as f:
nb = read(f, as_version=3)
jsons = writes(nb, version=2)
nb2 = json.loads(jsons)
(major, minor) = get_version(nb2)
self.assertEqual(major, 2)
示例9: save
def save(self, keep_alt=False):
if keep_alt:
# xxx store in alt filename
outfilename = "{}.alt.ipynb".format(self.name)
else:
outfilename = self.filename
# xxx don't specify output version for now
new_contents = nbformat.writes(self.notebook)
if replace_file_with_string(outfilename, new_contents):
print("{} saved into {}".format(self.name, outfilename))
示例10: _save_notebook
def _save_notebook(self, os_path, nb):
"""Save a notebook to an os_path."""
with self.atomic_writing(os_path, encoding='utf-8') as f:
if ftdetect(os_path) == 'notebook':
nbformat.write(nb, f, version=nbformat.NO_CONVERT)
elif ftdetect(os_path) == 'markdown':
nbjson = nbformat.writes(nb, version=nbformat.NO_CONVERT)
markdown = convert(nbjson, informat='notebook',
outformat='markdown')
f.write(markdown)
示例11: _save_notebook
def _save_notebook(self, path, nb):
self.log.debug('_save_notebook: %s', locals())
k = boto.s3.key.Key(self.bucket)
k.key = self._path_to_s3_key(path)
try:
notebook_json = nbformat.writes(nb, version=nbformat.NO_CONVERT)
k.set_contents_from_string(notebook_json)
except Exception as e:
raise web.HTTPError(400, u"Unexpected Error Writing Notebook: %s %s" % (path, e))
示例12: notebook_content
def notebook_content(self, content):
if isinstance(content, compat.string_types):
self._notebook_content = content
return
try:
# maybe this is a notebook
content = nbformat.writes(content, version=nbformat.NO_CONVERT)
self._notebook_content = content
except:
raise
示例13: write
def write(self, filepath, notebookNode, version=4):
"""
Write a notebook to Storage
:param filepath: The path to the notebook to write on the Storage
:param notebookNode: notebookNode object to write
:param version: Version of the notebook
:return boolean
"""
self.log.debug("Write the notebook '%s' to storage" % filepath)
content = nbformat.writes(notebookNode, version);
return self.do_write(filepath, content);
示例14: translate
def translate(self):
visitor = NBTranslator(self.document, self.app, self.docpath)
self.document.walkabout(visitor)
nb = _finilize_markdown_cells(visitor.nb)
if self.app.config.nbexport_execute:
ep = ExecutePreprocessor(allow_errors=True)
try:
ep.preprocess(nb, {'metadata': {}})
except CellExecutionError as e:
self.app.warn(str(e))
self.output = nbformat.writes(nb)
示例15: test_run_nb
def test_run_nb(self):
"""Test %run notebook.ipynb"""
from nbformat import v4, writes
nb = v4.new_notebook(
cells=[
v4.new_markdown_cell("The Ultimate Question of Everything"),
v4.new_code_cell("answer=42")
]
)
src = writes(nb, version=4)
self.mktmp(src, ext='.ipynb')
_ip.magic("run %s" % self.fname)
nt.assert_equal(_ip.user_ns['answer'], 42)