##// END OF EJS Templates
More work on getting rid of ipmaker.
Brian Granger -
Show More
@@ -189,12 +189,15 b' class ArgParseConfigLoader(CommandLineConfigLoader):'
189 189 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
190 190
191 191 def _add_other_arguments(self):
192 self.parser.add_argument('--ipythondir',dest='IPYTHONDIR',type=str,
193 help='set to override default location of IPYTHONDIR',
192 self.parser.add_argument('-ipythondir',dest='IPYTHONDIR',type=str,
193 help='Set to override default location of IPYTHONDIR.',
194 194 default=NoDefault)
195 self.parser.add_argument('-p','--p',dest='PROFILE_NAME',type=str,
196 help='the string name of the ipython profile to be used',
197 default=None)
198 self.parser.add_argument('--debug',dest="DEBUG",action='store_true',
199 help='debug the application startup process',
195 self.parser.add_argument('-p','-profile',dest='PROFILE',type=str,
196 help='The string name of the ipython profile to be used.',
197 default=NoDefault)
198 self.parser.add_argument('-debug',dest="DEBUG",action='store_true',
199 help='Debug the application startup process.',
200 default=NoDefault)
201 self.parser.add_argument('-config_file',dest='CONFIG_FILE',type=str,
202 help='Set the config file name to override default.',
200 203 default=NoDefault)
@@ -59,7 +59,7 b' class Application(object):'
59 59 """Start the application."""
60 60 self.attempt(self.create_default_config)
61 61 self.attempt(self.pre_load_command_line_config)
62 self.attempt(self.load_command_line_config, action='exit')
62 self.attempt(self.load_command_line_config, action='abort')
63 63 self.attempt(self.post_load_command_line_config)
64 64 self.attempt(self.find_ipythondir)
65 65 self.attempt(self.find_config_file_name)
@@ -137,11 +137,18 b' class Application(object):'
137 137 loader where they are resolved to an absolute path.
138 138 """
139 139
140 if self.command_line_config.PROFILE_NAME is not None:
141 self.profile_name = self.command_line_config.PROFILE_NAME
140 try:
141 self.config_file_name = self.command_line_config.CONFIG_FILE
142 except AttributeError:
143 pass
144
145 try:
146 self.profile_name = self.command_line_config.PROFILE
142 147 name_parts = self.config_file_name.split('.')
143 148 name_parts.insert(1, '_' + self.profile_name + '.')
144 149 self.config_file_name = ''.join(name_parts)
150 except AttributeError:
151 pass
145 152
146 153 def find_config_file_paths(self):
147 154 """Set the search paths for resolving the config file."""
@@ -168,7 +175,8 b' class Application(object):'
168 175 self.config_file_name)
169 176 self.file_config = Struct()
170 177 else:
171 self.log("Config file loaded: %s" % loader.full_filename)
178 self.log("Config file loaded: %s" % loader.full_filename,
179 self.file_config)
172 180
173 181 def post_load_file_config(self):
174 182 """Do actions after the config file is loaded."""
@@ -178,8 +186,8 b' class Application(object):'
178 186 """Merge the default, command line and file config objects."""
179 187 config = Struct()
180 188 config.update(self.default_config)
181 config.update(self.command_line_config)
182 189 config.update(self.file_config)
190 config.update(self.command_line_config)
183 191 self.master_config = config
184 192 self.log("Master config created:", self.master_config)
185 193
@@ -23,10 +23,22 b' Notes'
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 import os
27 import sys
28 import warnings
29
26 30 from IPython.core.application import Application
27 31 from IPython.core import release
28 32 from IPython.core.iplib import InteractiveShell
29 from IPython.config.loader import IPythonArgParseConfigLoader
33 from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault
34
35 from IPython.utils.ipstruct import Struct
36
37
38 #-----------------------------------------------------------------------------
39 # Utilities and helpers
40 #-----------------------------------------------------------------------------
41
30 42
31 43 ipython_desc = """
32 44 A Python shell with automatic history (input and output), dynamic object
@@ -34,10 +46,184 b' introspection, easier configuration, command completion, access to the system'
34 46 shell and more.
35 47 """
36 48
49 def threaded_shell_warning():
50 msg = """
51
52 The IPython threaded shells and their associated command line
53 arguments (pylab/wthread/gthread/qthread/q4thread) have been
54 deprecated. See the %gui magic for information on the new interface.
55 """
56 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
57
58
59 #-----------------------------------------------------------------------------
60 # Main classes and functions
61 #-----------------------------------------------------------------------------
62
63 cl_args = (
64 (('-autocall',), dict(
65 type=int, dest='AUTOCALL', default=NoDefault,
66 help='Set the autocall value (0,1,2).')
67 ),
68 (('-autoindent',), dict(
69 action='store_true', dest='AUTOINDENT', default=NoDefault,
70 help='Turn on autoindenting.')
71 ),
72 (('-noautoindent',), dict(
73 action='store_false', dest='AUTOINDENT', default=NoDefault,
74 help='Turn off autoindenting.')
75 ),
76 (('-automagic',), dict(
77 action='store_true', dest='AUTOMAGIC', default=NoDefault,
78 help='Turn on the auto calling of magic commands.')
79 ),
80 (('-noautomagic',), dict(
81 action='store_false', dest='AUTOMAGIC', default=NoDefault,
82 help='Turn off the auto calling of magic commands.')
83 ),
84 (('-autoedit_syntax',), dict(
85 action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault,
86 help='Turn on auto editing of files with syntax errors.')
87 ),
88 (('-noautoedit_syntax',), dict(
89 action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault,
90 help='Turn off auto editing of files with syntax errors.')
91 ),
92 (('-banner',), dict(
93 action='store_true', dest='DISPLAY_BANNER', default=NoDefault,
94 help='Display a banner upon starting IPython.')
95 ),
96 (('-nobanner',), dict(
97 action='store_false', dest='DISPLAY_BANNER', default=NoDefault,
98 help="Don't display a banner upon starting IPython.")
99 ),
100 (('-c',), dict(
101 type=str, dest='C', default=NoDefault,
102 help="Execute the given command string.")
103 ),
104 (('-cache_size',), dict(
105 type=int, dest='CACHE_SIZE', default=NoDefault,
106 help="Set the size of the output cache.")
107 ),
108 (('-classic',), dict(
109 action='store_true', dest='CLASSIC', default=NoDefault,
110 help="Gives IPython a similar feel to the classic Python prompt.")
111 ),
112 (('-colors',), dict(
113 type=str, dest='COLORS', default=NoDefault,
114 help="Set the color scheme (NoColor, Linux, and LightBG).")
115 ),
116 (('-color_info',), dict(
117 action='store_true', dest='COLOR_INFO', default=NoDefault,
118 help="Enable using colors for info related things.")
119 ),
120 (('-nocolor_info',), dict(
121 action='store_false', dest='COLOR_INFO', default=NoDefault,
122 help="Disable using colors for info related things.")
123 ),
124 (('-confirm_exit',), dict(
125 action='store_true', dest='CONFIRM_EXIT', default=NoDefault,
126 help="Prompt the user when existing.")
127 ),
128 (('-noconfirm_exit',), dict(
129 action='store_false', dest='CONFIRM_EXIT', default=NoDefault,
130 help="Don't prompt the user when existing.")
131 ),
132 (('-deep_reload',), dict(
133 action='store_true', dest='DEEP_RELOAD', default=NoDefault,
134 help="Enable deep (recursive) reloading by default.")
135 ),
136 (('-nodeep_reload',), dict(
137 action='store_false', dest='DEEP_RELOAD', default=NoDefault,
138 help="Disable deep (recursive) reloading by default.")
139 ),
140 (('-editor',), dict(
141 type=str, dest='EDITOR', default=NoDefault,
142 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).")
143 ),
144 (('-log','-l'), dict(
145 action='store_true', dest='LOGSTART', default=NoDefault,
146 help="Start logging to the default file (./ipython_log.py).")
147 ),
148 (('-logfile','-lf'), dict(
149 type=str, dest='LOGFILE', default=NoDefault,
150 help="Specify the name of your logfile.")
151 ),
152 (('-logplay','-lp'), dict(
153 type=str, dest='LOGPLAY', default=NoDefault,
154 help="Re-play a log file and then append to it.")
155 ),
156 (('-pdb',), dict(
157 action='store_true', dest='PDB', default=NoDefault,
158 help="Enable auto calling the pdb debugger after every exception.")
159 ),
160 (('-nopdb',), dict(
161 action='store_false', dest='PDB', default=NoDefault,
162 help="Disable auto calling the pdb debugger after every exception.")
163 ),
164 (('-pprint',), dict(
165 action='store_true', dest='PPRINT', default=NoDefault,
166 help="Enable auto pretty printing of results.")
167 ),
168 (('-nopprint',), dict(
169 action='store_false', dest='PPRINT', default=NoDefault,
170 help="Disable auto auto pretty printing of results.")
171 ),
172 (('-prompt_in1','-pi1'), dict(
173 type=str, dest='PROMPT_IN1', default=NoDefault,
174 help="Set the main input prompt ('In [\#]: ')")
175 ),
176 (('-prompt_in2','-pi2'), dict(
177 type=str, dest='PROMPT_IN2', default=NoDefault,
178 help="Set the secondary input prompt (' .\D.: ')")
179 ),
180 (('-prompt_out','-po'), dict(
181 type=str, dest='PROMPT_OUT', default=NoDefault,
182 help="Set the output prompt ('Out[\#]:')")
183 ),
184 (('-quick',), dict(
185 action='store_true', dest='QUICK', default=NoDefault,
186 help="Enable quick startup with no config files.")
187 ),
188 (('-readline',), dict(
189 action='store_true', dest='READLINE_USE', default=NoDefault,
190 help="Enable readline for command line usage.")
191 ),
192 (('-noreadline',), dict(
193 action='store_false', dest='READLINE_USE', default=NoDefault,
194 help="Disable readline for command line usage.")
195 ),
196 (('-screen_length','-sl'), dict(
197 type=int, dest='SCREEN_LENGTH', default=NoDefault,
198 help='Number of lines on screen, used to control printing of long strings.')
199 ),
200 (('-separate_in','-si'), dict(
201 type=str, dest='SEPARATE_IN', default=NoDefault,
202 help="Separator before input prompts. Default '\n'.")
203 ),
204 (('-separate_out','-so'), dict(
205 type=str, dest='SEPARATE_OUT', default=NoDefault,
206 help="Separator before output prompts. Default 0 (nothing).")
207 ),
208 (('-separate_out2','-so2'), dict(
209 type=str, dest='SEPARATE_OUT2', default=NoDefault,
210 help="Separator after output prompts. Default 0 (nonight).")
211 ),
212 (('-nosep',), dict(
213 action='store_true', dest='NOSEP', default=NoDefault,
214 help="Eliminate all spacing between prompts.")
215 ),
216 (('-xmode',), dict(
217 type=str, dest='XMODE', default=NoDefault,
218 help="Exception mode ('Plain','Context','Verbose')")
219 ),
220 )
221
222
37 223 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
38 arguments = (
39 ()
40 )
224
225 arguments = cl_args
226
41 227
42 228 class IPythonApp(Application):
43 229 name = 'ipython'
@@ -49,7 +235,72 b' class IPythonApp(Application):'
49 235 description=ipython_desc,
50 236 version=release.version)
51 237
238 def post_load_command_line_config(self):
239 """Do actions after loading cl config."""
240 clc = self.command_line_config
241
242 # This needs to be set here, the rest are set in pre_construct.
243 if hasattr(clc, 'CLASSIC'):
244 if clc.CLASSIC: clc.QUICK = 1
245
246 # Display the deprecation warnings about threaded shells
247 # if opts_all.pylab == 1: threaded_shell_warning()
248 # if opts_all.wthread == 1: threaded_shell_warning()
249 # if opts_all.qthread == 1: threaded_shell_warning()
250 # if opts_all.q4thread == 1: threaded_shell_warning()
251 # if opts_all.gthread == 1: threaded_shell_warning()
252
253 def load_file_config(self):
254 if hasattr(self.command_line_config, 'QUICK'):
255 if self.command_line_config.QUICK:
256 self.file_config = Struct()
257 return
258 super(IPythonApp, self).load_file_config()
259
260 def post_load_file_config(self):
261 """Logic goes here."""
262
263 def pre_construct(self):
264 config = self.master_config
265
266 if hasattr(config, 'CLASSIC'):
267 if config.CLASSIC:
268 config.QUICK = 1
269 config.CACHE_SIZE = 0
270 config.PPRINT = 0
271 config.PROMPT_IN1 = '>>> '
272 config.PROMPT_IN2 = '... '
273 config.PROMPT_OUT = ''
274 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = ''
275 config.COLORS = 'NoColor'
276 config.XMODE = 'Plain'
277
278 # All this should be moved to traitlet handlers in InteractiveShell
279 if hasattr(config, 'NOSEP'):
280 if config.NOSEP:
281 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0'
282
283 if hasattr(config, 'SEPARATE_IN'):
284 if config.SEPARATE_IN == '0': config.SEPARATE_IN = ''
285 config.SEPARATE_IN = config.SEPARATE_IN.replace('\\n','\n')
286
287 if hasattr(config, 'SEPARATE_OUT'):
288 if config.SEPARATE_OUT == '0': config.SEPARATE_OUT = ''
289 config.SEPARATE_OUT = config.SEPARATE_OUT.replace('\\n','\n')
290
291 if hasattr(config, 'SEPARATE_OUT'):
292 if config.SEPARATE_OUT2 == '0': config.SEPARATE_OUT2 = ''
293 config.SEPARATE_OUT2 = config.SEPARATE_OUT2.replace('\\n','\n')
294
52 295 def construct(self):
296 # I am a little hesitant to put these into InteractiveShell itself.
297 # But that might be the place for them
298 sys.path.insert(0, '')
299 # add personal ipythondir to sys.path so that users can put things in
300 # there for customization
301 sys.path.append(os.path.abspath(self.ipythondir))
302
303 # Create an InteractiveShell instance
53 304 self.shell = InteractiveShell(
54 305 name='__IP',
55 306 parent=None,
@@ -44,7 +44,7 b' from IPython.core.magic import Magic'
44 44 from IPython.core.prompts import CachedOutput
45 45 from IPython.core.component import Component
46 46 from IPython.core.oldusersetup import user_setup
47 from IPython.core.usage import interactive_usage, banner_parts
47 from IPython.core.usage import interactive_usage, default_banner
48 48
49 49 from IPython.extensions import pickleshare
50 50 from IPython.external.Itpl import ItplNS
@@ -55,7 +55,7 b' from IPython.utils.genutils import *'
55 55 from IPython.utils.strdispatch import StrDispatch
56 56
57 57 from IPython.utils.traitlets import (
58 Int, Float, Str, Bool
58 Int, Float, Str, CBool, CaselessStrEnum, Enum
59 59 )
60 60
61 61 #-----------------------------------------------------------------------------
@@ -160,6 +160,15 b' class SyntaxTB(ultratb.ListTB):'
160 160 self.last_syntax_error = None
161 161 return e
162 162
163 def get_default_editor():
164 try:
165 ed = os.environ['EDITOR']
166 except KeyError:
167 if os.name == 'posix':
168 ed = 'vi' # the only one guaranteed to be there!
169 else:
170 ed = 'notepad' # same in Windows!
171 return ed
163 172
164 173 #-----------------------------------------------------------------------------
165 174 # Main IPython class
@@ -187,47 +196,47 b' class InteractiveShell(Component, Magic):'
187 196 """An enhanced console for Python."""
188 197
189 198 alias = []
190 autocall = Bool(True)
191 autoedit_syntax = Bool(False)
192 autoindent = Bool(False)
193 automagic = Bool(True)
199 autocall = Enum((0,1,2), config_key='AUTOCALL')
200 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
201 autoindent = CBool(True, config_key='AUTOINDENT')
202 automagic = CBool(True, config_key='AUTOMAGIC')
194 203 autoexec = []
195 display_banner = Bool(True)
204 display_banner = CBool(True, config_key='DISPLAY_BANNER')
196 205 banner = Str('')
197 c = Str('')
198 cache_size = Int(1000)
199 classic = Bool(False)
200 color_info = Int(0)
201 colors = Str('LightBG')
202 confirm_exit = Bool(True)
203 debug = Bool(False)
204 deep_reload = Bool(False)
205 embedded = Bool(False)
206 editor = Str('0')
206 banner1 = Str(default_banner, config_key='BANNER1')
207 banner2 = Str('', config_key='BANNER2')
208 c = Str('', config_key='C')
209 cache_size = Int(1000, config_key='CACHE_SIZE')
210 classic = CBool(False, config_key='CLASSIC')
211 color_info = CBool(True, config_key='COLOR_INFO')
212 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
213 default_value='LightBG', config_key='COLORS')
214 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
215 debug = CBool(False)
216 deep_reload = CBool(False, config_key='DEEP_RELOAD')
217 embedded = CBool(False)
218 editor = Str(get_default_editor(), config_key='EDITOR')
207 219 filename = Str("<ipython console>")
208 help = Bool(False)
209 interactive = Bool(False)
210 logstart = Bool(False, config_key='LOGSTART')
211 logfile = Str('')
212 logplay = Str('')
213 messages = Bool(True)
214 multi_line_specials = Bool(True)
215 nosep = Bool(False)
220 help = CBool(False)
221 interactive = CBool(False)
222 logstart = CBool(False, config_key='LOGSTART')
223 logfile = Str('', config_key='LOGFILE')
224 logplay = Str('', config_key='LOGPLAY')
225 multi_line_specials = CBool(True)
216 226 object_info_string_level = Int(0)
217 227 pager = Str('less')
218 pdb = Bool(False)
219 pprint = Bool(True)
220 profile = Str('')
221 prompt_in1 = Str('In [\\#]: ')
222 prompt_in2 = Str(' .\\D.: ')
223 prompt_out = Str('Out[\\#]: ')
224 prompts_pad_left = Bool(True)
225 pydb = Bool(False)
226 quick = Bool(False)
227 quiet = Bool(False)
228
229 readline_use = Bool(True)
230 readline_merge_completions = Bool(True)
228 pdb = CBool(False, config_key='PDB')
229 pprint = CBool(True, config_key='PPRINT')
230 profile = Str('', config_key='PROFILE')
231 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
232 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
233 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
234 prompts_pad_left = CBool(True)
235 pydb = CBool(False)
236 quiet = CBool(False)
237
238 readline_use = CBool(True, config_key='READLINE_USE')
239 readline_merge_completions = CBool(True)
231 240 readline_omit__names = Int(0)
232 241 readline_remove_delims = '-/~'
233 242 readline_parse_and_bind = [
@@ -248,30 +257,36 b' class InteractiveShell(Component, Magic):'
248 257 '"\C-u": unix-line-discard',
249 258 ]
250 259
251 screen_length = Int(0)
252 separate_in = Str('\n')
253 separate_out = Str('')
254 separate_out2 = Str('')
260 screen_length = Int(0, config_key='SCREEN_LENGTH')
261 separate_in = Str('\n', config_key='SEPARATE_IN')
262 separate_out = Str('', config_key='SEPARATE_OUT')
263 separate_out2 = Str('', config_key='SEPARATE_OUT2')
255 264 system_header = Str('IPython system call: ')
256 system_verbose = Bool(False)
257 term_title = Bool(True)
258 wildcards_case_sensitive = Bool(True)
259 xmode = Str('Context')
260 magic_docstrings = Bool(False)
265 system_verbose = CBool(False)
266 term_title = CBool(True)
267 wildcards_case_sensitive = CBool(True)
268 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
269 default_value='Context', config_key='XMODE')
270 magic_docstrings = CBool(False)
261 271
262 272 # class attribute to indicate whether the class supports threads or not.
263 273 # Subclasses with thread support should override this as needed.
264 274 isthreaded = False
265 275
266 276 def __init__(self, name, parent=None, config=None, usage=None,
267 user_ns=None, user_global_ns=None, banner2='',
277 user_ns=None, user_global_ns=None,
278 banner1='', banner2='',
268 279 custom_exceptions=((),None), embedded=False):
269 280
281 # This is where traitlets with a config_key argument are updated
282 # from the values on config.
283 # Ideally, from here on out, the config should only be used when
284 # passing it to children components.
270 285 super(InteractiveShell, self).__init__(parent, config=config, name=name)
271 286
272 287 self.init_instance_attrs()
273 288 self.init_usage(usage)
274 self.init_banner(banner2)
289 self.init_banner(banner1, banner2)
275 290 self.init_embedded(embedded)
276 291 self.init_create_namespaces(user_ns, user_global_ns)
277 292 self.init_history()
@@ -292,9 +307,45 b' class InteractiveShell(Component, Magic):'
292 307 self.init_logger()
293 308 self.init_aliases()
294 309 self.init_builtins()
310
311 # pre_config_initialization
295 312 self.init_shadow_hist()
313
314 # The next section should contain averything that was in ipmaker.
296 315 self.init_logstart()
297 self.post_config_initialization()
316
317 # The following was in post_config_initialization
318 self.init_inspector()
319 self.init_readline()
320 self.init_prompts()
321 self.init_displayhook()
322 self.init_reload_doctest()
323 self.init_magics()
324 self.init_pdb()
325 self.hooks.late_startup_hook()
326 self.init_exec_commands()
327
328 #-------------------------------------------------------------------------
329 # Traitlet changed handlers
330 #-------------------------------------------------------------------------
331
332 def _banner1_changed(self):
333 self.compute_banner()
334
335 def _banner2_changed(self):
336 self.compute_banner()
337
338 @property
339 def usable_screen_length(self):
340 if self.screen_length == 0:
341 return 0
342 else:
343 num_lines_bot = self.separate_in.count('\n')+1
344 return self.screen_length - num_lines_bot
345
346 #-------------------------------------------------------------------------
347 # init_* methods called by __init__
348 #-------------------------------------------------------------------------
298 349
299 350 def init_instance_attrs(self):
300 351 self.jobs = BackgroundJobManager()
@@ -341,15 +392,21 b' class InteractiveShell(Component, Magic):'
341 392 else:
342 393 self.usage = usage
343 394
344 def init_banner(self, banner2):
395 def init_banner(self, banner1, banner2):
345 396 if self.c: # regular python doesn't print the banner with -c
346 397 self.display_banner = False
347 bp = banner_parts
398 if banner1:
399 self.banner1 = banner1
400 if banner2:
401 self.banner2 = banner2
402 self.compute_banner()
403
404 def compute_banner(self):
405 self.banner = self.banner1 + '\n'
348 406 if self.profile:
349 bp.append('IPython profile: %s\n' % self.profile)
350 if banner2 is not None:
351 bp.append(banner2)
352 self.banner = '\n'.join(bp)
407 self.banner += '\nIPython profile: %s\n' % self.profile
408 if self.banner2:
409 self.banner += '\n' + self.banner2 + '\n'
353 410
354 411 def init_embedded(self, embedded):
355 412 # We need to know whether the instance is meant for embedding, since
@@ -512,6 +569,10 b' class InteractiveShell(Component, Magic):'
512 569 histfname = 'history'
513 570 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
514 571
572 # Fill the history zero entry, user counter starts at 1
573 self.input_hist.append('\n')
574 self.input_hist_raw.append('\n')
575
515 576 def init_encoding(self):
516 577 # Get system encoding at startup time. Certain terminals (like Emacs
517 578 # under Win32 have it set to None, and we need to have a known valid
@@ -613,9 +674,9 b' class InteractiveShell(Component, Magic):'
613 674
614 675 def init_logstart(self):
615 676 if self.logplay:
616 IP.magic_logstart(self.logplay + ' append')
677 self.magic_logstart(self.logplay + ' append')
617 678 elif self.logfile:
618 IP.magic_logstart(self.logfile)
679 self.magic_logstart(self.logfile)
619 680 elif self.logstart:
620 681 self.magic_logstart()
621 682
@@ -687,7 +748,8 b' class InteractiveShell(Component, Magic):'
687 748 # This method will add the necessary builtins for operation, but
688 749 # tracking what it did via the builtins_added dict.
689 750
690 #TODO: remove this, redundant
751 #TODO: remove this, redundant. I don't understand why this is
752 # redundant?
691 753 self.add_builtins()
692 754
693 755 def init_shadow_hist(self):
@@ -701,24 +763,100 b' class InteractiveShell(Component, Magic):'
701 763 sys.exit()
702 764 self.shadowhist = ipcorehist.ShadowHist(self.db)
703 765
704 def post_config_initialization(self):
705 """Post configuration init method
706
707 This is called after the configuration files have been processed to
708 'finalize' the initialization."""
709
766 def init_inspector(self):
710 767 # Object inspector
711 768 self.inspector = oinspect.Inspector(oinspect.InspectColors,
712 769 PyColorize.ANSICodeColors,
713 770 'NoColor',
714 771 self.object_info_string_level)
715
772
773 def init_readline(self):
774 """Command history completion/saving/reloading."""
775
716 776 self.rl_next_input = None
717 777 self.rl_do_indent = False
718 # Load readline proper
719 if self.readline_use:
720 self.init_readline()
721 778
779 if not self.readline_use:
780 return
781
782 import IPython.utils.rlineimpl as readline
783
784 if not readline.have_readline:
785 self.has_readline = 0
786 self.readline = None
787 # no point in bugging windows users with this every time:
788 warn('Readline services not available on this platform.')
789 else:
790 sys.modules['readline'] = readline
791 import atexit
792 from IPython.core.completer import IPCompleter
793 self.Completer = IPCompleter(self,
794 self.user_ns,
795 self.user_global_ns,
796 self.readline_omit__names,
797 self.alias_table)
798 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
799 self.strdispatchers['complete_command'] = sdisp
800 self.Completer.custom_completers = sdisp
801 # Platform-specific configuration
802 if os.name == 'nt':
803 self.readline_startup_hook = readline.set_pre_input_hook
804 else:
805 self.readline_startup_hook = readline.set_startup_hook
806
807 # Load user's initrc file (readline config)
808 # Or if libedit is used, load editrc.
809 inputrc_name = os.environ.get('INPUTRC')
810 if inputrc_name is None:
811 home_dir = get_home_dir()
812 if home_dir is not None:
813 inputrc_name = '.inputrc'
814 if readline.uses_libedit:
815 inputrc_name = '.editrc'
816 inputrc_name = os.path.join(home_dir, inputrc_name)
817 if os.path.isfile(inputrc_name):
818 try:
819 readline.read_init_file(inputrc_name)
820 except:
821 warn('Problems reading readline initialization file <%s>'
822 % inputrc_name)
823
824 self.has_readline = 1
825 self.readline = readline
826 # save this in sys so embedded copies can restore it properly
827 sys.ipcompleter = self.Completer.complete
828 self.set_completer()
829
830 # Configure readline according to user's prefs
831 # This is only done if GNU readline is being used. If libedit
832 # is being used (as on Leopard) the readline config is
833 # not run as the syntax for libedit is different.
834 if not readline.uses_libedit:
835 for rlcommand in self.readline_parse_and_bind:
836 #print "loading rl:",rlcommand # dbg
837 readline.parse_and_bind(rlcommand)
838
839 # Remove some chars from the delimiters list. If we encounter
840 # unicode chars, discard them.
841 delims = readline.get_completer_delims().encode("ascii", "ignore")
842 delims = delims.translate(string._idmap,
843 self.readline_remove_delims)
844 readline.set_completer_delims(delims)
845 # otherwise we end up with a monster history after a while:
846 readline.set_history_length(1000)
847 try:
848 #print '*** Reading readline history' # dbg
849 readline.read_history_file(self.histfile)
850 except IOError:
851 pass # It doesn't exist yet.
852
853 atexit.register(self.atexit_operations)
854 del atexit
855
856 # Configure auto-indent for all platforms
857 self.set_autoindent(self.autoindent)
858
859 def init_prompts(self):
722 860 # Initialize cache, set in/out prompts and printing system
723 861 self.outputcache = CachedOutput(self,
724 862 self.cache_size,
@@ -737,6 +875,7 b' class InteractiveShell(Component, Magic):'
737 875 except AttributeError:
738 876 pass
739 877
878 def init_displayhook(self):
740 879 # I don't like assigning globally to sys, because it means when
741 880 # embedding instances, each embedded instance overrides the previous
742 881 # choice. But sys.displayhook seems to be called internally by exec,
@@ -745,24 +884,25 b' class InteractiveShell(Component, Magic):'
745 884 self.sys_displayhook = sys.displayhook
746 885 sys.displayhook = self.outputcache
747 886
887 def init_reload_doctest(self):
748 888 # Do a proper resetting of doctest, including the necessary displayhook
749 889 # monkeypatching
750 890 try:
751 891 doctest_reload()
752 892 except ImportError:
753 893 warn("doctest module does not exist.")
754
894
895 def init_magics(self):
755 896 # Set user colors (don't do it in the constructor above so that it
756 897 # doesn't crash if colors option is invalid)
757 898 self.magic_colors(self.colors)
758 899
900 def init_pdb(self):
759 901 # Set calling of pdb on exceptions
902 # self.call_pdb is a property
760 903 self.call_pdb = self.pdb
761 904
762
763
764 self.hooks.late_startup_hook()
765
905 def init_exec_commands(self):
766 906 for cmd in self.autoexec:
767 907 #print "autoexec>",cmd #dbg
768 908 self.api.runlines(cmd)
@@ -809,9 +949,12 b' class InteractiveShell(Component, Magic):'
809 949
810 950 self.user_ns['_sh'] = shadowns
811 951
812 # Fill the history zero entry, user counter starts at 1
813 self.input_hist.append('\n')
814 self.input_hist_raw.append('\n')
952 # Put 'help' in the user namespace
953 try:
954 from site import _Helper
955 self.user_ns['help'] = _Helper()
956 except ImportError:
957 warn('help() not available - check site.py')
815 958
816 959 def add_builtins(self):
817 960 """Store ipython references into the builtin namespace.
@@ -825,6 +968,17 b' class InteractiveShell(Component, Magic):'
825 968 # when it is refactored.
826 969 __builtin__.exit = Quitter(self,'exit')
827 970 __builtin__.quit = Quitter(self,'quit')
971
972 # Recursive reload
973 try:
974 from IPython.lib import deepreload
975 if self.deep_reload:
976 __builtin__.reload = deepreload.reload
977 else:
978 __builtin__.dreload = deepreload.reload
979 del deepreload
980 except ImportError:
981 pass
828 982
829 983 # TODO: deprecate all of these, they are unsafe. Why though?
830 984 builtins_new = dict(__IPYTHON__ = self,
@@ -1287,87 +1441,6 b' class InteractiveShell(Component, Magic):'
1287 1441 self.readline.insert_text(self.rl_next_input)
1288 1442 self.rl_next_input = None
1289 1443
1290 def init_readline(self):
1291 """Command history completion/saving/reloading."""
1292
1293
1294 import IPython.utils.rlineimpl as readline
1295
1296 if not readline.have_readline:
1297 self.has_readline = 0
1298 self.readline = None
1299 # no point in bugging windows users with this every time:
1300 warn('Readline services not available on this platform.')
1301 else:
1302 sys.modules['readline'] = readline
1303 import atexit
1304 from IPython.core.completer import IPCompleter
1305 self.Completer = IPCompleter(self,
1306 self.user_ns,
1307 self.user_global_ns,
1308 self.readline_omit__names,
1309 self.alias_table)
1310 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1311 self.strdispatchers['complete_command'] = sdisp
1312 self.Completer.custom_completers = sdisp
1313 # Platform-specific configuration
1314 if os.name == 'nt':
1315 self.readline_startup_hook = readline.set_pre_input_hook
1316 else:
1317 self.readline_startup_hook = readline.set_startup_hook
1318
1319 # Load user's initrc file (readline config)
1320 # Or if libedit is used, load editrc.
1321 inputrc_name = os.environ.get('INPUTRC')
1322 if inputrc_name is None:
1323 home_dir = get_home_dir()
1324 if home_dir is not None:
1325 inputrc_name = '.inputrc'
1326 if readline.uses_libedit:
1327 inputrc_name = '.editrc'
1328 inputrc_name = os.path.join(home_dir, inputrc_name)
1329 if os.path.isfile(inputrc_name):
1330 try:
1331 readline.read_init_file(inputrc_name)
1332 except:
1333 warn('Problems reading readline initialization file <%s>'
1334 % inputrc_name)
1335
1336 self.has_readline = 1
1337 self.readline = readline
1338 # save this in sys so embedded copies can restore it properly
1339 sys.ipcompleter = self.Completer.complete
1340 self.set_completer()
1341
1342 # Configure readline according to user's prefs
1343 # This is only done if GNU readline is being used. If libedit
1344 # is being used (as on Leopard) the readline config is
1345 # not run as the syntax for libedit is different.
1346 if not readline.uses_libedit:
1347 for rlcommand in self.readline_parse_and_bind:
1348 #print "loading rl:",rlcommand # dbg
1349 readline.parse_and_bind(rlcommand)
1350
1351 # Remove some chars from the delimiters list. If we encounter
1352 # unicode chars, discard them.
1353 delims = readline.get_completer_delims().encode("ascii", "ignore")
1354 delims = delims.translate(string._idmap,
1355 self.readline_remove_delims)
1356 readline.set_completer_delims(delims)
1357 # otherwise we end up with a monster history after a while:
1358 readline.set_history_length(1000)
1359 try:
1360 #print '*** Reading readline history' # dbg
1361 readline.read_history_file(self.histfile)
1362 except IOError:
1363 pass # It doesn't exist yet.
1364
1365 atexit.register(self.atexit_operations)
1366 del atexit
1367
1368 # Configure auto-indent for all platforms
1369 self.set_autoindent(self.autoindent)
1370
1371 1444 def ask_yes_no(self,prompt,default=True):
1372 1445 if self.quiet:
1373 1446 return True
@@ -2480,7 +2553,7 b' class InteractiveShell(Component, Magic):'
2480 2553 #print 'line:<%r>' % line # dbg
2481 2554 self.magic_pinfo(line)
2482 2555 else:
2483 page(self.usage,screen_lines=self.screen_length)
2556 page(self.usage,screen_lines=self.usable_screen_length)
2484 2557 return '' # Empty string is needed here!
2485 2558 except:
2486 2559 # Pass any other exceptions through to the normal handler
@@ -2562,7 +2635,6 b' class InteractiveShell(Component, Magic):'
2562 2635 """Handle interactive exit.
2563 2636
2564 2637 This method calls the ask_exit callback."""
2565 print "IN self.exit", self.confirm_exit
2566 2638 if self.confirm_exit:
2567 2639 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2568 2640 self.ask_exit()
@@ -485,7 +485,7 b' Currently the magic system has the following functions:\\n"""'
485 485 (' '+mesc).join(self.lsmagic()),
486 486 Magic.auto_status[self.shell.automagic] ) )
487 487
488 page(outmsg,screen_lines=self.shell.screen_length)
488 page(outmsg,screen_lines=self.shell.usable_screen_length)
489 489
490 490
491 491 def magic_autoindent(self, parameter_s = ''):
@@ -1423,7 +1423,7 b' Currently the magic system has the following functions:\\n"""'
1423 1423 output = stdout_trap.getvalue()
1424 1424 output = output.rstrip()
1425 1425
1426 page(output,screen_lines=self.shell.screen_length)
1426 page(output,screen_lines=self.shell.usable_screen_length)
1427 1427 print sys_exit,
1428 1428
1429 1429 dump_file = opts.D[0]
@@ -2530,10 +2530,10 b' Defaulting color scheme to \'NoColor\'"""'
2530 2530 than more) in your system, using colored object information displays
2531 2531 will not work properly. Test it and see."""
2532 2532
2533 self.shell.color_info = 1 - self.shell.color_info
2533 self.shell.color_info = not self.shell.color_info
2534 2534 self.magic_colors(self.shell.colors)
2535 2535 print 'Object introspection functions have now coloring:',
2536 print ['OFF','ON'][self.shell.color_info]
2536 print ['OFF','ON'][int(self.shell.color_info)]
2537 2537
2538 2538 def magic_Pprint(self, parameter_s=''):
2539 2539 """Toggle pretty printing on/off."""
@@ -3267,7 +3267,7 b' Defaulting color scheme to \'NoColor\'"""'
3267 3267 return
3268 3268
3269 3269 page(self.shell.pycolorize(cont),
3270 screen_lines=self.shell.screen_length)
3270 screen_lines=self.shell.usable_screen_length)
3271 3271
3272 3272 def _rerun_pasted(self):
3273 3273 """ Rerun a previously pasted command.
@@ -578,9 +578,11 b' quick_guide = """\\'
578 578 help -> Python's own help system.
579 579 object? -> Details about 'object'. ?object also works, ?? prints more."""
580 580
581 banner_parts = [
581 default_banner_parts = [
582 582 'Python %s' % (sys.version.split('\n')[0],),
583 583 'Type "copyright", "credits" or "license" for more information.\n',
584 584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
585 585 quick_guide
586 586 ]
587
588 default_banner = '\n'.join(default_banner_parts)
@@ -858,4 +858,42 b' class CBool(Bool):'
858 858 try:
859 859 return bool(value)
860 860 except:
861 self.error(obj, value) No newline at end of file
861 self.error(obj, value)
862
863 class Enum(TraitletType):
864
865 def __init__(self, values, default_value=None, allow_none=True, **metadata):
866 self.values = values
867 self._allow_none = allow_none
868 super(Enum, self).__init__(default_value, **metadata)
869
870 def validate(self, obj, value):
871 if value is None:
872 if self._allow_none:
873 return value
874
875 if value in self.values:
876 return value
877 self.error(obj, value)
878
879 def info(self):
880 """ Returns a description of the trait."""
881 result = 'any of ' + repr(self.values)
882 if self._allow_none:
883 return result + ' or None'
884 return result
885
886 class CaselessStrEnum(Enum):
887
888 def validate(self, obj, value):
889 if value is None:
890 if self._allow_none:
891 return value
892
893 if not isinstance(value, str):
894 self.error(obj, value)
895
896 for v in self.values:
897 if v.lower() == value.lower():
898 return v
899 self.error(obj, value) No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now