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