##// END OF EJS Templates
Reset the interactive namespace __warningregistry__ before executing code...
Reset the interactive namespace __warningregistry__ before executing code Fixes #6611. Idea: Right now, people often don't see important warnings when running code in IPython, because (to a first approximation) any given warning will only issue once per session. Blink and you'll miss it! This is a very common contributor to confused emails to numpy-discussion. E.g.: In [5]: 1 / my_array_with_random_contents /home/njs/.user-python2.7-64bit-3/bin/ipython:1: RuntimeWarning: divide by zero encountered in divide #!/home/njs/.user-python2.7-64bit-3/bin/python Out[5]: array([ 1.77073316, -2.29765021, -2.01800811, ..., 1.13871243, -1.08302964, -8.6185091 ]) Oo, right, guess I gotta be careful of those zeros -- thanks, numpy, for giving me that warning! A few days later: In [592]: 1 / some_other_array Out[592]: array([ 3.07735763, 0.50769289, 0.83984078, ..., -0.67563917, -0.85736257, -1.36511271]) Oops, it turns out that this array had a zero in it too, and that's going to bite me later. But no warning this time! The effect of this commit is to make it so that warnings triggered by the code in cell 5 do *not* suppress warnings triggered by the code in cell 592. Note that this only applies to warnings triggered *directly* by code entered interactively -- if somepkg.foo() calls anotherpkg.bad_func() which issues a warning, then this warning will still only be displayed once, even if multiple cells call somepkg.foo(). But if cell 5 and cell 592 both call anotherpkg.bad_func() directly, then both will get warnings. (Important exception: if foo() is defined *interactively*, and calls anotherpkg.bad_func(), then every cell that calls foo() will display the warning again. This is unavoidable without fixes to CPython upstream.) Explanation: Python's warning system has some weird quirks. By default, it tries to suppress duplicate warnings, where "duplicate" means the same warning message triggered twice by the same line of code. This requires determining which line of code is responsible for triggering a warning, and this is controlled by the stacklevel= argument to warnings.warn. Basically, though, the idea is that if foo() calls bar() which calls baz() which calls some_deprecated_api(), then baz() will get counted as being "responsible", and the warning system will make a note that the usage of some_deprecated_api() inside baz() has already been warned about and doesn't need to be warned about again. So far so good. To accomplish this, obviously, there has to be a record of somewhere which line this was. You might think that this would be done by recording the filename:linenumber pair in a dict inside the warnings module, or something like that. You would be wrong. What actually happens is that the warnings module will use stack introspection to reach into baz()'s execution environment, create a global (module-level) variable there named __warningregistry__, and then, inside this dictionary, record just the line number. Basically, it assumes that any given module contains only one line 1, only one line 2, etc., so storing the filename is irrelevant. Obviously for interactive code this is totally wrong -- all cells share the same execution environment and global namespace, and they all contain a new line 1. Currently the warnings module treats these as if they were all the same line. In fact they are not the same line; once we have executed a given chunk of code, we will never see those particular lines again. As soon as a given chunk of code finishes executing, its line number labels become meaningless, and the corresponding warning registry entries become meaningless as well. Therefore, with this patch we delete the __warningregistry__ each time we execute a new block of code.

File last commit:

