##// END OF EJS Templates
HTML-Slides -> Slides-Reveal
Jonathan Frederic -
Show More
@@ -0,0 +1,52 b''
1 """
2 Exporter that exports Basic HTML.
3 """
4
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
7 #
8 # Distributed under the terms of the Modified BSD License.
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 from IPython.utils.traitlets import Unicode
18
19 from IPython.nbconvert import transformers
20 from IPython.config import Config
21
22 from .exporter import Exporter
23
24 #-----------------------------------------------------------------------------
25 # Classes
26 #-----------------------------------------------------------------------------
27
28 class SlidesExporter(Exporter):
29 """
30 Exports slides
31 """
32
33 file_extension = Unicode(
34 'html', config=True,
35 help="Extension of the file that should be written to disk"
36 )
37
38 flavor = Unicode('reveal', config=True, help="""Flavor of the data format to
39 use. I.E. 'reveal'""")
40
41 @property
42 def default_config(self):
43 c = Config({
44 'CSSHTMLHeaderTransformer':{
45 'enabled':True
46 },
47 'RevealHelpTransformer':{
48 'enabled':True,
49 },
50 })
51 c.merge(super(SlidesExporter,self).default_config)
52 return c
@@ -0,0 +1,47 b''
1 """
2 Module with tests for slides.py
3 """
4
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
7 #
8 # Distributed under the terms of the Modified BSD License.
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 from .base import ExportersTestsBase
18 from ..slides import SlidesExporter
19
20 #-----------------------------------------------------------------------------
21 # Class
22 #-----------------------------------------------------------------------------
23
24 class TestSlidesExporter(ExportersTestsBase):
25 """Contains test functions for slides.py"""
26
27 def test_constructor(self):
28 """
29 Can a SlidesExporter be constructed?
30 """
31 SlidesExporter()
32
33
34 def test_export(self):
35 """
36 Can a SlidesExporter export something?
37 """
38 (output, resources) = SlidesExporter().from_filename(self._get_notebook())
39 assert len(output) > 0
40
41
42 def test_export_reveal(self):
43 """
44 Can a SlidesExporter export using the 'reveal' flavor?
45 """
46 (output, resources) = SlidesExporter(flavor='reveal').from_filename(self._get_notebook())
47 assert len(output) > 0
@@ -1,7 +1,8 b''
1 from .html import HTMLExporter
2 from .export import *
1 from .export import *
2 from .html import HTMLExporter
3 from .slides import SlidesExporter
3 from .exporter import Exporter
4 from .exporter import Exporter
4 from .latex import LatexExporter
5 from .latex import LatexExporter
5 from .markdown import MarkdownExporter
6 from .markdown import MarkdownExporter
6 from .python import PythonExporter
7 from .python import PythonExporter
7 from .rst import RSTExporter
8 from .rst import RSTExporter
@@ -1,195 +1,205 b''
1 """
1 """
2 Module containing single call export functions.
2 Module containing single call export functions.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
5 # Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 from functools import wraps
16 from functools import wraps
17
17
18 from IPython.nbformat.v3.nbbase import NotebookNode
18 from IPython.nbformat.v3.nbbase import NotebookNode
19 from IPython.config import Config
19 from IPython.config import Config
20
20
21 from .exporter import Exporter
21 from .exporter import Exporter
22 from .html import HTMLExporter
22 from .html import HTMLExporter
23 from .slides import SlidesExporter
23 from .latex import LatexExporter
24 from .latex import LatexExporter
24 from .markdown import MarkdownExporter
25 from .markdown import MarkdownExporter
25 from .python import PythonExporter
26 from .python import PythonExporter
26 from .rst import RSTExporter
27 from .rst import RSTExporter
27
28
28 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
29 # Classes
30 # Classes
30 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
31
32
32 def DocDecorator(f):
33 def DocDecorator(f):
33
34
34 #Set docstring of function
35 #Set docstring of function
35 f.__doc__ = f.__doc__ + """
36 f.__doc__ = f.__doc__ + """
36 nb : Notebook node
37 nb : Notebook node
37 config : config (optional, keyword arg)
38 config : config (optional, keyword arg)
38 User configuration instance.
39 User configuration instance.
39 resources : dict (optional, keyword arg)
40 resources : dict (optional, keyword arg)
40 Resources used in the conversion process.
41 Resources used in the conversion process.
41
42
42 Returns
43 Returns
43 ----------
44 ----------
44 tuple- output, resources, exporter_instance
45 tuple- output, resources, exporter_instance
45 output : str
46 output : str
46 Jinja 2 output. This is the resulting converted notebook.
47 Jinja 2 output. This is the resulting converted notebook.
47 resources : dictionary
48 resources : dictionary
48 Dictionary of resources used prior to and during the conversion
49 Dictionary of resources used prior to and during the conversion
49 process.
50 process.
50 exporter_instance : Exporter
51 exporter_instance : Exporter
51 Instance of the Exporter class used to export the document. Useful
52 Instance of the Exporter class used to export the document. Useful
52 to caller because it provides a 'file_extension' property which
53 to caller because it provides a 'file_extension' property which
53 specifies what extension the output should be saved as."""
54 specifies what extension the output should be saved as."""
54
55
55 @wraps(f)
56 @wraps(f)
56 def decorator(*args, **kwargs):
57 def decorator(*args, **kwargs):
57 return f(*args, **kwargs)
58 return f(*args, **kwargs)
58
59
59 return decorator
60 return decorator
60
61
61
62
62 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
63 # Functions
64 # Functions
64 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
65
66
66 __all__ = [
67 __all__ = [
67 'export',
68 'export',
68 'export_html',
69 'export_html',
69 'export_custom',
70 'export_custom',
71 'export_slides',
70 'export_latex',
72 'export_latex',
71 'export_markdown',
73 'export_markdown',
72 'export_python',
74 'export_python',
73 'export_rst',
75 'export_rst',
74 'export_by_name',
76 'export_by_name',
75 'get_export_names',
77 'get_export_names',
76 'ExporterNameError'
78 'ExporterNameError'
77 ]
79 ]
78
80
79
81
80 class ExporterNameError(NameError):
82 class ExporterNameError(NameError):
81 pass
83 pass
82
84
83
85
84 @DocDecorator
86 @DocDecorator
85 def export(exporter, nb, **kw):
87 def export(exporter, nb, **kw):
86 """
88 """
87 Export a notebook object using specific exporter class.
89 Export a notebook object using specific exporter class.
88
90
89 exporter : Exporter class type or instance
91 exporter : Exporter class type or instance
90 Class type or instance of the exporter that should be used. If the
92 Class type or instance of the exporter that should be used. If the
91 method initializes it's own instance of the class, it is ASSUMED that
93 method initializes it's own instance of the class, it is ASSUMED that
92 the class type provided exposes a constructor (__init__) with the same
94 the class type provided exposes a constructor (__init__) with the same
93 signature as the base Exporter class.
95 signature as the base Exporter class.
94 """
96 """
95
97
96 #Check arguments
98 #Check arguments
97 if exporter is None:
99 if exporter is None:
98 raise TypeError("Exporter is None")
100 raise TypeError("Exporter is None")
99 elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
101 elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
100 raise TypeError("exporter does not inherit from Exporter (base)")
102 raise TypeError("exporter does not inherit from Exporter (base)")
101 if nb is None:
103 if nb is None:
102 raise TypeError("nb is None")
104 raise TypeError("nb is None")
103
105
104 #Create the exporter
106 #Create the exporter
105 resources = kw.pop('resources', None)
107 resources = kw.pop('resources', None)
106 if isinstance(exporter, Exporter):
108 if isinstance(exporter, Exporter):
107 exporter_instance = exporter
109 exporter_instance = exporter
108 else:
110 else:
109 exporter_instance = exporter(**kw)
111 exporter_instance = exporter(**kw)
110
112
111 #Try to convert the notebook using the appropriate conversion function.
113 #Try to convert the notebook using the appropriate conversion function.
112 if isinstance(nb, NotebookNode):
114 if isinstance(nb, NotebookNode):
113 output, resources = exporter_instance.from_notebook_node(nb, resources)
115 output, resources = exporter_instance.from_notebook_node(nb, resources)
114 elif isinstance(nb, basestring):
116 elif isinstance(nb, basestring):
115 output, resources = exporter_instance.from_filename(nb, resources)
117 output, resources = exporter_instance.from_filename(nb, resources)
116 else:
118 else:
117 output, resources = exporter_instance.from_file(nb, resources)
119 output, resources = exporter_instance.from_file(nb, resources)
118 return output, resources
120 return output, resources
119
121
120
122
121 @DocDecorator
123 @DocDecorator
122 def export_custom(nb, **kw):
124 def export_custom(nb, **kw):
123 """
125 """
124 Export a notebook object to a custom format
126 Export a notebook object to a custom format
125 """
127 """
126 return export(Exporter, nb, **kw)
128 return export(Exporter, nb, **kw)
127
129
128
130
129 @DocDecorator
131 @DocDecorator
130 def export_html(nb, **kw):
132 def export_html(nb, **kw):
131 """
133 """
132 Export a notebook object to HTML
134 Export a notebook object to HTML
133 """
135 """
134 return export(HTMLExporter, nb, **kw)
136 return export(HTMLExporter, nb, **kw)
135
137
136
138
137 @DocDecorator
139 @DocDecorator
140 def export_slides(nb, **kw):
141 """
142 Export a notebook object to Slides
143 """
144 return export(SlidesExporter, nb, **kw)
145
146
147 @DocDecorator
138 def export_latex(nb, **kw):
148 def export_latex(nb, **kw):
139 """
149 """
140 Export a notebook object to LaTeX
150 Export a notebook object to LaTeX
141 """
151 """
142 return export(LatexExporter, nb, **kw)
152 return export(LatexExporter, nb, **kw)
143
153
144
154
145 @DocDecorator
155 @DocDecorator
146 def export_markdown(nb, **kw):
156 def export_markdown(nb, **kw):
147 """
157 """
148 Export a notebook object to Markdown
158 Export a notebook object to Markdown
149 """
159 """
150 return export(MarkdownExporter, nb, **kw)
160 return export(MarkdownExporter, nb, **kw)
151
161
152
162
153 @DocDecorator
163 @DocDecorator
154 def export_python(nb, **kw):
164 def export_python(nb, **kw):
155 """
165 """
156 Export a notebook object to Python
166 Export a notebook object to Python
157 """
167 """
158 return export(PythonExporter, nb, **kw)
168 return export(PythonExporter, nb, **kw)
159
169
160
170
161 @DocDecorator
171 @DocDecorator
162 def export_rst(nb, **kw):
172 def export_rst(nb, **kw):
163 """
173 """
164 Export a notebook object to reStructuredText
174 Export a notebook object to reStructuredText
165 """
175 """
166 return export(RSTExporter, nb, **kw)
176 return export(RSTExporter, nb, **kw)
167
177
168
178
169 @DocDecorator
179 @DocDecorator
170 def export_by_name(format_name, nb, **kw):
180 def export_by_name(format_name, nb, **kw):
171 """
181 """
172 Export a notebook object to a template type by its name. Reflection
182 Export a notebook object to a template type by its name. Reflection
173 (Inspect) is used to find the template's corresponding explicit export
183 (Inspect) is used to find the template's corresponding explicit export
174 method defined in this module. That method is then called directly.
184 method defined in this module. That method is then called directly.
175
185
176 format_name : str
186 format_name : str
177 Name of the template style to export to.
187 Name of the template style to export to.
178 """
188 """
179
189
180 function_name = "export_" + format_name.lower()
190 function_name = "export_" + format_name.lower()
181
191
182 if function_name in globals():
192 if function_name in globals():
183 return globals()[function_name](nb, **kw)
193 return globals()[function_name](nb, **kw)
184 else:
194 else:
185 raise ExporterNameError("template for `%s` not found" % function_name)
195 raise ExporterNameError("template for `%s` not found" % function_name)
186
196
187
197
188 def get_export_names():
198 def get_export_names():
189 "Return a list of the currently supported export targets"
199 "Return a list of the currently supported export targets"
190 # grab everything after 'export_'
200 # grab everything after 'export_'
191 l = [x[len('export_'):] for x in __all__ if x.startswith('export_')]
201 l = [x[len('export_'):] for x in __all__ if x.startswith('export_')]
192
202
193 # filter out the one method that is not a template
203 # filter out the one method that is not a template
194 l = [x for x in l if 'by_name' not in x]
204 l = [x for x in l if 'by_name' not in x]
195 return sorted(l)
205 return sorted(l)
@@ -1,64 +1,56 b''
1 """
1 """
2 Module with tests for basichtml.py
2 Module with tests for html.py
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from .base import ExportersTestsBase
17 from .base import ExportersTestsBase
18 from ..html import HTMLExporter
18 from ..html import HTMLExporter
19 from IPython.testing.decorators import onlyif_cmds_exist
19 from IPython.testing.decorators import onlyif_cmds_exist
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Class
22 # Class
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class TestHTMLExporter(ExportersTestsBase):
25 class TestHTMLExporter(ExportersTestsBase):
26 """Contains test functions for basichtml.py"""
26 """Contains test functions for html.py"""
27
27
28 def test_constructor(self):
28 def test_constructor(self):
29 """
29 """
30 Can a HTMLExporter be constructed?
30 Can a HTMLExporter be constructed?
31 """
31 """
32 HTMLExporter()
32 HTMLExporter()
33
33
34 @onlyif_cmds_exist('pandoc')
34 @onlyif_cmds_exist('pandoc')
35 def test_export(self):
35 def test_export(self):
36 """
36 """
37 Can a HTMLExporter export something?
37 Can a HTMLExporter export something?
38 """
38 """
39 (output, resources) = HTMLExporter().from_filename(self._get_notebook())
39 (output, resources) = HTMLExporter().from_filename(self._get_notebook())
40 assert len(output) > 0
40 assert len(output) > 0
41
41
42
42
43 def test_export_basic(self):
43 def test_export_basic(self):
44 """
44 """
45 Can a HTMLExporter export using the 'basic' flavor?
45 Can a HTMLExporter export using the 'basic' flavor?
46 """
46 """
47 (output, resources) = HTMLExporter(flavor='basic').from_filename(self._get_notebook())
47 (output, resources) = HTMLExporter(flavor='basic').from_filename(self._get_notebook())
48 assert len(output) > 0
48 assert len(output) > 0
49
49
50
50
51 def test_export_full(self):
51 def test_export_full(self):
52 """
52 """
53 Can a HTMLExporter export using the 'full' flavor?
53 Can a HTMLExporter export using the 'full' flavor?
54 """
54 """
55 (output, resources) = HTMLExporter(flavor='full').from_filename(self._get_notebook())
55 (output, resources) = HTMLExporter(flavor='full').from_filename(self._get_notebook())
56 assert len(output) > 0
56 assert len(output) > 0
57
58
59 def test_export_reveal(self):
60 """
61 Can a HTMLExporter export using the 'reveal' flavor?
62 """
63 (output, resources) = HTMLExporter(flavor='reveal').from_filename(self._get_notebook())
64 assert len(output) > 0 No newline at end of file
@@ -1,259 +1,259 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """NBConvert is a utility for conversion of .ipynb files.
2 """NBConvert is a utility for conversion of .ipynb files.
3
3
4 Command-line interface for the NbConvert conversion utility.
4 Command-line interface for the NbConvert conversion utility.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 #Copyright (c) 2013, the IPython Development Team.
7 #Copyright (c) 2013, the IPython Development Team.
8 #
8 #
9 #Distributed under the terms of the Modified BSD License.
9 #Distributed under the terms of the Modified BSD License.
10 #
10 #
11 #The full license is in the file COPYING.txt, distributed with this software.
11 #The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 #Imports
15 #Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 # Stdlib imports
18 # Stdlib imports
19 from __future__ import print_function
19 from __future__ import print_function
20 import sys
20 import sys
21 import os
21 import os
22 import glob
22 import glob
23
23
24 # From IPython
24 # From IPython
25 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
25 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
26 from IPython.config import catch_config_error, Configurable
26 from IPython.config import catch_config_error, Configurable
27 from IPython.utils.traitlets import (
27 from IPython.utils.traitlets import (
28 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
28 Unicode, List, Instance, DottedObjectName, Type, CaselessStrEnum,
29 )
29 )
30 from IPython.utils.importstring import import_item
30 from IPython.utils.importstring import import_item
31
31
32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
32 from .exporters.export import export_by_name, get_export_names, ExporterNameError
33 from IPython.nbconvert import exporters, transformers, writers
33 from IPython.nbconvert import exporters, transformers, writers
34 from .utils.base import NbConvertBase
34 from .utils.base import NbConvertBase
35 from .utils.exceptions import ConversionException
35 from .utils.exceptions import ConversionException
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 #Classes and functions
38 #Classes and functions
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 nbconvert_aliases = {}
41 nbconvert_aliases = {}
42 nbconvert_aliases.update(base_aliases)
42 nbconvert_aliases.update(base_aliases)
43 nbconvert_aliases.update({
43 nbconvert_aliases.update({
44 'to' : 'NbConvertApp.export_format',
44 'to' : 'NbConvertApp.export_format',
45 'flavor' : 'Exporter.flavor',
45 'flavor' : 'Exporter.flavor',
46 'template' : 'Exporter.template_file',
46 'template' : 'Exporter.template_file',
47 'notebooks' : 'NbConvertApp.notebooks',
47 'notebooks' : 'NbConvertApp.notebooks',
48 'writer' : 'NbConvertApp.writer_class',
48 'writer' : 'NbConvertApp.writer_class',
49 })
49 })
50
50
51 nbconvert_flags = {}
51 nbconvert_flags = {}
52 nbconvert_flags.update(base_flags)
52 nbconvert_flags.update(base_flags)
53 nbconvert_flags.update({
53 nbconvert_flags.update({
54 'stdout' : (
54 'stdout' : (
55 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
55 {'NbConvertApp' : {'writer_class' : "StdoutWriter"}},
56 "Write notebook output to stdout instead of files."
56 "Write notebook output to stdout instead of files."
57 ),
57 ),
58
58
59 'pdf' : (
59 'pdf' : (
60 {'NbConvertApp' : {'writer_class' : "PDFWriter"}},
60 {'NbConvertApp' : {'writer_class' : "PDFWriter"}},
61 "Compile notebook output to a PDF."
61 "Compile notebook output to a PDF."
62 )
62 )
63 })
63 })
64
64
65
65
66 class NbConvertApp(BaseIPythonApplication):
66 class NbConvertApp(BaseIPythonApplication):
67 """Application used to convert to and from notebook file type (*.ipynb)"""
67 """Application used to convert to and from notebook file type (*.ipynb)"""
68
68
69 name = 'ipython-nbconvert'
69 name = 'ipython-nbconvert'
70 aliases = nbconvert_aliases
70 aliases = nbconvert_aliases
71 flags = nbconvert_flags
71 flags = nbconvert_flags
72
72
73 def _classes_default(self):
73 def _classes_default(self):
74 classes = [NbConvertBase]
74 classes = [NbConvertBase]
75 for pkg in (exporters, transformers, writers):
75 for pkg in (exporters, transformers, writers):
76 for name in dir(pkg):
76 for name in dir(pkg):
77 cls = getattr(pkg, name)
77 cls = getattr(pkg, name)
78 if isinstance(cls, type) and issubclass(cls, Configurable):
78 if isinstance(cls, type) and issubclass(cls, Configurable):
79 classes.append(cls)
79 classes.append(cls)
80 return classes
80 return classes
81
81
82 description = Unicode(
82 description = Unicode(
83 u"""This application is used to convert notebook files (*.ipynb)
83 u"""This application is used to convert notebook files (*.ipynb)
84 to various other formats.""")
84 to various other formats.""")
85
85
86 examples = Unicode(u"""
86 examples = Unicode(u"""
87 The simplest way to use nbconvert is
87 The simplest way to use nbconvert is
88
88
89 > ipython nbconvert mynotebook.ipynb
89 > ipython nbconvert mynotebook.ipynb
90
90
91 which will convert mynotebook.ipynb to the default format (probably HTML).
91 which will convert mynotebook.ipynb to the default format (probably HTML).
92
92
93 You can specify the export format with `--to`.
93 You can specify the export format with `--to`.
94 Options include {0}
94 Options include {0}
95
95
96 > ipython nbconvert --to latex mynotebook.ipnynb
96 > ipython nbconvert --to latex mynotebook.ipnynb
97
97
98 Both HTML and LaTeX support multiple flavors of output. LaTeX includes
98 Both HTML and LaTeX support multiple flavors of output. LaTeX includes
99 'basic', 'book', and 'article'. HTML includes 'basic', 'full', and
99 'basic', 'book', and 'article'. HTML includes 'basic' and 'full'. You
100 'reveal'. You can specify the flavor of the format used.
100 can specify the flavor of the format used.
101
101
102 > ipython nbconvert --to html --flavor reveal mynotebook.ipnynb
102 > ipython nbconvert --to html --flavor reveal mynotebook.ipnynb
103
103
104 You can also pipe the output to stdout, rather than a file
104 You can also pipe the output to stdout, rather than a file
105
105
106 > ipython nbconvert mynotebook.ipynb --stdout
106 > ipython nbconvert mynotebook.ipynb --stdout
107
107
108 or to a PDF
108 or to a PDF
109
109
110 > ipython nbconvert mynotebook.ipynb --pdf
110 > ipython nbconvert mynotebook.ipynb --pdf
111
111
112 Multiple notebooks can be given at the command line in a couple of
112 Multiple notebooks can be given at the command line in a couple of
113 different ways:
113 different ways:
114
114
115 > ipython nbconvert notebook*.ipynb
115 > ipython nbconvert notebook*.ipynb
116 > ipython nbconvert notebook1.ipynb notebook2.ipynb
116 > ipython nbconvert notebook1.ipynb notebook2.ipynb
117
117
118 or you can specify the notebooks list in a config file, containing::
118 or you can specify the notebooks list in a config file, containing::
119
119
120 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
120 c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
121
121
122 > ipython nbconvert --config mycfg.py
122 > ipython nbconvert --config mycfg.py
123 """.format(get_export_names()))
123 """.format(get_export_names()))
124 # Writer specific variables
124 # Writer specific variables
125 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
125 writer = Instance('IPython.nbconvert.writers.base.WriterBase',
126 help="""Instance of the writer class used to write the
126 help="""Instance of the writer class used to write the
127 results of the conversion.""")
127 results of the conversion.""")
128 writer_class = DottedObjectName('FilesWriter', config=True,
128 writer_class = DottedObjectName('FilesWriter', config=True,
129 help="""Writer class used to write the
129 help="""Writer class used to write the
130 results of the conversion""")
130 results of the conversion""")
131 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
131 writer_aliases = {'FilesWriter': 'IPython.nbconvert.writers.files.FilesWriter',
132 'PDFWriter': 'IPython.nbconvert.writers.pdf.PDFWriter',
132 'PDFWriter': 'IPython.nbconvert.writers.pdf.PDFWriter',
133 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
133 'DebugWriter': 'IPython.nbconvert.writers.debug.DebugWriter',
134 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
134 'StdoutWriter': 'IPython.nbconvert.writers.stdout.StdoutWriter'}
135 writer_factory = Type()
135 writer_factory = Type()
136
136
137 def _writer_class_changed(self, name, old, new):
137 def _writer_class_changed(self, name, old, new):
138 if new in self.writer_aliases:
138 if new in self.writer_aliases:
139 new = self.writer_aliases[new]
139 new = self.writer_aliases[new]
140 self.writer_factory = import_item(new)
140 self.writer_factory = import_item(new)
141
141
142
142
143 # Other configurable variables
143 # Other configurable variables
144 export_format = CaselessStrEnum(get_export_names(),
144 export_format = CaselessStrEnum(get_export_names(),
145 default_value="html",
145 default_value="html",
146 config=True,
146 config=True,
147 help="""The export format to be used."""
147 help="""The export format to be used."""
148 )
148 )
149
149
150 notebooks = List([], config=True, help="""List of notebooks to convert.
150 notebooks = List([], config=True, help="""List of notebooks to convert.
151 Wildcards are supported.
151 Wildcards are supported.
152 Filenames passed positionally will be added to the list.
152 Filenames passed positionally will be added to the list.
153 """)
153 """)
154
154
155 @catch_config_error
155 @catch_config_error
156 def initialize(self, argv=None):
156 def initialize(self, argv=None):
157 super(NbConvertApp, self).initialize(argv)
157 super(NbConvertApp, self).initialize(argv)
158 self.init_syspath()
158 self.init_syspath()
159 self.init_notebooks()
159 self.init_notebooks()
160 self.init_writer()
160 self.init_writer()
161
161
162
162
163 def init_syspath(self):
163 def init_syspath(self):
164 """
164 """
165 Add the cwd to the sys.path ($PYTHONPATH)
165 Add the cwd to the sys.path ($PYTHONPATH)
166 """
166 """
167 sys.path.insert(0, os.getcwd())
167 sys.path.insert(0, os.getcwd())
168
168
169
169
170 def init_notebooks(self):
170 def init_notebooks(self):
171 """Construct the list of notebooks.
171 """Construct the list of notebooks.
172 If notebooks are passed on the command-line,
172 If notebooks are passed on the command-line,
173 they override notebooks specified in config files.
173 they override notebooks specified in config files.
174 Glob each notebook to replace notebook patterns with filenames.
174 Glob each notebook to replace notebook patterns with filenames.
175 """
175 """
176
176
177 # Specifying notebooks on the command-line overrides (rather than adds)
177 # Specifying notebooks on the command-line overrides (rather than adds)
178 # the notebook list
178 # the notebook list
179 if self.extra_args:
179 if self.extra_args:
180 patterns = self.extra_args
180 patterns = self.extra_args
181 else:
181 else:
182 patterns = self.notebooks
182 patterns = self.notebooks
183
183
184 # Use glob to replace all the notebook patterns with filenames.
184 # Use glob to replace all the notebook patterns with filenames.
185 filenames = []
185 filenames = []
186 for pattern in patterns:
186 for pattern in patterns:
187
187
188 # Use glob to find matching filenames. Allow the user to convert
188 # Use glob to find matching filenames. Allow the user to convert
189 # notebooks without having to type the extension.
189 # notebooks without having to type the extension.
190 globbed_files = glob.glob(pattern)
190 globbed_files = glob.glob(pattern)
191 globbed_files.extend(glob.glob(pattern + '.ipynb'))
191 globbed_files.extend(glob.glob(pattern + '.ipynb'))
192
192
193 for filename in globbed_files:
193 for filename in globbed_files:
194 if not filename in filenames:
194 if not filename in filenames:
195 filenames.append(filename)
195 filenames.append(filename)
196 self.notebooks = filenames
196 self.notebooks = filenames
197
197
198 def init_writer(self):
198 def init_writer(self):
199 """
199 """
200 Initialize the writer (which is stateless)
200 Initialize the writer (which is stateless)
201 """
201 """
202 self._writer_class_changed(None, self.writer_class, self.writer_class)
202 self._writer_class_changed(None, self.writer_class, self.writer_class)
203 self.writer = self.writer_factory(parent=self)
203 self.writer = self.writer_factory(parent=self)
204
204
205 def start(self):
205 def start(self):
206 """
206 """
207 Ran after initialization completed
207 Ran after initialization completed
208 """
208 """
209 super(NbConvertApp, self).start()
209 super(NbConvertApp, self).start()
210 self.convert_notebooks()
210 self.convert_notebooks()
211
211
212 def convert_notebooks(self):
212 def convert_notebooks(self):
213 """
213 """
214 Convert the notebooks in the self.notebook traitlet
214 Convert the notebooks in the self.notebook traitlet
215 """
215 """
216 # Export each notebook
216 # Export each notebook
217 conversion_success = 0
217 conversion_success = 0
218 for notebook_filename in self.notebooks:
218 for notebook_filename in self.notebooks:
219
219
220 # Get a unique key for the notebook and set it in the resources object.
220 # Get a unique key for the notebook and set it in the resources object.
221 basename = os.path.basename(notebook_filename)
221 basename = os.path.basename(notebook_filename)
222 notebook_name = basename[:basename.rfind('.')]
222 notebook_name = basename[:basename.rfind('.')]
223 resources = {}
223 resources = {}
224 resources['unique_key'] = notebook_name
224 resources['unique_key'] = notebook_name
225 resources['output_files_dir'] = '%s_files' % notebook_name
225 resources['output_files_dir'] = '%s_files' % notebook_name
226
226
227 # Try to export
227 # Try to export
228 try:
228 try:
229 output, resources = export_by_name(self.export_format,
229 output, resources = export_by_name(self.export_format,
230 notebook_filename,
230 notebook_filename,
231 resources=resources,
231 resources=resources,
232 config=self.config)
232 config=self.config)
233 except ExporterNameError as e:
233 except ExporterNameError as e:
234 print("Error while converting '%s': '%s' exporter not found."
234 print("Error while converting '%s': '%s' exporter not found."
235 %(notebook_filename, self.export_format),
235 %(notebook_filename, self.export_format),
236 file=sys.stderr)
236 file=sys.stderr)
237 print("Known exporters are:",
237 print("Known exporters are:",
238 "\n\t" + "\n\t".join(get_export_names()),
238 "\n\t" + "\n\t".join(get_export_names()),
239 file=sys.stderr)
239 file=sys.stderr)
240 self.exit(1)
240 self.exit(1)
241 except ConversionException as e:
241 except ConversionException as e:
242 print("Error while converting '%s': %s" %(notebook_filename, e),
242 print("Error while converting '%s': %s" %(notebook_filename, e),
243 file=sys.stderr)
243 file=sys.stderr)
244 self.exit(1)
244 self.exit(1)
245 else:
245 else:
246 self.writer.write(output, resources, notebook_name=notebook_name)
246 self.writer.write(output, resources, notebook_name=notebook_name)
247 conversion_success += 1
247 conversion_success += 1
248
248
249 # If nothing was converted successfully, help the user.
249 # If nothing was converted successfully, help the user.
250 if conversion_success == 0:
250 if conversion_success == 0:
251 self.print_help()
251 self.print_help()
252 sys.exit(-1)
252 sys.exit(-1)
253
253
254
254
255 #-----------------------------------------------------------------------------
255 #-----------------------------------------------------------------------------
256 # Main entry point
256 # Main entry point
257 #-----------------------------------------------------------------------------
257 #-----------------------------------------------------------------------------
258
258
259 launch_new_instance = NbConvertApp.launch_instance
259 launch_new_instance = NbConvertApp.launch_instance
1 NO CONTENT: file renamed from IPython/nbconvert/templates/html_reveal.tpl to IPython/nbconvert/templates/slides_reveal.tpl
NO CONTENT: file renamed from IPython/nbconvert/templates/html_reveal.tpl to IPython/nbconvert/templates/slides_reveal.tpl
@@ -1,135 +1,135 b''
1 """
1 """
2 Contains tests for the nbconvertapp
2 Contains tests for the nbconvertapp
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 #Distributed under the terms of the Modified BSD License.
7 #Distributed under the terms of the Modified BSD License.
8 #
8 #
9 #The full license is in the file COPYING.txt, distributed with this software.
9 #The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import os
16 import os
17 from .base import TestsBase
17 from .base import TestsBase
18
18
19 from IPython.utils import py3compat
19 from IPython.utils import py3compat
20
20
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Constants
23 # Constants
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 # Define ipython commandline name
26 # Define ipython commandline name
27 if py3compat.PY3:
27 if py3compat.PY3:
28 IPYTHON = 'ipython3'
28 IPYTHON = 'ipython3'
29 else:
29 else:
30 IPYTHON = 'ipython'
30 IPYTHON = 'ipython'
31
31
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Classes and functions
34 # Classes and functions
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 class TestNbConvertApp(TestsBase):
37 class TestNbConvertApp(TestsBase):
38 """Collection of NbConvertApp tests"""
38 """Collection of NbConvertApp tests"""
39
39
40
40
41 def test_notebook_help(self):
41 def test_notebook_help(self):
42 """
42 """
43 Will help show if no notebooks are specified?
43 Will help show if no notebooks are specified?
44 """
44 """
45 with self.create_temp_cwd():
45 with self.create_temp_cwd():
46 assert "see '--help-all'" in self.call([IPYTHON, 'nbconvert'])
46 assert "see '--help-all'" in self.call([IPYTHON, 'nbconvert'])
47
47
48
48
49 def test_glob(self):
49 def test_glob(self):
50 """
50 """
51 Do search patterns work for notebook names?
51 Do search patterns work for notebook names?
52 """
52 """
53 with self.create_temp_cwd(['notebook*.ipynb']):
53 with self.create_temp_cwd(['notebook*.ipynb']):
54 assert not 'error' in self.call([IPYTHON, 'nbconvert',
54 assert not 'error' in self.call([IPYTHON, 'nbconvert',
55 '--to="python"', '--notebooks=["*.ipynb"]']).lower()
55 '--to="python"', '--notebooks=["*.ipynb"]']).lower()
56 assert os.path.isfile('notebook1.py')
56 assert os.path.isfile('notebook1.py')
57 assert os.path.isfile('notebook2.py')
57 assert os.path.isfile('notebook2.py')
58
58
59
59
60 def test_glob_subdir(self):
60 def test_glob_subdir(self):
61 """
61 """
62 Do search patterns work for subdirectory notebook names?
62 Do search patterns work for subdirectory notebook names?
63 """
63 """
64 with self.create_temp_cwd() as cwd:
64 with self.create_temp_cwd() as cwd:
65 self.copy_files_to(['notebook*.ipynb'], 'subdir/')
65 self.copy_files_to(['notebook*.ipynb'], 'subdir/')
66 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
66 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
67 '--notebooks=["%s"]' % os.path.join('subdir', '*.ipynb')]).lower()
67 '--notebooks=["%s"]' % os.path.join('subdir', '*.ipynb')]).lower()
68 assert os.path.isfile('notebook1.py')
68 assert os.path.isfile('notebook1.py')
69 assert os.path.isfile('notebook2.py')
69 assert os.path.isfile('notebook2.py')
70
70
71
71
72 def test_explicit(self):
72 def test_explicit(self):
73 """
73 """
74 Do explicit notebook names work?
74 Do explicit notebook names work?
75 """
75 """
76 with self.create_temp_cwd(['notebook*.ipynb']):
76 with self.create_temp_cwd(['notebook*.ipynb']):
77 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
77 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
78 '--notebooks=["notebook2.ipynb"]']).lower()
78 '--notebooks=["notebook2.ipynb"]']).lower()
79 assert not os.path.isfile('notebook1.py')
79 assert not os.path.isfile('notebook1.py')
80 assert os.path.isfile('notebook2.py')
80 assert os.path.isfile('notebook2.py')
81
81
82
82
83 def test_flavor(self):
83 def test_flavor(self):
84 """
84 """
85 Do explicit notebook names work?
85 Do export flavors work?
86 """
86 """
87 with self.create_temp_cwd(['notebook*.ipynb']):
87 with self.create_temp_cwd(['notebook*.ipynb']):
88 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="html"',
88 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="slides"',
89 '--notebooks=["notebook2.ipynb"]', '--flavor="reveal"']).lower()
89 '--notebooks=["notebook2.ipynb"]', '--flavor="reveal"']).lower()
90 assert os.path.isfile('notebook2.html')
90 assert os.path.isfile('notebook2.html')
91 with open('notebook2.html') as f:
91 with open('notebook2.html') as f:
92 assert '/reveal.css' in f.read()
92 assert '/reveal.css' in f.read()
93
93
94
94
95 def test_glob_explicit(self):
95 def test_glob_explicit(self):
96 """
96 """
97 Can a search pattern be used along with matching explicit notebook names?
97 Can a search pattern be used along with matching explicit notebook names?
98 """
98 """
99 with self.create_temp_cwd(['notebook*.ipynb']):
99 with self.create_temp_cwd(['notebook*.ipynb']):
100 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
100 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
101 '--notebooks=["*.ipynb", "notebook1.ipynb", "notebook2.ipynb"]']).lower()
101 '--notebooks=["*.ipynb", "notebook1.ipynb", "notebook2.ipynb"]']).lower()
102 assert os.path.isfile('notebook1.py')
102 assert os.path.isfile('notebook1.py')
103 assert os.path.isfile('notebook2.py')
103 assert os.path.isfile('notebook2.py')
104
104
105
105
106 def test_explicit_glob(self):
106 def test_explicit_glob(self):
107 """
107 """
108 Can explicit notebook names be used and then a matching search pattern?
108 Can explicit notebook names be used and then a matching search pattern?
109 """
109 """
110 with self.create_temp_cwd(['notebook*.ipynb']):
110 with self.create_temp_cwd(['notebook*.ipynb']):
111 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
111 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--to="python"',
112 '--notebooks=["notebook1.ipynb", "notebook2.ipynb", "*.ipynb"]']).lower()
112 '--notebooks=["notebook1.ipynb", "notebook2.ipynb", "*.ipynb"]']).lower()
113 assert os.path.isfile('notebook1.py')
113 assert os.path.isfile('notebook1.py')
114 assert os.path.isfile('notebook2.py')
114 assert os.path.isfile('notebook2.py')
115
115
116
116
117 def test_default_config(self):
117 def test_default_config(self):
118 """
118 """
119 Does the default config work?
119 Does the default config work?
120 """
120 """
121 with self.create_temp_cwd(['notebook*.ipynb', 'ipython_nbconvert_config.py']):
121 with self.create_temp_cwd(['notebook*.ipynb', 'ipython_nbconvert_config.py']):
122 assert not 'error' in self.call([IPYTHON, 'nbconvert']).lower()
122 assert not 'error' in self.call([IPYTHON, 'nbconvert']).lower()
123 assert os.path.isfile('notebook1.py')
123 assert os.path.isfile('notebook1.py')
124 assert not os.path.isfile('notebook2.py')
124 assert not os.path.isfile('notebook2.py')
125
125
126
126
127 def test_override_config(self):
127 def test_override_config(self):
128 """
128 """
129 Can the default config be overriden?
129 Can the default config be overriden?
130 """
130 """
131 with self.create_temp_cwd(['notebook*.ipynb', 'ipython_nbconvert_config.py',
131 with self.create_temp_cwd(['notebook*.ipynb', 'ipython_nbconvert_config.py',
132 'override.py']):
132 'override.py']):
133 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--config="override.py"']).lower()
133 assert not 'error' in self.call([IPYTHON, 'nbconvert', '--config="override.py"']).lower()
134 assert not os.path.isfile('notebook1.py')
134 assert not os.path.isfile('notebook1.py')
135 assert os.path.isfile('notebook2.py')
135 assert os.path.isfile('notebook2.py')
General Comments 0
You need to be logged in to leave comments. Login now