##// END OF EJS Templates
jupyter_nbconvert is now nbconvert...
Min RK -
Show More
@@ -1,19 +1,19 b''
1 1 """
2 2 Shim to maintain backwards compatibility with old IPython.nbconvert imports.
3 3 """
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import sys
8 8 from warnings import warn
9 9
10 10 warn("The `IPython.nbconvert` package has been deprecated. "
11 11 "You should import from ipython_nbconvert instead.")
12 12
13 13 from IPython.utils.shimmodule import ShimModule
14 14
15 15 # Unconditionally insert the shim into sys.modules so that further import calls
16 16 # trigger the custom attribute access above
17 17
18 18 sys.modules['IPython.nbconvert'] = ShimModule(
19 src='IPython.nbconvert', mirror='jupyter_nbconvert')
19 src='IPython.nbconvert', mirror='nbconvert')
@@ -1,374 +1,374 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6 """
7 7
8 8 # Copyright (c) IPython Development Team.
9 9 # Distributed under the terms of the Modified BSD License.
10 10
11 11 from __future__ import absolute_import
12 12 from __future__ import print_function
13 13
14 14 import logging
15 15 import os
16 16 import sys
17 17
18 18 from traitlets.config.loader import Config
19 19 from traitlets.config.application import boolean_flag, catch_config_error, Application
20 20 from IPython.core import release
21 21 from IPython.core import usage
22 22 from IPython.core.completer import IPCompleter
23 23 from IPython.core.crashhandler import CrashHandler
24 24 from IPython.core.formatters import PlainTextFormatter
25 25 from IPython.core.history import HistoryManager
26 26 from IPython.core.prompts import PromptManager
27 27 from IPython.core.application import (
28 28 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
29 29 )
30 30 from IPython.core.magics import ScriptMagics
31 31 from IPython.core.shellapp import (
32 32 InteractiveShellApp, shell_flags, shell_aliases
33 33 )
34 34 from IPython.extensions.storemagic import StoreMagics
35 35 from IPython.terminal.interactiveshell import TerminalInteractiveShell
36 36 from IPython.utils import warn
37 37 from IPython.paths import get_ipython_dir
38 38 from traitlets import (
39 39 Bool, List, Dict,
40 40 )
41 41
42 42 #-----------------------------------------------------------------------------
43 43 # Globals, utilities and helpers
44 44 #-----------------------------------------------------------------------------
45 45
46 46 _examples = """
47 47 ipython --matplotlib # enable matplotlib integration
48 48 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
49 49
50 50 ipython --log-level=DEBUG # set logging to DEBUG
51 51 ipython --profile=foo # start with profile foo
52 52
53 53 ipython qtconsole # start the qtconsole GUI application
54 54 ipython help qtconsole # show the help for the qtconsole subcmd
55 55
56 56 ipython console # start the terminal-based console application
57 57 ipython help console # show the help for the console subcmd
58 58
59 59 ipython notebook # start the IPython notebook
60 60 ipython help notebook # show the help for the notebook subcmd
61 61
62 62 ipython profile create foo # create profile foo w/ default config files
63 63 ipython help profile # show the help for the profile subcmd
64 64
65 65 ipython locate # print the path to the IPython directory
66 66 ipython locate profile foo # print the path to the directory for profile `foo`
67 67
68 68 ipython nbconvert # convert notebooks to/from other formats
69 69 """
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Crash handler for this application
73 73 #-----------------------------------------------------------------------------
74 74
75 75 class IPAppCrashHandler(CrashHandler):
76 76 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
77 77
78 78 def __init__(self, app):
79 79 contact_name = release.author
80 80 contact_email = release.author_email
81 81 bug_tracker = 'https://github.com/ipython/ipython/issues'
82 82 super(IPAppCrashHandler,self).__init__(
83 83 app, contact_name, contact_email, bug_tracker
84 84 )
85 85
86 86 def make_report(self,traceback):
87 87 """Return a string containing a crash report."""
88 88
89 89 sec_sep = self.section_sep
90 90 # Start with parent report
91 91 report = [super(IPAppCrashHandler, self).make_report(traceback)]
92 92 # Add interactive-specific info we may have
93 93 rpt_add = report.append
94 94 try:
95 95 rpt_add(sec_sep+"History of session input:")
96 96 for line in self.app.shell.user_ns['_ih']:
97 97 rpt_add(line)
98 98 rpt_add('\n*** Last line of input (may not be in above history):\n')
99 99 rpt_add(self.app.shell._last_input_line+'\n')
100 100 except:
101 101 pass
102 102
103 103 return ''.join(report)
104 104
105 105 #-----------------------------------------------------------------------------
106 106 # Aliases and Flags
107 107 #-----------------------------------------------------------------------------
108 108 flags = dict(base_flags)
109 109 flags.update(shell_flags)
110 110 frontend_flags = {}
111 111 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
112 112 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
113 113 'Turn on auto editing of files with syntax errors.',
114 114 'Turn off auto editing of files with syntax errors.'
115 115 )
116 116 addflag('banner', 'TerminalIPythonApp.display_banner',
117 117 "Display a banner upon starting IPython.",
118 118 "Don't display a banner upon starting IPython."
119 119 )
120 120 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
121 121 """Set to confirm when you try to exit IPython with an EOF (Control-D
122 122 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
123 123 you can force a direct exit without any confirmation.""",
124 124 "Don't prompt the user when exiting."
125 125 )
126 126 addflag('term-title', 'TerminalInteractiveShell.term_title',
127 127 "Enable auto setting the terminal title.",
128 128 "Disable auto setting the terminal title."
129 129 )
130 130 classic_config = Config()
131 131 classic_config.InteractiveShell.cache_size = 0
132 132 classic_config.PlainTextFormatter.pprint = False
133 133 classic_config.PromptManager.in_template = '>>> '
134 134 classic_config.PromptManager.in2_template = '... '
135 135 classic_config.PromptManager.out_template = ''
136 136 classic_config.InteractiveShell.separate_in = ''
137 137 classic_config.InteractiveShell.separate_out = ''
138 138 classic_config.InteractiveShell.separate_out2 = ''
139 139 classic_config.InteractiveShell.colors = 'NoColor'
140 140 classic_config.InteractiveShell.xmode = 'Plain'
141 141
142 142 frontend_flags['classic']=(
143 143 classic_config,
144 144 "Gives IPython a similar feel to the classic Python prompt."
145 145 )
146 146 # # log doesn't make so much sense this way anymore
147 147 # paa('--log','-l',
148 148 # action='store_true', dest='InteractiveShell.logstart',
149 149 # help="Start logging to the default log file (./ipython_log.py).")
150 150 #
151 151 # # quick is harder to implement
152 152 frontend_flags['quick']=(
153 153 {'TerminalIPythonApp' : {'quick' : True}},
154 154 "Enable quick startup with no config files."
155 155 )
156 156
157 157 frontend_flags['i'] = (
158 158 {'TerminalIPythonApp' : {'force_interact' : True}},
159 159 """If running code from the command line, become interactive afterwards."""
160 160 )
161 161 flags.update(frontend_flags)
162 162
163 163 aliases = dict(base_aliases)
164 164 aliases.update(shell_aliases)
165 165
166 166 #-----------------------------------------------------------------------------
167 167 # Main classes and functions
168 168 #-----------------------------------------------------------------------------
169 169
170 170
171 171 class LocateIPythonApp(BaseIPythonApplication):
172 172 description = """print the path to the IPython dir"""
173 173 subcommands = Dict(dict(
174 174 profile=('IPython.core.profileapp.ProfileLocate',
175 175 "print the path to an IPython profile directory",
176 176 ),
177 177 ))
178 178 def start(self):
179 179 if self.subapp is not None:
180 180 return self.subapp.start()
181 181 else:
182 182 print(self.ipython_dir)
183 183
184 184
185 185 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
186 186 name = u'ipython'
187 187 description = usage.cl_usage
188 188 crash_handler_class = IPAppCrashHandler
189 189 examples = _examples
190 190
191 191 flags = Dict(flags)
192 192 aliases = Dict(aliases)
193 193 classes = List()
194 194 def _classes_default(self):
195 195 """This has to be in a method, for TerminalIPythonApp to be available."""
196 196 return [
197 197 InteractiveShellApp, # ShellApp comes before TerminalApp, because
198 198 self.__class__, # it will also affect subclasses (e.g. QtConsole)
199 199 TerminalInteractiveShell,
200 200 PromptManager,
201 201 HistoryManager,
202 202 ProfileDir,
203 203 PlainTextFormatter,
204 204 IPCompleter,
205 205 ScriptMagics,
206 206 StoreMagics,
207 207 ]
208 208
209 209 subcommands = dict(
210 210 qtconsole=('qtconsole.console.qtconsoleapp.JupyterQtConsoleApp',
211 211 """DEPRECATD: Launch the Jupyter Qt Console."""
212 212 ),
213 213 notebook=('jupyter_notebook.notebookapp.NotebookApp',
214 214 """DEPRECATED: Launch the IPython HTML Notebook Server."""
215 215 ),
216 216 profile = ("IPython.core.profileapp.ProfileApp",
217 217 "Create and manage IPython profiles."
218 218 ),
219 219 kernel = ("ipython_kernel.kernelapp.IPKernelApp",
220 220 "Start a kernel without an attached frontend."
221 221 ),
222 222 console=('jupyter_console.app.ZMQTerminalIPythonApp',
223 223 """DEPRECATED: Launch the Jupyter terminal-based Console."""
224 224 ),
225 225 locate=('IPython.terminal.ipapp.LocateIPythonApp',
226 226 LocateIPythonApp.description
227 227 ),
228 228 history=('IPython.core.historyapp.HistoryApp',
229 229 "Manage the IPython history database."
230 230 ),
231 nbconvert=('jupyter_nbconvert.nbconvertapp.NbConvertApp',
231 nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
232 232 "DEPRECATED: Convert notebooks to/from other formats."
233 233 ),
234 234 trust=('jupyter_nbformat.sign.TrustNotebookApp',
235 235 "DEPRECATED: Sign notebooks to trust their potentially unsafe contents at load."
236 236 ),
237 237 kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
238 238 "DEPRECATED: Manage Jupyter kernel specifications."
239 239 ),
240 240 )
241 241 subcommands['install-nbextension'] = (
242 242 "jupyter_notebook.nbextensions.NBExtensionApp",
243 243 "DEPRECATED: Install Jupyter notebook extension files"
244 244 )
245 245
246 246 # *do* autocreate requested profile, but don't create the config file.
247 247 auto_create=Bool(True)
248 248 # configurables
249 249 quick = Bool(False, config=True,
250 250 help="""Start IPython quickly by skipping the loading of config files."""
251 251 )
252 252 def _quick_changed(self, name, old, new):
253 253 if new:
254 254 self.load_config_file = lambda *a, **kw: None
255 255
256 256 display_banner = Bool(True, config=True,
257 257 help="Whether to display a banner upon starting IPython."
258 258 )
259 259
260 260 # if there is code of files to run from the cmd line, don't interact
261 261 # unless the --i flag (App.force_interact) is true.
262 262 force_interact = Bool(False, config=True,
263 263 help="""If a command or file is given via the command-line,
264 264 e.g. 'ipython foo.py', start an interactive shell after executing the
265 265 file or command."""
266 266 )
267 267 def _force_interact_changed(self, name, old, new):
268 268 if new:
269 269 self.interact = True
270 270
271 271 def _file_to_run_changed(self, name, old, new):
272 272 if new:
273 273 self.something_to_run = True
274 274 if new and not self.force_interact:
275 275 self.interact = False
276 276 _code_to_run_changed = _file_to_run_changed
277 277 _module_to_run_changed = _file_to_run_changed
278 278
279 279 # internal, not-configurable
280 280 interact=Bool(True)
281 281 something_to_run=Bool(False)
282 282
283 283 def parse_command_line(self, argv=None):
284 284 """override to allow old '-pylab' flag with deprecation warning"""
285 285
286 286 argv = sys.argv[1:] if argv is None else argv
287 287
288 288 if '-pylab' in argv:
289 289 # deprecated `-pylab` given,
290 290 # warn and transform into current syntax
291 291 argv = argv[:] # copy, don't clobber
292 292 idx = argv.index('-pylab')
293 293 warn.warn("`-pylab` flag has been deprecated.\n"
294 294 " Use `--matplotlib <backend>` and import pylab manually.")
295 295 argv[idx] = '--pylab'
296 296
297 297 return super(TerminalIPythonApp, self).parse_command_line(argv)
298 298
299 299 @catch_config_error
300 300 def initialize(self, argv=None):
301 301 """Do actions after construct, but before starting the app."""
302 302 super(TerminalIPythonApp, self).initialize(argv)
303 303 if self.subapp is not None:
304 304 # don't bother initializing further, starting subapp
305 305 return
306 306 # print self.extra_args
307 307 if self.extra_args and not self.something_to_run:
308 308 self.file_to_run = self.extra_args[0]
309 309 self.init_path()
310 310 # create the shell
311 311 self.init_shell()
312 312 # and draw the banner
313 313 self.init_banner()
314 314 # Now a variety of things that happen after the banner is printed.
315 315 self.init_gui_pylab()
316 316 self.init_extensions()
317 317 self.init_code()
318 318
319 319 def init_shell(self):
320 320 """initialize the InteractiveShell instance"""
321 321 # Create an InteractiveShell instance.
322 322 # shell.display_banner should always be False for the terminal
323 323 # based app, because we call shell.show_banner() by hand below
324 324 # so the banner shows *before* all extension loading stuff.
325 325 self.shell = TerminalInteractiveShell.instance(parent=self,
326 326 display_banner=False, profile_dir=self.profile_dir,
327 327 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
328 328 self.shell.configurables.append(self)
329 329
330 330 def init_banner(self):
331 331 """optionally display the banner"""
332 332 if self.display_banner and self.interact:
333 333 self.shell.show_banner()
334 334 # Make sure there is a space below the banner.
335 335 if self.log_level <= logging.INFO: print()
336 336
337 337 def _pylab_changed(self, name, old, new):
338 338 """Replace --pylab='inline' with --pylab='auto'"""
339 339 if new == 'inline':
340 340 warn.warn("'inline' not available as pylab backend, "
341 341 "using 'auto' instead.")
342 342 self.pylab = 'auto'
343 343
344 344 def start(self):
345 345 if self.subapp is not None:
346 346 return self.subapp.start()
347 347 # perform any prexec steps:
348 348 if self.interact:
349 349 self.log.debug("Starting IPython's mainloop...")
350 350 self.shell.mainloop()
351 351 else:
352 352 self.log.debug("IPython not interactive...")
353 353
354 354 def load_default_config(ipython_dir=None):
355 355 """Load the default config file from the default ipython_dir.
356 356
357 357 This is useful for embedded shells.
358 358 """
359 359 if ipython_dir is None:
360 360 ipython_dir = get_ipython_dir()
361 361
362 362 profile_dir = os.path.join(ipython_dir, 'profile_default')
363 363
364 364 config = Config()
365 365 for cf in Application._load_config_files("ipython_config", path=profile_dir):
366 366 config.update(cf)
367 367
368 368 return config
369 369
370 370 launch_new_instance = TerminalIPythonApp.launch_instance
371 371
372 372
373 373 if __name__ == '__main__':
374 374 launch_new_instance()
@@ -1,247 +1,247 b''
1 1 # encoding: utf-8
2 2 """
3 3 IO related utilities.
4 4 """
5 5
6 6 # Copyright (c) IPython Development Team.
7 7 # Distributed under the terms of the Modified BSD License.
8 8
9 9 from __future__ import print_function
10 10 from __future__ import absolute_import
11 11
12 12
13 13 import codecs
14 14 from contextlib import contextmanager
15 15 import io
16 16 import os
17 17 import shutil
18 18 import sys
19 19 import tempfile
20 20 import warnings
21 21 from warnings import warn
22 22 from .capture import CapturedIO, capture_output
23 23 from .py3compat import string_types, input, PY3
24 24
25 25
26 26 class IOStream:
27 27
28 28 def __init__(self,stream, fallback=None):
29 29 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
30 30 if fallback is not None:
31 31 stream = fallback
32 32 else:
33 33 raise ValueError("fallback required, but not specified")
34 34 self.stream = stream
35 35 self._swrite = stream.write
36 36
37 37 # clone all methods not overridden:
38 38 def clone(meth):
39 39 return not hasattr(self, meth) and not meth.startswith('_')
40 40 for meth in filter(clone, dir(stream)):
41 41 setattr(self, meth, getattr(stream, meth))
42 42
43 43 def __repr__(self):
44 44 cls = self.__class__
45 45 tpl = '{mod}.{cls}({args})'
46 46 return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
47 47
48 48 def write(self,data):
49 49 try:
50 50 self._swrite(data)
51 51 except:
52 52 try:
53 53 # print handles some unicode issues which may trip a plain
54 54 # write() call. Emulate write() by using an empty end
55 55 # argument.
56 56 print(data, end='', file=self.stream)
57 57 except:
58 58 # if we get here, something is seriously broken.
59 59 print('ERROR - failed to write data to stream:', self.stream,
60 60 file=sys.stderr)
61 61
62 62 def writelines(self, lines):
63 63 if isinstance(lines, string_types):
64 64 lines = [lines]
65 65 for line in lines:
66 66 self.write(line)
67 67
68 68 # This class used to have a writeln method, but regular files and streams
69 69 # in Python don't have this method. We need to keep this completely
70 70 # compatible so we removed it.
71 71
72 72 @property
73 73 def closed(self):
74 74 return self.stream.closed
75 75
76 76 def close(self):
77 77 pass
78 78
79 79 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
80 80 devnull = open(os.devnull, 'w')
81 81 stdin = IOStream(sys.stdin, fallback=devnull)
82 82 stdout = IOStream(sys.stdout, fallback=devnull)
83 83 stderr = IOStream(sys.stderr, fallback=devnull)
84 84
85 85 class IOTerm:
86 86 """ Term holds the file or file-like objects for handling I/O operations.
87 87
88 88 These are normally just sys.stdin, sys.stdout and sys.stderr but for
89 89 Windows they can can replaced to allow editing the strings before they are
90 90 displayed."""
91 91
92 92 # In the future, having IPython channel all its I/O operations through
93 93 # this class will make it easier to embed it into other environments which
94 94 # are not a normal terminal (such as a GUI-based shell)
95 95 def __init__(self, stdin=None, stdout=None, stderr=None):
96 96 mymodule = sys.modules[__name__]
97 97 self.stdin = IOStream(stdin, mymodule.stdin)
98 98 self.stdout = IOStream(stdout, mymodule.stdout)
99 99 self.stderr = IOStream(stderr, mymodule.stderr)
100 100
101 101
102 102 class Tee(object):
103 103 """A class to duplicate an output stream to stdout/err.
104 104
105 105 This works in a manner very similar to the Unix 'tee' command.
106 106
107 107 When the object is closed or deleted, it closes the original file given to
108 108 it for duplication.
109 109 """
110 110 # Inspired by:
111 111 # http://mail.python.org/pipermail/python-list/2007-May/442737.html
112 112
113 113 def __init__(self, file_or_name, mode="w", channel='stdout'):
114 114 """Construct a new Tee object.
115 115
116 116 Parameters
117 117 ----------
118 118 file_or_name : filename or open filehandle (writable)
119 119 File that will be duplicated
120 120
121 121 mode : optional, valid mode for open().
122 122 If a filename was give, open with this mode.
123 123
124 124 channel : str, one of ['stdout', 'stderr']
125 125 """
126 126 if channel not in ['stdout', 'stderr']:
127 127 raise ValueError('Invalid channel spec %s' % channel)
128 128
129 129 if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
130 130 self.file = file_or_name
131 131 else:
132 132 self.file = open(file_or_name, mode)
133 133 self.channel = channel
134 134 self.ostream = getattr(sys, channel)
135 135 setattr(sys, channel, self)
136 136 self._closed = False
137 137
138 138 def close(self):
139 139 """Close the file and restore the channel."""
140 140 self.flush()
141 141 setattr(sys, self.channel, self.ostream)
142 142 self.file.close()
143 143 self._closed = True
144 144
145 145 def write(self, data):
146 146 """Write data to both channels."""
147 147 self.file.write(data)
148 148 self.ostream.write(data)
149 149 self.ostream.flush()
150 150
151 151 def flush(self):
152 152 """Flush both channels."""
153 153 self.file.flush()
154 154 self.ostream.flush()
155 155
156 156 def __del__(self):
157 157 if not self._closed:
158 158 self.close()
159 159
160 160
161 161 def ask_yes_no(prompt, default=None, interrupt=None):
162 162 """Asks a question and returns a boolean (y/n) answer.
163 163
164 164 If default is given (one of 'y','n'), it is used if the user input is
165 165 empty. If interrupt is given (one of 'y','n'), it is used if the user
166 166 presses Ctrl-C. Otherwise the question is repeated until an answer is
167 167 given.
168 168
169 169 An EOF is treated as the default answer. If there is no default, an
170 170 exception is raised to prevent infinite loops.
171 171
172 172 Valid answers are: y/yes/n/no (match is not case sensitive)."""
173 173
174 174 answers = {'y':True,'n':False,'yes':True,'no':False}
175 175 ans = None
176 176 while ans not in answers.keys():
177 177 try:
178 178 ans = input(prompt+' ').lower()
179 179 if not ans: # response was an empty string
180 180 ans = default
181 181 except KeyboardInterrupt:
182 182 if interrupt:
183 183 ans = interrupt
184 184 except EOFError:
185 185 if default in answers.keys():
186 186 ans = default
187 187 print()
188 188 else:
189 189 raise
190 190
191 191 return answers[ans]
192 192
193 193
194 194 def temp_pyfile(src, ext='.py'):
195 195 """Make a temporary python file, return filename and filehandle.
196 196
197 197 Parameters
198 198 ----------
199 199 src : string or list of strings (no need for ending newlines if list)
200 200 Source code to be written to the file.
201 201
202 202 ext : optional, string
203 203 Extension for the generated file.
204 204
205 205 Returns
206 206 -------
207 207 (filename, open filehandle)
208 208 It is the caller's responsibility to close the open file and unlink it.
209 209 """
210 210 fname = tempfile.mkstemp(ext)[1]
211 211 f = open(fname,'w')
212 212 f.write(src)
213 213 f.flush()
214 214 return fname, f
215 215
216 216 def atomic_writing(*args, **kwargs):
217 217 """DEPRECATED: moved to jupyter_notebook.services.contents.fileio"""
218 218 warn("IPython.utils.io.atomic_writing has moved to jupyter_notebook.services.contents.fileio")
219 219 from jupyter_notebook.services.contents.fileio import atomic_writing
220 220 return atomic_writing(*args, **kwargs)
221 221
222 222 def raw_print(*args, **kw):
223 223 """Raw print to sys.__stdout__, otherwise identical interface to print()."""
224 224
225 225 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
226 226 file=sys.__stdout__)
227 227 sys.__stdout__.flush()
228 228
229 229
230 230 def raw_print_err(*args, **kw):
231 231 """Raw print to sys.__stderr__, otherwise identical interface to print()."""
232 232
233 233 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
234 234 file=sys.__stderr__)
235 235 sys.__stderr__.flush()
236 236
237 237
238 238 # Short aliases for quick debugging, do NOT use these in production code.
239 239 rprint = raw_print
240 240 rprinte = raw_print_err
241 241
242 242
243 243 def unicode_std_stream(stream='stdout'):
244 """DEPRECATED, moved to jupyter_nbconvert.utils.io"""
245 warn("IPython.utils.io.unicode_std_stream has moved to jupyter_nbconvert.utils.io")
246 from jupyter_nbconvert.utils.io import unicode_std_stream
244 """DEPRECATED, moved to nbconvert.utils.io"""
245 warn("IPython.utils.io.unicode_std_stream has moved to nbconvert.utils.io")
246 from nbconvert.utils.io import unicode_std_stream
247 247 return unicode_std_stream(stream)
@@ -1,288 +1,288 b''
1 1 #!/usr/bin/env python
2 2 # -*- coding: utf-8 -*-
3 3 """Setup script for IPython.
4 4
5 5 Under Posix environments it works like a typical setup.py script.
6 6 Under Windows, the command sdist is not supported, since IPython
7 7 requires utilities which are not available under Windows."""
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (c) 2008-2011, IPython Development Team.
11 11 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
12 12 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
13 13 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
14 14 #
15 15 # Distributed under the terms of the Modified BSD License.
16 16 #
17 17 # The full license is in the file COPYING.rst, distributed with this software.
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Minimal Python version sanity check
22 22 #-----------------------------------------------------------------------------
23 23 from __future__ import print_function
24 24
25 25 import sys
26 26
27 27 # This check is also made in IPython/__init__, don't forget to update both when
28 28 # changing Python version requirements.
29 29 v = sys.version_info
30 30 if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
31 31 error = "ERROR: IPython requires Python version 2.7 or 3.3 or above."
32 32 print(error, file=sys.stderr)
33 33 sys.exit(1)
34 34
35 35 PY3 = (sys.version_info[0] >= 3)
36 36
37 37 # At least we're on the python version we need, move on.
38 38
39 39 #-------------------------------------------------------------------------------
40 40 # Imports
41 41 #-------------------------------------------------------------------------------
42 42
43 43 # Stdlib imports
44 44 import os
45 45 import shutil
46 46
47 47 from glob import glob
48 48
49 49 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
50 50 # update it when the contents of directories change.
51 51 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
52 52
53 53 from distutils.core import setup
54 54
55 55 # Our own imports
56 56 from setupbase import target_update
57 57
58 58 from setupbase import (
59 59 setup_args,
60 60 find_packages,
61 61 find_package_data,
62 62 check_package_data_first,
63 63 find_entry_points,
64 64 build_scripts_entrypt,
65 65 find_data_files,
66 66 check_for_readline,
67 67 git_prebuild,
68 68 get_bdist_wheel,
69 69 install_symlinked,
70 70 install_lib_symlink,
71 71 install_scripts_for_symlink,
72 72 unsymlink,
73 73 )
74 74
75 75 isfile = os.path.isfile
76 76 pjoin = os.path.join
77 77
78 78 #-------------------------------------------------------------------------------
79 79 # Handle OS specific things
80 80 #-------------------------------------------------------------------------------
81 81
82 82 if os.name in ('nt','dos'):
83 83 os_name = 'windows'
84 84 else:
85 85 os_name = os.name
86 86
87 87 # Under Windows, 'sdist' has not been supported. Now that the docs build with
88 88 # Sphinx it might work, but let's not turn it on until someone confirms that it
89 89 # actually works.
90 90 if os_name == 'windows' and 'sdist' in sys.argv:
91 91 print('The sdist command is not available under Windows. Exiting.')
92 92 sys.exit(1)
93 93
94 94
95 95 #-------------------------------------------------------------------------------
96 96 # Things related to the IPython documentation
97 97 #-------------------------------------------------------------------------------
98 98
99 99 # update the manuals when building a source dist
100 100 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
101 101
102 102 # List of things to be updated. Each entry is a triplet of args for
103 103 # target_update()
104 104 to_update = [
105 105 ('docs/man/ipython.1.gz',
106 106 ['docs/man/ipython.1'],
107 107 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'),
108 108 ]
109 109
110 110
111 111 [ target_update(*t) for t in to_update ]
112 112
113 113 #---------------------------------------------------------------------------
114 114 # Find all the packages, package data, and data_files
115 115 #---------------------------------------------------------------------------
116 116
117 117 packages = find_packages()
118 118 package_data = find_package_data()
119 119
120 120 data_files = find_data_files()
121 121
122 122 setup_args['packages'] = packages
123 123 setup_args['package_data'] = package_data
124 124 setup_args['data_files'] = data_files
125 125
126 126 #---------------------------------------------------------------------------
127 127 # custom distutils commands
128 128 #---------------------------------------------------------------------------
129 129 # imports here, so they are after setuptools import if there was one
130 130 from distutils.command.sdist import sdist
131 131 from distutils.command.upload import upload
132 132
133 133 class UploadWindowsInstallers(upload):
134 134
135 135 description = "Upload Windows installers to PyPI (only used from tools/release_windows.py)"
136 136 user_options = upload.user_options + [
137 137 ('files=', 'f', 'exe file (or glob) to upload')
138 138 ]
139 139 def initialize_options(self):
140 140 upload.initialize_options(self)
141 141 meta = self.distribution.metadata
142 142 base = '{name}-{version}'.format(
143 143 name=meta.get_name(),
144 144 version=meta.get_version()
145 145 )
146 146 self.files = os.path.join('dist', '%s.*.exe' % base)
147 147
148 148 def run(self):
149 149 for dist_file in glob(self.files):
150 150 self.upload_file('bdist_wininst', 'any', dist_file)
151 151
152 152 setup_args['cmdclass'] = {
153 153 'build_py': \
154 154 check_package_data_first(git_prebuild('IPython')),
155 155 'sdist' : git_prebuild('IPython', sdist),
156 156 'upload_wininst' : UploadWindowsInstallers,
157 157 'symlink': install_symlinked,
158 158 'install_lib_symlink': install_lib_symlink,
159 159 'install_scripts_sym': install_scripts_for_symlink,
160 160 'unsymlink': unsymlink,
161 161 }
162 162
163 163 ### Temporarily disable install while it's broken during the big split
164 164 from textwrap import dedent
165 165 from distutils.command.install import install
166 166
167 167 class DisabledInstall(install):
168 168 def run(self):
169 169 msg = dedent("""
170 170 While we are in the midst of The Big Split,
171 171 IPython cannot be installed from master.
172 172 You can use `pip install -e .` for an editable install,
173 173 which still works.
174 174 """)
175 175 print(msg, file=sys.stderr)
176 176 raise SystemExit(1)
177 177
178 178 setup_args['cmdclass']['install'] = DisabledInstall
179 179
180 180
181 181 #---------------------------------------------------------------------------
182 182 # Handle scripts, dependencies, and setuptools specific things
183 183 #---------------------------------------------------------------------------
184 184
185 185 # For some commands, use setuptools. Note that we do NOT list install here!
186 186 # If you want a setuptools-enhanced install, just run 'setupegg.py install'
187 187 needs_setuptools = set(('develop', 'release', 'bdist_egg', 'bdist_rpm',
188 188 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel',
189 189 'egg_info', 'easy_install', 'upload', 'install_egg_info',
190 190 ))
191 191
192 192 if len(needs_setuptools.intersection(sys.argv)) > 0:
193 193 import setuptools
194 194
195 195 # This dict is used for passing extra arguments that are setuptools
196 196 # specific to setup
197 197 setuptools_extra_args = {}
198 198
199 199 # setuptools requirements
200 200
201 201 pyzmq = 'pyzmq>=13'
202 202
203 203 extras_require = dict(
204 204 parallel = ['ipyparallel'],
205 205 qtconsole = ['qtconsole'],
206 206 doc = ['Sphinx>=1.1', 'numpydoc'],
207 207 test = ['nose>=0.10.1', 'requests'],
208 208 terminal = [],
209 209 kernel = ['ipython_kernel'],
210 210 nbformat = ['jupyter_nbformat'],
211 211 notebook = ['jupyter_notebook'],
212 nbconvert = ['jupyter_nbconvert']
212 nbconvert = ['nbconvert'],
213 213 )
214 214
215 215 if sys.version_info < (3, 3):
216 216 extras_require['test'].append('mock')
217 217
218 218 install_requires = [
219 219 'decorator',
220 220 'pickleshare',
221 221 'simplegeneric>0.8',
222 222 'traitlets',
223 223 ]
224 224
225 225 # add platform-specific dependencies
226 226 if sys.platform == 'darwin':
227 227 install_requires.append('appnope')
228 228 if 'bdist_wheel' in sys.argv[1:] or not check_for_readline():
229 229 install_requires.append('gnureadline')
230 230
231 231 if sys.platform.startswith('win'):
232 232 extras_require['terminal'].append('pyreadline>=2.0')
233 233 else:
234 234 install_requires.append('pexpect')
235 235
236 236 everything = set()
237 237 for deps in extras_require.values():
238 238 everything.update(deps)
239 239 extras_require['all'] = everything
240 240
241 241 if 'setuptools' in sys.modules:
242 242 setup_args['cmdclass']['bdist_wheel'] = get_bdist_wheel()
243 243
244 244 setuptools_extra_args['zip_safe'] = False
245 245 setuptools_extra_args['entry_points'] = {
246 246 'console_scripts': find_entry_points(),
247 247 'pygments.lexers': [
248 248 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer',
249 249 'ipython = IPython.lib.lexers:IPythonLexer',
250 250 'ipython3 = IPython.lib.lexers:IPython3Lexer',
251 251 ],
252 252 }
253 253 setup_args['extras_require'] = extras_require
254 254 requires = setup_args['install_requires'] = install_requires
255 255
256 256 # Script to be run by the windows binary installer after the default setup
257 257 # routine, to add shortcuts and similar windows-only things. Windows
258 258 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
259 259 # doesn't find them.
260 260 if 'bdist_wininst' in sys.argv:
261 261 if len(sys.argv) > 2 and \
262 262 ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
263 263 print("ERROR: bdist_wininst must be run alone. Exiting.", file=sys.stderr)
264 264 sys.exit(1)
265 265 setup_args['data_files'].append(
266 266 ['Scripts', ('scripts/ipython.ico', 'scripts/ipython_nb.ico')])
267 267 setup_args['scripts'] = [pjoin('scripts','ipython_win_post_install.py')]
268 268 setup_args['options'] = {"bdist_wininst":
269 269 {"install_script":
270 270 "ipython_win_post_install.py"}}
271 271
272 272 else:
273 273 # scripts has to be a non-empty list, or install_scripts isn't called
274 274 setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()]
275 275
276 276 setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt
277 277
278 278 #---------------------------------------------------------------------------
279 279 # Do the actual setup now
280 280 #---------------------------------------------------------------------------
281 281
282 282 setup_args.update(setuptools_extra_args)
283 283
284 284 def main():
285 285 setup(**setup_args)
286 286
287 287 if __name__ == '__main__':
288 288 main()
General Comments 0
You need to be logged in to leave comments. Login now