r18247:d7aa64bd
r18548:61431d7d
Show More
nbconvertapp.py
320 lines | 11.8 KiB | text/x-python | PythonLexer
Brian E. Granger
Adding initial version of nbconvert.
r11087 #!/usr/bin/env python
MinRK
add PDFExporter...
r16265 """NbConvert is a utility for conversion of .ipynb files.
Brian E. Granger
Adding initial version of nbconvert.
r11087
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 Command-line interface for the NbConvert conversion utility.
Brian E. Granger
Adding initial version of nbconvert.
r11087 """
MinRK
add PDFExporter...
r16265 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Brian E. Granger
Adding initial version of nbconvert.
r11087
from __future__ import print_function
MinRK
add basic logging to NbConvert stages
r11842
import logging
Brian E. Granger
Adding initial version of nbconvert.
r11087 import sys
import os
Jonathan Frederic
Added writers and supporting code.
r11367 import glob
Brian E. Granger
Adding initial version of nbconvert.
r11087
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
MinRK
add missing ProfileDir to nbconvertapp.classes
r12358 from IPython.core.profiledir import ProfileDir
MinRK
populate NbConvertApp.classes from exporters, writers, transformers
r11453 from IPython.config import catch_config_error, Configurable
MinRK
export_format is an enum...
r11454 from IPython.utils.traitlets import (
Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
)
Jonathan Frederic
Added writers and supporting code.
r11367 from IPython.utils.importstring import import_item
Brian E. Granger
Adding initial version of nbconvert.
r11087
MinRK
create single exporter in NotebookApp...
r11865 from .exporters.export import get_export_names, exporter_map
Jake Vanderplas
rename post_processors submodule to postprocessors
r12249 from IPython.nbconvert import exporters, preprocessors, writers, postprocessors
Jonathan Frederic
Rename utils.config to utils.base
r11420 from .utils.base import NbConvertBase
David Wolever
Catch ConversionExceptions in main nbconvert loop
r11703 from .utils.exceptions import ConversionException
Brian E. Granger
Adding initial version of nbconvert.
r11087
#-----------------------------------------------------------------------------
Jonathan Frederic
Added writers and supporting code.
r11367 #Classes and functions
Brian E. Granger
Adding initial version of nbconvert.
r11087 #-----------------------------------------------------------------------------
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 class DottedOrNone(DottedObjectName):
"""
A string holding a valid dotted object name in Python, such as A.b3._c
Also allows for None type."""
default_value = u''
def validate(self, obj, value):
if value is not None and len(value) > 0:
return super(DottedOrNone, self).validate(obj, value)
else:
return value
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 nbconvert_aliases = {}
nbconvert_aliases.update(base_aliases)
nbconvert_aliases.update({
Jonathan Frederic
Added aliases to nbconvert commandline
r11735 'to' : 'NbConvertApp.export_format',
Matthias BUSSONNIER
Exporter -> TemplateExporter / BaseExporter
r12500 'template' : 'TemplateExporter.template_file',
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 'writer' : 'NbConvertApp.writer_class',
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 'post': 'NbConvertApp.postprocessor_class',
damianavila
Added working speaker notes for slides.
r11894 'output': 'NbConvertApp.output_base',
MinRK
clarify `reveal-prefix` alias name
r12440 'reveal-prefix': 'RevealHelpPreprocessor.url_prefix',
MinRK
support downgrading notebooks with nbconvert...
r18247 'nbformat': 'NotebookExporter.nbformat_version',
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 })
nbconvert_flags = {}
nbconvert_flags.update(base_flags)
nbconvert_flags.update({
'stdout' : (
{'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
"Write notebook output to stdout instead of files."
)
})
Jonathan Frederic
Added writers and supporting code.
r11367 class NbConvertApp(BaseIPythonApplication):
Thomas Kluyver
Miscellaneous docs fixes
r13597 """Application used to convert from notebook file type (``*.ipynb``)"""
Brian E. Granger
Adding initial version of nbconvert.
r11087
Jonathan Frederic
Set name and allow base to determine default config name
r11406 name = 'ipython-nbconvert'
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 aliases = nbconvert_aliases
flags = nbconvert_flags
MinRK
add basic logging to NbConvert stages
r11842 def _log_level_default(self):
return logging.INFO
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 def _classes_default(self):
MinRK
add missing ProfileDir to nbconvertapp.classes
r12358 classes = [NbConvertBase, ProfileDir]
jakobgager
Adress comments...
r12902 for pkg in (exporters, preprocessors, writers, postprocessors):
MinRK
populate NbConvertApp.classes from exporters, writers, transformers
r11453 for name in dir(pkg):
cls = getattr(pkg, name)
if isinstance(cls, type) and issubclass(cls, Configurable):
classes.append(cls)
MinRK
add missing ProfileDir to nbconvertapp.classes
r12358
MinRK
populate NbConvertApp.classes from exporters, writers, transformers
r11453 return classes
Paul Ivanov
added examples and info for nbconvert
r11248
Jonathan Frederic
Added writers and supporting code.
r11367 description = Unicode(
MinRK
export_format is an enum...
r11454 u"""This application is used to convert notebook files (*.ipynb)
Jonathan Frederic
Added warnings
r11755 to various other formats.
WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.""")
Paul Ivanov
print supported TARGETs for nbconvert --help
r11251
Matthias BUSSONNIER
add output flag to nbconvert...
r11801 output_base = Unicode('', config=True, help='''overwrite base name use for output files.
MinRK
support downgrading notebooks with nbconvert...
r18247 can only be used when converting one notebook at a time.
Matthias BUSSONNIER
add output flag to nbconvert...
r11801 ''')
Jonathan Frederic
Added writers and supporting code.
r11367 examples = Unicode(u"""
MinRK
export_format is an enum...
r11454 The simplest way to use nbconvert is
> ipython nbconvert mynotebook.ipynb
which will convert mynotebook.ipynb to the default format (probably HTML).
Jonathan Frederic
Updated help string
r11741 You can specify the export format with `--to`.
MinRK
export_format is an enum...
r11454 Options include {0}
dexterdev
Update nbconvertapp.py...
r16435 > ipython nbconvert --to latex mynotebook.ipynb
Jonathan Frederic
Updated help string
r11741
Jonathan Frederic
flavor=template
r11745 Both HTML and LaTeX support multiple output templates. LaTeX includes
Pierre Haessig
fix extra typo spotted by @takluyver
r16720 'base', 'article' and 'report'. HTML includes 'basic' and 'full'. You
Jonathan Frederic
HTML-Slides -> Slides-Reveal
r11744 can specify the flavor of the format used.
Jonathan Frederic
Updated help string
r11741
Jonathan Frederic
Update comment
r11761 > ipython nbconvert --to html --template basic mynotebook.ipynb
MinRK
export_format is an enum...
r11454
You can also pipe the output to stdout, rather than a file
> ipython nbconvert mynotebook.ipynb --stdout
Jonathan Frederic
Fixed errors after testing...
r11742
MinRK
add PDFExporter...
r16265 PDF is generated via latex
Jonathan Frederic
Fixed errors after testing...
r11742
MinRK
add PDFExporter...
r16265 > ipython nbconvert mynotebook.ipynb --to pdf
MinRK
export_format is an enum...
r11454
damianavila
Adding --to slides --post serve example in help.
r11776 You can get (and serve) a Reveal.js-powered slideshow
> ipython nbconvert myslides.ipynb --to slides --post serve
Jonathan Frederic
Added writers and supporting code.
r11367 Multiple notebooks can be given at the command line in a couple of
different ways:
> ipython nbconvert notebook*.ipynb
> ipython nbconvert notebook1.ipynb notebook2.ipynb
MinRK
mention local config file in examples
r11469
or you can specify the notebooks list in a config file, containing::
c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
> ipython nbconvert --config mycfg.py
MinRK
export_format is an enum...
r11454 """.format(get_export_names()))
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # Writer specific variables
Jonathan Frederic
Added writers and supporting code.
r11367 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
help="""Instance of the writer class used to write the
results of the conversion.""")
writer_class = DottedObjectName('FilesWriter', config=True,
help="""Writer class used to write the
results of the conversion""")
Jonathan Frederic
Make writer & post-processor aliases case insensitive.
r12054 writer_aliases = {'fileswriter': 'IPython.nbconvert.writers.files.FilesWriter',
'debugwriter': 'IPython.nbconvert.writers.debug.DebugWriter',
'stdoutwriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
Jonathan Frederic
Added writers and supporting code.
r11367 writer_factory = Type()
Paul Ivanov
print supported TARGETs for nbconvert --help
r11251
Jonathan Frederic
Added writers and supporting code.
r11367 def _writer_class_changed(self, name, old, new):
Jonathan Frederic
Revert "Simplify"...
r12070 if new.lower() in self.writer_aliases:
new = self.writer_aliases[new.lower()]
Jonathan Frederic
Added writers and supporting code.
r11367 self.writer_factory = import_item(new)
Paul Ivanov
added examples and info for nbconvert
r11248
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 # Post-processor specific variables
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 postprocessor = Instance('IPython.nbconvert.postprocessors.base.PostProcessorBase',
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 help="""Instance of the PostProcessor class used to write the
results of the conversion.""")
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 postprocessor_class = DottedOrNone(config=True,
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 help="""PostProcessor class used to write the
results of the conversion""")
MinRK
remove PDF post processor
r16418 postprocessor_aliases = {'serve': 'IPython.nbconvert.postprocessors.serve.ServePostProcessor'}
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 postprocessor_factory = Type()
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 def _postprocessor_class_changed(self, name, old, new):
if new.lower() in self.postprocessor_aliases:
new = self.postprocessor_aliases[new.lower()]
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 if new:
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 self.postprocessor_factory = import_item(new)
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747
Brian E. Granger
Adding initial version of nbconvert.
r11087
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # Other configurable variables
MinRK
export_format is an enum...
r11454 export_format = CaselessStrEnum(get_export_names(),
Jonathan Frederic
Added aliases to nbconvert commandline
r11735 default_value="html",
MinRK
export_format is an enum...
r11454 config=True,
help="""The export format to be used."""
)
Brian E. Granger
Adding initial version of nbconvert.
r11087
Jonathan Frederic
Added writers and supporting code.
r11367 notebooks = List([], config=True, help="""List of notebooks to convert.
MinRK
export_format is an enum...
r11454 Wildcards are supported.
Filenames passed positionally will be added to the list.
""")
Brian E. Granger
Adding initial version of nbconvert.
r11087
Jonathan Frederic
Added writers and supporting code.
r11367 @catch_config_error
def initialize(self, argv=None):
Jonathan Frederic
Better name `init_syspath`
r11652 self.init_syspath()
jon
Call path fix before traitlet stuff
r16356 super(NbConvertApp, self).initialize(argv)
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 self.init_notebooks()
Jonathan Frederic
Added writers and supporting code.
r11367 self.init_writer()
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 self.init_postprocessor()
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747
Brian E. Granger
Adding initial version of nbconvert.
r11087
Jonathan Frederic
Add cwd to sys.path...
r11651
Jonathan Frederic
Better name `init_syspath`
r11652 def init_syspath(self):
Jonathan Frederic
Add cwd to sys.path...
r11651 """
Add the cwd to the sys.path ($PYTHONPATH)
"""
Jonathan Frederic
Insert cwd to top of list
r11688 sys.path.insert(0, os.getcwd())
Jonathan Frederic
Add cwd to sys.path...
r11651
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 def init_notebooks(self):
MinRK
use positional args *or* config...
r11468 """Construct the list of notebooks.
If notebooks are passed on the command-line,
they override notebooks specified in config files.
Glob each notebook to replace notebook patterns with filenames.
Jonathan Frederic
Added writers and supporting code.
r11367 """
Brian E. Granger
Adding initial version of nbconvert.
r11087
MinRK
use positional args *or* config...
r11468 # Specifying notebooks on the command-line overrides (rather than adds)
# the notebook list
if self.extra_args:
patterns = self.extra_args
else:
patterns = self.notebooks
Jonathan Frederic
Added writers and supporting code.
r11367
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # Use glob to replace all the notebook patterns with filenames.
Jonathan Frederic
Added writers and supporting code.
r11367 filenames = []
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 for pattern in patterns:
Jonathan Frederic
Allow notebook filenames without their extensions
r11660
# Use glob to find matching filenames. Allow the user to convert
# notebooks without having to type the extension.
globbed_files = glob.glob(pattern)
globbed_files.extend(glob.glob(pattern + '.ipynb'))
MinRK
warn on glob with no matches
r11851 if not globbed_files:
self.log.warn("pattern %r matched no files", pattern)
Jonathan Frederic
Allow notebook filenames without their extensions
r11660
for filename in globbed_files:
Jonathan Frederic
Added writers and supporting code.
r11367 if not filename in filenames:
filenames.append(filename)
self.notebooks = filenames
def init_writer(self):
"""
Initialize the writer (which is stateless)
"""
self._writer_class_changed(None, self.writer_class, self.writer_class)
self.writer = self.writer_factory(parent=self)
Brian E. Granger
Adding initial version of nbconvert.
r11087
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 def init_postprocessor(self):
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 """
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 Initialize the postprocessor (which is stateless)
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747 """
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 self._postprocessor_class_changed(None, self.postprocessor_class,
self.postprocessor_class)
if self.postprocessor_factory:
self.postprocessor = self.postprocessor_factory(parent=self)
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 def start(self):
Brian E. Granger
Adding initial version of nbconvert.
r11087 """
MinRK
cleanup flags / aliases for NbConvertApp...
r11448 Ran after initialization completed
Jonathan Frederic
Added writers and supporting code.
r11367 """
Brian E. Granger
Adding initial version of nbconvert.
r11087 super(NbConvertApp, self).start()
Jonathan Frederic
Moved nb conversion into its own method. Additional error handling.
r11400 self.convert_notebooks()
def convert_notebooks(self):
"""
Convert the notebooks in the self.notebook traitlet
"""
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # Export each notebook
Jonathan Frederic
Moved nb conversion into its own method. Additional error handling.
r11400 conversion_success = 0
Matthias BUSSONNIER
add output flag to nbconvert...
r11801
if self.output_base != '' and len(self.notebooks) > 1:
MinRK
create single exporter in NotebookApp...
r11865 self.log.error(
Matthias BUSSONNIER
add output flag to nbconvert...
r11801 """UsageError: --output flag or `NbConvertApp.output_base` config option
cannot be used when converting multiple notebooks.
MinRK
create single exporter in NotebookApp...
r11865 """)
Matthias BUSSONNIER
add output flag to nbconvert...
r11801 self.exit(1)
MinRK
create single exporter in NotebookApp...
r11865
exporter = exporter_map[self.export_format](config=self.config)
Matthias BUSSONNIER
add output flag to nbconvert...
r11801
Jonathan Frederic
Added writers and supporting code.
r11367 for notebook_filename in self.notebooks:
MinRK
add basic logging to NbConvert stages
r11842 self.log.info("Converting notebook %s to %s", notebook_filename, self.export_format)
Jonathan Frederic
Added writers and supporting code.
r11367
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # Get a unique key for the notebook and set it in the resources object.
Jonathan Frederic
Added writers and supporting code.
r11367 basename = os.path.basename(notebook_filename)
notebook_name = basename[:basename.rfind('.')]
Matthias BUSSONNIER
add output flag to nbconvert...
r11801 if self.output_base:
MinRK
Avoid duplicate extension in nbconvert...
r17309 # strip duplicate extension from output_base, to avoid Basname.ext.ext
if getattr(exporter, 'file_extension', False):
base, ext = os.path.splitext(self.output_base)
if ext == '.' + exporter.file_extension:
self.output_base = base
Matthias BUSSONNIER
add output flag to nbconvert...
r11801 notebook_name = self.output_base
Jonathan Frederic
Added writers and supporting code.
r11367 resources = {}
Jonathan Frederic
Inline user custom CSS if it's defined.
r16819 resources['profile_dir'] = self.profile_dir.location
Jonathan Frederic
Added writers and supporting code.
r11367 resources['unique_key'] = notebook_name
Jonathan Frederic
Move extracted files into their own subdir
r11631 resources['output_files_dir'] = '%s_files' % notebook_name
MinRK
tweak support-file output...
r11847 self.log.info("Support files will be in %s", os.path.join(resources['output_files_dir'], ''))
Jonathan Frederic
Added writers and supporting code.
r11367
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # Try to export
Jonathan Frederic
Merging done by hand
r11368 try:
MinRK
create single exporter in NotebookApp...
r11865 output, resources = exporter.from_filename(notebook_filename, resources=resources)
David Wolever
Catch ConversionExceptions in main nbconvert loop
r11703 except ConversionException as e:
MinRK
create single exporter in NotebookApp...
r11865 self.log.error("Error while converting '%s'", notebook_filename,
exc_info=True)
David Wolever
Exit with status 1, not -1
r11705 self.exit(1)
Jonathan Frederic
Moved nb conversion into its own method. Additional error handling.
r11400 else:
MinRK
support downgrading notebooks with nbconvert...
r18247 if 'output_suffix' in resources and not self.output_base:
notebook_name += resources['output_suffix']
MinRK
Avoid duplicate extension in nbconvert...
r17309 write_results = self.writer.write(output, resources, notebook_name=notebook_name)
Jonathan Frederic
Moved PDF logic into Post-Processor class
r11747
#Post-process if post processor has been defined.
Jonathan Frederic
Also renamed local variables in nbconvertapp
r12258 if hasattr(self, 'postprocessor') and self.postprocessor:
MinRK
Avoid duplicate extension in nbconvert...
r17309 self.postprocessor(write_results)
Jonathan Frederic
Moved nb conversion into its own method. Additional error handling.
r11400 conversion_success += 1
Jonathan Frederic
Added a space between pound and comments (@minrk request)
r11632 # If nothing was converted successfully, help the user.
Jonathan Frederic
Moved nb conversion into its own method. Additional error handling.
r11400 if conversion_success == 0:
Jonathan Frederic
Unnecessary
r11666 self.print_help()
Jonathan Frederic
Return failure, remove comments
r11667 sys.exit(-1)
damianavila
Redo after corrupted codebase.
r11772
Brian E. Granger
Adding initial version of nbconvert.
r11087 #-----------------------------------------------------------------------------
Brian E. Granger
Rename nbconvert entry point to the launch_new_instance.
r11092 # Main entry point
Brian E. Granger
Adding initial version of nbconvert.
r11087 #-----------------------------------------------------------------------------
MinRK
Application.launch_instance...
r11176 launch_new_instance = NbConvertApp.launch_instance