##// END OF EJS Templates
Merging ipython-app branch into config-refactor....
Brian Granger -
r2228:2b35d9f0 merge
parent child Browse files
Show More
@@ -0,0 +1,45 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Autocall capabilities for IPython.core.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26
27 #-----------------------------------------------------------------------------
28 # Code
29 #-----------------------------------------------------------------------------
30
31 class IPyAutocall(object):
32 """ Instances of this class are always autocalled
33
34 This happens regardless of 'autocall' variable state. Use this to
35 develop macro-like mechanisms.
36 """
37
38 def set_ip(self,ip):
39 """ Will be used to set _ip point to current ipython instance b/f call
40
41 Override this method if you don't want this to happen.
42
43 """
44 self._ip = ip
45
@@ -0,0 +1,104 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A context manager for managing things injected into :mod:`__builtin__`.
5
6 Authors:
7
8 * Brian Granger
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
22 import __builtin__
23
24 from IPython.core.component import Component
25 from IPython.core.quitter import Quitter
26
27 #-----------------------------------------------------------------------------
28 # Classes and functions
29 #-----------------------------------------------------------------------------
30
31
32 class BuiltinUndefined(object): pass
33 BuiltinUndefined = BuiltinUndefined()
34
35
36 class BuiltinTrap(Component):
37
38 def __init__(self, parent, name=None, config=None):
39 super(BuiltinTrap, self).__init__(parent, name, config)
40 # Don't just grab parent!!!
41 from IPython.core.iplib import InteractiveShell
42 self.shell = InteractiveShell.get_instances(root=self.root)[0]
43 self._orig_builtins = {}
44
45 def __enter__(self):
46 self.set()
47 # I return self, so callers can use add_builtin in a with clause.
48 return self
49
50 def __exit__(self, type, value, traceback):
51 self.unset()
52 return True
53
54 def add_builtin(self, key, value):
55 """Add a builtin and save the original."""
56 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
57 self._orig_builtins[key] = orig
58 __builtin__.__dict__[key] = value
59
60 def remove_builtin(self, key):
61 """Remove an added builtin and re-set the original."""
62 try:
63 orig = self._orig_builtins.pop(key)
64 except KeyError:
65 pass
66 else:
67 if orig is BuiltinUndefined:
68 del __builtin__.__dict__[key]
69 else:
70 __builtin__.__dict__[key] = orig
71
72 def set(self):
73 """Store ipython references in the __builtin__ namespace."""
74 self.add_builtin('exit', Quitter(self.shell, 'exit'))
75 self.add_builtin('quit', Quitter(self.shell, 'quit'))
76
77 # Recursive reload function
78 try:
79 from IPython.lib import deepreload
80 if self.shell.deep_reload:
81 self.add_builtin('reload', deepreload.reload)
82 else:
83 self.add_builtin('dreload', deepreload.reload)
84 del deepreload
85 except ImportError:
86 pass
87
88 # Keep in the builtins a flag for when IPython is active. We set it
89 # with setdefault so that multiple nested IPythons don't clobber one
90 # another. Each will increase its value by one upon being activated,
91 # which also gives us a way to determine the nesting level.
92 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
93
94 def unset(self):
95 """Remove any builtins which might have been added by add_builtins, or
96 restore overwritten ones to their previous values."""
97 for key in self._orig_builtins.keys():
98 self.remove_builtin(key)
99 self._orig_builtins.clear()
100 self._builtins_added = False
101 try:
102 del __builtin__.__dict__['__IPYTHON__active']
103 except KeyError:
104 pass No newline at end of file
@@ -0,0 +1,282 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 An embedded IPython shell.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26 from __future__ import with_statement
27
28 import sys
29
30 from IPython.core import ultratb
31 from IPython.core.iplib import InteractiveShell
32
33 from IPython.utils.traitlets import Bool, Str, CBool
34 from IPython.utils.genutils import ask_yes_no
35
36 #-----------------------------------------------------------------------------
37 # Classes and functions
38 #-----------------------------------------------------------------------------
39
40 # This is an additional magic that is exposed in embedded shells.
41 def kill_embedded(self,parameter_s=''):
42 """%kill_embedded : deactivate for good the current embedded IPython.
43
44 This function (after asking for confirmation) sets an internal flag so that
45 an embedded IPython will never activate again. This is useful to
46 permanently disable a shell that is being called inside a loop: once you've
47 figured out what you needed from it, you may then kill it and the program
48 will then continue to run without the interactive shell interfering again.
49 """
50
51 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
52 "(y/n)? [y/N] ",'n')
53 if kill:
54 self.embedded_active = False
55 print "This embedded IPython will not reactivate anymore once you exit."
56
57
58 class InteractiveShellEmbed(InteractiveShell):
59
60 dummy_mode = Bool(False)
61 exit_msg = Str('')
62 embedded = CBool(True)
63 embedded_active = CBool(True)
64
65 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
66 user_ns=None, user_global_ns=None,
67 banner1=None, banner2=None,
68 custom_exceptions=((),None), exit_msg=''):
69
70 # First we need to save the state of sys.displayhook and
71 # sys.ipcompleter so we can restore it when we are done.
72 self.save_sys_displayhook()
73 self.save_sys_ipcompleter()
74
75 super(InteractiveShellEmbed,self).__init__(
76 parent=parent, config=config, ipythondir=ipythondir, usage=usage,
77 user_ns=user_ns, user_global_ns=user_global_ns,
78 banner1=banner1, banner2=banner2,
79 custom_exceptions=custom_exceptions)
80
81 self.save_sys_displayhook_embed()
82 self.exit_msg = exit_msg
83 self.define_magic("kill_embedded", kill_embedded)
84
85 # don't use the ipython crash handler so that user exceptions aren't
86 # trapped
87 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
88 mode=self.xmode,
89 call_pdb=self.pdb)
90
91 self.restore_sys_displayhook()
92 self.restore_sys_ipcompleter()
93
94 def init_sys_modules(self):
95 pass
96
97 def save_sys_displayhook(self):
98 # sys.displayhook is a global, we need to save the user's original
99 # Don't rely on __displayhook__, as the user may have changed that.
100 self.sys_displayhook_orig = sys.displayhook
101
102 def save_sys_ipcompleter(self):
103 """Save readline completer status."""
104 try:
105 #print 'Save completer',sys.ipcompleter # dbg
106 self.sys_ipcompleter_orig = sys.ipcompleter
107 except:
108 pass # not nested with IPython
109
110 def restore_sys_displayhook(self):
111 sys.displayhook = self.sys_displayhook_orig
112
113 def restore_sys_ipcompleter(self):
114 """Restores the readline completer which was in place.
115
116 This allows embedded IPython within IPython not to disrupt the
117 parent's completion.
118 """
119 try:
120 self.readline.set_completer(self.sys_ipcompleter_orig)
121 sys.ipcompleter = self.sys_ipcompleter_orig
122 except:
123 pass
124
125 def save_sys_displayhook_embed(self):
126 self.sys_displayhook_embed = sys.displayhook
127
128 def restore_sys_displayhook_embed(self):
129 sys.displayhook = self.sys_displayhook_embed
130
131 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
132 stack_depth=1):
133 """Activate the interactive interpreter.
134
135 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
136 the interpreter shell with the given local and global namespaces, and
137 optionally print a header string at startup.
138
139 The shell can be globally activated/deactivated using the
140 set/get_dummy_mode methods. This allows you to turn off a shell used
141 for debugging globally.
142
143 However, *each* time you call the shell you can override the current
144 state of dummy_mode with the optional keyword parameter 'dummy'. For
145 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
146 can still have a specific call work by making it as IPShell(dummy=0).
147
148 The optional keyword parameter dummy controls whether the call
149 actually does anything.
150 """
151
152 # If the user has turned it off, go away
153 if not self.embedded_active:
154 return
155
156 # Normal exits from interactive mode set this flag, so the shell can't
157 # re-enter (it checks this variable at the start of interactive mode).
158 self.exit_now = False
159
160 # Allow the dummy parameter to override the global __dummy_mode
161 if dummy or (dummy != 0 and self.dummy_mode):
162 return
163
164 self.restore_sys_displayhook_embed()
165
166 if self.has_readline:
167 self.set_completer()
168
169 if self.banner and header:
170 format = '%s\n%s\n'
171 else:
172 format = '%s%s\n'
173 banner = format % (self.banner,header)
174
175 # Call the embedding code with a stack depth of 1 so it can skip over
176 # our call and get the original caller's namespaces.
177 self.mainloop(banner, local_ns, global_ns,
178 stack_depth=stack_depth)
179
180 if self.exit_msg is not None:
181 print self.exit_msg
182
183 # Restore global systems (display, completion)
184 self.restore_sys_displayhook()
185 self.restore_sys_ipcompleter()
186
187 def mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
188 """Embeds IPython into a running python program.
189
190 Input:
191
192 - header: An optional header message can be specified.
193
194 - local_ns, global_ns: working namespaces. If given as None, the
195 IPython-initialized one is updated with __main__.__dict__, so that
196 program variables become visible but user-specific configuration
197 remains possible.
198
199 - stack_depth: specifies how many levels in the stack to go to
200 looking for namespaces (when local_ns and global_ns are None). This
201 allows an intermediate caller to make sure that this function gets
202 the namespace from the intended level in the stack. By default (0)
203 it will get its locals and globals from the immediate caller.
204
205 Warning: it's possible to use this in a program which is being run by
206 IPython itself (via %run), but some funny things will happen (a few
207 globals get overwritten). In the future this will be cleaned up, as
208 there is no fundamental reason why it can't work perfectly."""
209
210 # Get locals and globals from caller
211 if local_ns is None or global_ns is None:
212 call_frame = sys._getframe(stack_depth).f_back
213
214 if local_ns is None:
215 local_ns = call_frame.f_locals
216 if global_ns is None:
217 global_ns = call_frame.f_globals
218
219 # Update namespaces and fire up interpreter
220
221 # The global one is easy, we can just throw it in
222 self.user_global_ns = global_ns
223
224 # but the user/local one is tricky: ipython needs it to store internal
225 # data, but we also need the locals. We'll copy locals in the user
226 # one, but will track what got copied so we can delete them at exit.
227 # This is so that a later embedded call doesn't see locals from a
228 # previous call (which most likely existed in a separate scope).
229 local_varnames = local_ns.keys()
230 self.user_ns.update(local_ns)
231 #self.user_ns['local_ns'] = local_ns # dbg
232
233 # Patch for global embedding to make sure that things don't overwrite
234 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
235 # FIXME. Test this a bit more carefully (the if.. is new)
236 if local_ns is None and global_ns is None:
237 self.user_global_ns.update(__main__.__dict__)
238
239 # make sure the tab-completer has the correct frame information, so it
240 # actually completes using the frame's locals/globals
241 self.set_completer_frame()
242
243 with self.builtin_trap:
244 self.interact(header)
245
246 # now, purge out the user namespace from anything we might have added
247 # from the caller's local namespace
248 delvar = self.user_ns.pop
249 for var in local_varnames:
250 delvar(var,None)
251
252
253 _embedded_shell = None
254
255
256 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
257 exit_msg=''):
258 """Call this to embed IPython at the current point in your program.
259
260 The first invocation of this will create an :class:`InteractiveShellEmbed`
261 instance and then call it. Consecutive calls just call the already
262 created instance.
263
264 Here is a simple example::
265
266 from IPython import embed
267 a = 10
268 b = 20
269 embed('First time')
270 c = 30
271 d = 40
272 embed
273
274 Full customization can be done by passing a :class:`Struct` in as the
275 config argument.
276 """
277 global _embedded_shell
278 if _embedded_shell is None:
279 _embedded_shell = InteractiveShellEmbed(config=config,
280 usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg)
281 _embedded_shell(header=header, stack_depth=2)
282
@@ -0,0 +1,52 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Global exception classes for IPython.core.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Exception classes
28 #-----------------------------------------------------------------------------
29
30 class IPythonCoreError(Exception):
31 pass
32
33
34 class TryNext(IPythonCoreError):
35 """Try next hook exception.
36
37 Raise this in your hook function to indicate that the next hook handler
38 should be used to handle the operation. If you pass arguments to the
39 constructor those arguments will be used by the next hook instead of the
40 original ones.
41 """
42
43 def __init__(self, *args, **kwargs):
44 self.args = args
45 self.kwargs = kwargs
46
47 class UsageError(IPythonCoreError):
48 """Error in magic function arguments, etc.
49
50 Something that probably won't warrant a full traceback, but should
51 nevertheless interrupt a macro / batch file.
52 """ No newline at end of file
@@ -0,0 +1,317 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 The main IPython application object
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26 import os
27 import sys
28 import warnings
29
30 from IPython.core.application import Application
31 from IPython.core import release
32 from IPython.core.iplib import InteractiveShell
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
42
43 ipython_desc = """
44 A Python shell with automatic history (input and output), dynamic object
45 introspection, easier configuration, command completion, access to the system
46 shell and more.
47 """
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 (('-term_title',), dict(
217 action='store_true', dest='TERM_TITLE', default=NoDefault,
218 help="Enable auto setting the terminal title.")
219 ),
220 (('-noterm_title',), dict(
221 action='store_false', dest='TERM_TITLE', default=NoDefault,
222 help="Disable auto setting the terminal title.")
223 ),
224 (('-xmode',), dict(
225 type=str, dest='XMODE', default=NoDefault,
226 help="Exception mode ('Plain','Context','Verbose')")
227 ),
228 # These are only here to get the proper deprecation warnings
229 (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict(
230 action='store_true', dest='THREADED_SHELL', default=NoDefault,
231 help="These command line flags are deprecated, see the 'gui' magic.")
232 ),
233 )
234
235
236 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
237
238 arguments = cl_args
239
240
241 class IPythonApp(Application):
242 name = 'ipython'
243 config_file_name = 'ipython_config.py'
244
245 def create_command_line_config(self):
246 """Create and return a command line config loader."""
247 return IPythonAppCLConfigLoader(
248 description=ipython_desc,
249 version=release.version)
250
251 def post_load_command_line_config(self):
252 """Do actions after loading cl config."""
253 clc = self.command_line_config
254
255 # This needs to be set here, the rest are set in pre_construct.
256 if hasattr(clc, 'CLASSIC'):
257 if clc.CLASSIC: clc.QUICK = 1
258
259 # Display the deprecation warnings about threaded shells
260 if hasattr(clc, 'THREADED_SHELL'):
261 threaded_shell_warning()
262 del clc['THREADED_SHELL']
263
264 def load_file_config(self):
265 if hasattr(self.command_line_config, 'QUICK'):
266 if self.command_line_config.QUICK:
267 self.file_config = Struct()
268 return
269 super(IPythonApp, self).load_file_config()
270
271 def post_load_file_config(self):
272 """Logic goes here."""
273
274 def pre_construct(self):
275 config = self.master_config
276
277 if hasattr(config, 'CLASSIC'):
278 if config.CLASSIC:
279 config.QUICK = 1
280 config.CACHE_SIZE = 0
281 config.PPRINT = 0
282 config.PROMPT_IN1 = '>>> '
283 config.PROMPT_IN2 = '... '
284 config.PROMPT_OUT = ''
285 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = ''
286 config.COLORS = 'NoColor'
287 config.XMODE = 'Plain'
288
289 # All this should be moved to traitlet handlers in InteractiveShell
290 # But, currently InteractiveShell doesn't have support for changing
291 # these values at runtime. Once we support that, this should
292 # be moved there!!!
293 if hasattr(config, 'NOSEP'):
294 if config.NOSEP:
295 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0'
296
297 def construct(self):
298 # I am a little hesitant to put these into InteractiveShell itself.
299 # But that might be the place for them
300 sys.path.insert(0, '')
301 # add personal ipythondir to sys.path so that users can put things in
302 # there for customization
303 sys.path.append(os.path.abspath(self.ipythondir))
304
305 # Create an InteractiveShell instance
306 self.shell = InteractiveShell(
307 parent=None,
308 config=self.master_config
309 )
310
311 def start_app(self):
312 self.shell.mainloop()
313
314
315 if __name__ == '__main__':
316 app = IPythonApp()
317 app.start() No newline at end of file
@@ -0,0 +1,219 b''
1 # -*- coding: utf-8 -*-
2 """
3 Main IPython Component
4 """
5
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
14
15 #-----------------------------------------------------------------------------
16 # Imports
17 #-----------------------------------------------------------------------------
18
19 import glob
20 import os
21 import shutil
22 import sys
23
24 from IPython.utils.genutils import *
25
26 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
27 """Install or upgrade the user configuration directory.
28
29 Can be called when running for the first time or to upgrade the user's
30 .ipython/ directory.
31
32 Parameters
33 ----------
34 ipythondir : path
35 The directory to be used for installation/upgrade. In 'install' mode,
36 if this path already exists, the function exits immediately.
37
38 rc_suffix : str
39 Extension for the config files. On *nix platforms it is typically the
40 empty string, while Windows normally uses '.ini'.
41
42 mode : str, optional
43 Valid modes are 'install' and 'upgrade'.
44
45 interactive : bool, optional
46 If False, do not wait for user input on any errors. Normally after
47 printing its status information, this function waits for the user to
48 hit Return before proceeding. This is because the default use case is
49 when first installing the IPython configuration, so we want the user to
50 acknowledge the initial message, which contains some useful
51 information.
52 """
53
54 # For automatic use, deactivate all i/o
55 if interactive:
56 def wait():
57 try:
58 raw_input("Please press <RETURN> to start IPython.")
59 except EOFError:
60 print >> Term.cout
61 print '*'*70
62
63 def printf(s):
64 print s
65 else:
66 wait = lambda : None
67 printf = lambda s : None
68
69 # Install mode should be re-entrant: if the install dir already exists,
70 # bail out cleanly.
71 # XXX. This is too hasty to return. We need to check to make sure that
72 # all the expected config files and directories are actually there. We
73 # currently have a failure mode if someone deletes a needed config file
74 # but still has the ipythondir.
75 if mode == 'install' and os.path.isdir(ipythondir):
76 return
77
78 cwd = os.getcwd() # remember where we started
79 glb = glob.glob
80
81 printf('*'*70)
82 if mode == 'install':
83 printf(
84 """Welcome to IPython. I will try to create a personal configuration directory
85 where you can customize many aspects of IPython's functionality in:\n""")
86 else:
87 printf('I am going to upgrade your configuration in:')
88
89 printf(ipythondir)
90
91 rcdirend = os.path.join('IPython','config','userconfig')
92 cfg = lambda d: os.path.join(d,rcdirend)
93 try:
94 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
95 printf("Initializing from configuration: %s" % rcdir)
96 except IndexError:
97 warning = """
98 Installation error. IPython's directory was not found.
99
100 Check the following:
101
102 The ipython/IPython directory should be in a directory belonging to your
103 PYTHONPATH environment variable (that is, it should be in a directory
104 belonging to sys.path). You can copy it explicitly there or just link to it.
105
106 IPython will create a minimal default configuration for you.
107
108 """
109 warn(warning)
110 wait()
111
112 if sys.platform =='win32':
113 inif = 'ipythonrc.ini'
114 else:
115 inif = 'ipythonrc'
116 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
117 inif : '# intentionally left blank' }
118 os.makedirs(ipythondir, mode = 0777)
119 for f, cont in minimal_setup.items():
120 # In 2.5, this can be more cleanly done using 'with'
121 fobj = file(ipythondir + '/' + f,'w')
122 fobj.write(cont)
123 fobj.close()
124
125 return
126
127 if mode == 'install':
128 try:
129 shutil.copytree(rcdir,ipythondir)
130 os.chdir(ipythondir)
131 rc_files = glb("ipythonrc*")
132 for rc_file in rc_files:
133 os.rename(rc_file,rc_file+rc_suffix)
134 except:
135 warning = """
136
137 There was a problem with the installation:
138 %s
139 Try to correct it or contact the developers if you think it's a bug.
140 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
141 warn(warning)
142 wait()
143 return
144
145 elif mode == 'upgrade':
146 try:
147 os.chdir(ipythondir)
148 except:
149 printf("""
150 Can not upgrade: changing to directory %s failed. Details:
151 %s
152 """ % (ipythondir,sys.exc_info()[1]) )
153 wait()
154 return
155 else:
156 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
157 for new_full_path in sources:
158 new_filename = os.path.basename(new_full_path)
159 if new_filename.startswith('ipythonrc'):
160 new_filename = new_filename + rc_suffix
161 # The config directory should only contain files, skip any
162 # directories which may be there (like CVS)
163 if os.path.isdir(new_full_path):
164 continue
165 if os.path.exists(new_filename):
166 old_file = new_filename+'.old'
167 if os.path.exists(old_file):
168 os.remove(old_file)
169 os.rename(new_filename,old_file)
170 shutil.copy(new_full_path,new_filename)
171 else:
172 raise ValueError('unrecognized mode for install: %r' % mode)
173
174 # Fix line-endings to those native to each platform in the config
175 # directory.
176 try:
177 os.chdir(ipythondir)
178 except:
179 printf("""
180 Problem: changing to directory %s failed.
181 Details:
182 %s
183
184 Some configuration files may have incorrect line endings. This should not
185 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
186 wait()
187 else:
188 for fname in glb('ipythonrc*'):
189 try:
190 native_line_ends(fname,backup=0)
191 except IOError:
192 pass
193
194 if mode == 'install':
195 printf("""
196 Successful installation!
197
198 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
199 IPython manual (there are both HTML and PDF versions supplied with the
200 distribution) to make sure that your system environment is properly configured
201 to take advantage of IPython's features.
202
203 Important note: the configuration system has changed! The old system is
204 still in place, but its setting may be partly overridden by the settings in
205 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
206 if some of the new settings bother you.
207
208 """)
209 else:
210 printf("""
211 Successful upgrade!
212
213 All files in your directory:
214 %(ipythondir)s
215 which would have been overwritten by the upgrade were backed up with a .old
216 extension. If you had made particular customizations in those files you may
217 want to merge them back into the new files.""" % locals() )
218 wait()
219 os.chdir(cwd) No newline at end of file
@@ -0,0 +1,306 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Paging capabilities for IPython.core
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 rid of that dependency, we could move it there.
16 -----
17 """
18
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Imports
28 #-----------------------------------------------------------------------------
29
30 import os
31 import re
32 import sys
33
34 from IPython.core import ipapi
35 from IPython.core.error import TryNext
36 from IPython.utils.genutils import (
37 chop, Term
38 )
39
40 if os.name == "nt":
41 from IPython.utils.winconsole import get_console_size
42
43
44 #-----------------------------------------------------------------------------
45 # Classes and functions
46 #-----------------------------------------------------------------------------
47
48 esc_re = re.compile(r"(\x1b[^m]+m)")
49
50 def page_dumb(strng,start=0,screen_lines=25):
51 """Very dumb 'pager' in Python, for when nothing else works.
52
53 Only moves forward, same interface as page(), except for pager_cmd and
54 mode."""
55
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
59 print >>Term.cout, os.linesep.join(screens[0])
60 else:
61 last_escape = ""
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
64 print >>Term.cout, last_escape + hunk
65 if not page_more():
66 return
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
71
72 #----------------------------------------------------------------------------
73 def page(strng,start=0,screen_lines=0,pager_cmd = None):
74 """Print a string, piping through a pager after a certain length.
75
76 The screen_lines parameter specifies the number of *usable* lines of your
77 terminal screen (total lines minus lines you need to reserve to show other
78 information).
79
80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 your screen size and will only use up to (screen_size+screen_lines) for
82 printing, paging after that. That is, if you want auto-detection but need
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 auto-detection without any lines reserved simply use screen_lines = 0.
85
86 If a string won't fit in the allowed lines, it is sent through the
87 specified pager command. If none given, look for PAGER in the environment,
88 and ultimately default to less.
89
90 If no system pager works, the string is sent through a 'dumb pager'
91 written in python, very simplistic.
92 """
93
94 # Some routines may auto-compute start offsets incorrectly and pass a
95 # negative value. Offset to 0 for robustness.
96 start = max(0,start)
97
98 # first, try the hook
99 ip = ipapi.get()
100 if ip:
101 try:
102 ip.hooks.show_in_pager(strng)
103 return
104 except TryNext:
105 pass
106
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 TERM = os.environ.get('TERM','dumb')
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 print strng
111 return
112 # chop off the topmost part of the string we don't want to see
113 str_lines = strng.split(os.linesep)[start:]
114 str_toprint = os.linesep.join(str_lines)
115 num_newlines = len(str_lines)
116 len_str = len(str_toprint)
117
118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 # takes. Very basic, but good enough for docstrings in reasonable
120 # terminals. If someone later feels like refining it, it's not hard.
121 numlines = max(num_newlines,int(len_str/80)+1)
122
123 if os.name == "nt":
124 screen_lines_def = get_console_size(defaulty=25)[1]
125 else:
126 screen_lines_def = 25 # default value if we can't auto-determine
127
128 # auto-determine screen size
129 if screen_lines <= 0:
130 if TERM=='xterm':
131 use_curses = USE_CURSES
132 else:
133 # curses causes problems on many terminals other than xterm.
134 use_curses = False
135 if use_curses:
136 # There is a bug in curses, where *sometimes* it fails to properly
137 # initialize, and then after the endwin() call is made, the
138 # terminal is left in an unusable state. Rather than trying to
139 # check everytime for this (by requesting and comparing termios
140 # flags each time), we just save the initial terminal state and
141 # unconditionally reset it every time. It's cheaper than making
142 # the checks.
143 term_flags = termios.tcgetattr(sys.stdout)
144 scr = curses.initscr()
145 screen_lines_real,screen_cols = scr.getmaxyx()
146 curses.endwin()
147 # Restore terminal state in case endwin() didn't.
148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
149 # Now we have what we needed: the screen size in rows/columns
150 screen_lines += screen_lines_real
151 #print '***Screen size:',screen_lines_real,'lines x',\
152 #screen_cols,'columns.' # dbg
153 else:
154 screen_lines += screen_lines_def
155
156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
157 if numlines <= screen_lines :
158 #print '*** normal print' # dbg
159 print >>Term.cout, str_toprint
160 else:
161 # Try to open pager and default to internal one if that fails.
162 # All failure modes are tagged as 'retval=1', to match the return
163 # value of a failed system command. If any intermediate attempt
164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
165 pager_cmd = get_pager_cmd(pager_cmd)
166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
167 if os.name == 'nt':
168 if pager_cmd.startswith('type'):
169 # The default WinXP 'type' command is failing on complex strings.
170 retval = 1
171 else:
172 tmpname = tempfile.mktemp('.txt')
173 tmpfile = file(tmpname,'wt')
174 tmpfile.write(strng)
175 tmpfile.close()
176 cmd = "%s < %s" % (pager_cmd,tmpname)
177 if os.system(cmd):
178 retval = 1
179 else:
180 retval = None
181 os.remove(tmpname)
182 else:
183 try:
184 retval = None
185 # if I use popen4, things hang. No idea why.
186 #pager,shell_out = os.popen4(pager_cmd)
187 pager = os.popen(pager_cmd,'w')
188 pager.write(strng)
189 pager.close()
190 retval = pager.close() # success returns None
191 except IOError,msg: # broken pipe when user quits
192 if msg.args == (32,'Broken pipe'):
193 retval = None
194 else:
195 retval = 1
196 except OSError:
197 # Other strange problems, sometimes seen in Win2k/cygwin
198 retval = 1
199 if retval is not None:
200 page_dumb(strng,screen_lines=screen_lines)
201
202 #----------------------------------------------------------------------------
203 def page_file(fname,start = 0, pager_cmd = None):
204 """Page a file, using an optional pager command and starting line.
205 """
206
207 pager_cmd = get_pager_cmd(pager_cmd)
208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
209
210 try:
211 if os.environ['TERM'] in ['emacs','dumb']:
212 raise EnvironmentError
213 xsys(pager_cmd + ' ' + fname)
214 except:
215 try:
216 if start > 0:
217 start -= 1
218 page(open(fname).read(),start)
219 except:
220 print 'Unable to show file',`fname`
221
222 #----------------------------------------------------------------------------
223 def get_pager_cmd(pager_cmd = None):
224 """Return a pager command.
225
226 Makes some attempts at finding an OS-correct one."""
227
228 if os.name == 'posix':
229 default_pager_cmd = 'less -r' # -r for color control sequences
230 elif os.name in ['nt','dos']:
231 default_pager_cmd = 'type'
232
233 if pager_cmd is None:
234 try:
235 pager_cmd = os.environ['PAGER']
236 except:
237 pager_cmd = default_pager_cmd
238 return pager_cmd
239
240 #-----------------------------------------------------------------------------
241 def get_pager_start(pager,start):
242 """Return the string for paging files with an offset.
243
244 This is the '+N' argument which less and more (under Unix) accept.
245 """
246
247 if pager in ['less','more']:
248 if start:
249 start_string = '+' + str(start)
250 else:
251 start_string = ''
252 else:
253 start_string = ''
254 return start_string
255
256 #----------------------------------------------------------------------------
257 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
259 import msvcrt
260 def page_more():
261 """ Smart pausing between pages
262
263 @return: True if need print more lines, False if quit
264 """
265 Term.cout.write('---Return to continue, q to quit--- ')
266 ans = msvcrt.getch()
267 if ans in ("q", "Q"):
268 result = False
269 else:
270 result = True
271 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
272 return result
273 else:
274 def page_more():
275 ans = raw_input('---Return to continue, q to quit--- ')
276 if ans.lower().startswith('q'):
277 return False
278 else:
279 return True
280
281 #----------------------------------------------------------------------------
282 def snip_print(str,width = 75,print_full = 0,header = ''):
283 """Print a string snipping the midsection to fit in width.
284
285 print_full: mode control:
286 - 0: only snip long strings
287 - 1: send to page() directly.
288 - 2: snip long strings and ask for full length viewing with page()
289 Return 1 if snipping was necessary, 0 otherwise."""
290
291 if print_full == 1:
292 page(header+str)
293 return 0
294
295 print header,
296 if len(str) < width:
297 print str
298 snip = 0
299 else:
300 whalf = int((width -5)/2)
301 print str[:whalf] + ' <...> ' + str[-whalf:]
302 snip = 1
303 if snip and print_full == 2:
304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
305 page(str)
306 return snip No newline at end of file
@@ -0,0 +1,38 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A simple class for quitting IPython.
5
6 Authors:
7
8 * Brian Granger
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
22
23 class Quitter(object):
24 """Simple class to handle exit, similar to Python 2.5's.
25
26 It handles exiting in an ipython-safe manner, which the one in Python 2.5
27 doesn't do (obviously, since it doesn't know about ipython)."""
28
29 def __init__(self, shell, name):
30 self.shell = shell
31 self.name = name
32
33 def __repr__(self):
34 return 'Type %s() to exit.' % self.name
35 __str__ = __repr__
36
37 def __call__(self):
38 self.shell.exit() No newline at end of file
@@ -19,11 +19,24 b' the new code in IPython.core.shell.'
19 19 from warnings import warn
20 20
21 21 msg = """
22 This module (IPython.Shell) has been moved to a new location
23 (IPython.core.shell) and is being refactored. Please update your code
24 to use the new IPython.core.shell module"""
22 This module (IPython.Shell) is deprecated. The classes that were in this
23 module have been replaced by:
24
25 IPShell->IPython.core.iplib.InteractiveShell
26 IPShellEmbed->IPython.core.embed.InteractiveShellEmbed
27
28 Please migrate your code to use these classes instead.
29 """
25 30
26 31 warn(msg, category=DeprecationWarning, stacklevel=1)
27 32
28 from IPython.core.shell import start, IPShell, IPShellEmbed
33 from IPython.core.iplib import InteractiveShell as IPShell
34 from IPython.core.embed import InteractiveShellEmbed as IPShellEmbed
35
36 def start(user_ns=None, embedded=False):
37 """Return an instance of :class:`InteractiveShell`."""
38 if embedded:
39 return InteractiveShellEmbed(user_ns=user_ns)
40 else:
41 return InteractiveShell(user_ns=user_ns)
29 42
@@ -1,67 +1,47 b''
1 # -*- coding: utf-8 -*-
1 #!/usr/bin/env python
2 # encoding: utf-8
2 3 """
3 IPython -- An enhanced Interactive Python
4 IPython.
4 5
5 One of Python's nicest features is its interactive interpreter. This allows
6 very fast testing of ideas without the overhead of creating test files as is
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
10
11 IPython tries to:
12
13 i - provide an efficient environment for interactive work in Python
14 programming. It tries to address what we see as shortcomings of the standard
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
17
18 ii - offer a flexible framework so that it can be used as the base
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
22 fields. Python is a fabulous language for implementing this kind of system
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
28 IPython requires Python 2.4 or newer.
6 IPython is a set of tools for interactive and exploratory computing in Python.
29 7 """
30 8
31 #*****************************************************************************
32 # Copyright (C) 2008-2009 The IPython Development Team
33 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2009 The IPython Development Team
34 11 #
35 12 # Distributed under the terms of the BSD License. The full license is in
36 13 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
14 #-----------------------------------------------------------------------------
15
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
38 19
39 # Enforce proper version requirements
20 import os
40 21 import sys
22 from IPython.core import release
23
24 #-----------------------------------------------------------------------------
25 # Setup everything
26 #-----------------------------------------------------------------------------
27
41 28
42 29 if sys.version[0:3] < '2.4':
43 30 raise ImportError('Python Version 2.4 or above is required for IPython.')
44 31
32
45 33 # Make it easy to import extensions - they are always directly on pythonpath.
46 34 # Therefore, non-IPython modules can be added to extensions directory
47 import os
48 35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
49 36
50 # Define what gets imported with a 'from IPython import *'
51 __all__ = ['IPython.core.ipapi','utils.generics','utils.ipstruct',
52 'core.release','core.shell']
53
54 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
55 # access to them via IPython.<name>
56 glob,loc = globals(),locals()
57 for name in __all__:
58 #print 'Importing: ',name # dbg
59 __import__(name,glob,loc,[])
37 #-----------------------------------------------------------------------------
38 # Setup the top level names
39 #-----------------------------------------------------------------------------
60 40
61 from IPython.core import shell
62 Shell = shell
63 from IPython.core import ipapi
64 from IPython.core import iplib
41 # In some cases, these are causing circular imports.
42 from IPython.core.iplib import InteractiveShell
43 from IPython.core.embed import embed
44 from IPython.core.error import TryNext
65 45
66 46 from IPython.lib import (
67 47 enable_wx, disable_wx,
@@ -75,13 +55,10 b' from IPython.lib import ('
75 55 )
76 56
77 57 # Release data
78 from IPython.core import release # do it explicitly so pydoc can see it - pydoc bug
79 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
80 ( release.authors['Fernando'] + release.authors['Janko'] + \
81 release.authors['Nathan'] )
58 __author__ = ''
59 for author, email in release.authors.values():
60 __author__ += author + ' <' + email + '>\n'
82 61 __license__ = release.license
83 62 __version__ = release.version
84 63 __revision__ = release.revision
85 64
86 # Namespace cleanup
87 del name,glob,loc
@@ -163,7 +163,7 b' class ArgParseConfigLoader(CommandLineConfigLoader):'
163 163 self._add_arguments()
164 164 self._add_other_arguments()
165 165
166 def _add_other_arguments():
166 def _add_other_arguments(self):
167 167 pass
168 168
169 169 def _add_arguments(self):
@@ -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 default=NoDefault)
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.',
194 200 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',
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)
@@ -1,9 +1,6 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3
4 def test_import_configloader():
5 from IPython.config import configloader
6
7 4 def test_import_userconfig():
8 5 from IPython.config import userconfig
9 6
@@ -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
@@ -70,12 +70,13 b' import os'
70 70 import re
71 71 import shlex
72 72 import sys
73 import IPython.utils.rlineimpl as readline
74 73 import itertools
74 import types
75
76 from IPython.core.error import TryNext
77 import IPython.utils.rlineimpl as readline
75 78 from IPython.utils.ipstruct import Struct
76 from IPython.core import ipapi
77 79 from IPython.utils import generics
78 import types
79 80
80 81 # Python 2.4 offers sets as a builtin
81 82 try:
@@ -195,7 +196,7 b' class Completer:'
195 196
196 197 try:
197 198 words = generics.complete_object(obj, words)
198 except ipapi.TryNext:
199 except TryNext:
199 200 pass
200 201 # Build match list to return
201 202 n = len(attr)
@@ -241,7 +242,7 b' class IPCompleter(Completer):'
241 242 self.get_line_buffer = self.readline.get_line_buffer
242 243 self.get_endidx = self.readline.get_endidx
243 244 self.omit__names = omit__names
244 self.merge_completions = shell.rc.readline_merge_completions
245 self.merge_completions = shell.readline_merge_completions
245 246 if alias_table is None:
246 247 alias_table = {}
247 248 self.alias_table = alias_table
@@ -553,7 +554,7 b' class IPCompleter(Completer):'
553 554 return withcase
554 555 # if none, then case insensitive ones are ok too
555 556 return [r for r in res if r.lower().startswith(text.lower())]
556 except ipapi.TryNext:
557 except TryNext:
557 558 pass
558 559
559 560 return None
@@ -21,6 +21,7 b' Authors:'
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from copy import deepcopy
24 import datetime
24 25 from weakref import WeakValueDictionary
25 26
26 27 from IPython.utils.ipstruct import Struct
@@ -51,15 +52,19 b' class MetaComponentTracker(type):'
51 52 When a Component or subclass is instantiated, this is called and
52 53 the instance is saved in a WeakValueDictionary for tracking.
53 54 """
54
55 instance = super(MetaComponentTracker, cls).__call__(*args, **kw)
55 instance = cls.__new__(cls, *args, **kw)
56 # Do this before __init__ is called so get_instances works inside
57 # __init__ methods!
56 58 for c in cls.__mro__:
57 59 if issubclass(cls, c) and issubclass(c, Component):
58 60 c.__numcreated += 1
59 61 c.__instance_refs[c.__numcreated] = instance
62 if isinstance(instance, cls):
63 cls.__init__(instance, *args, **kw)
64
60 65 return instance
61 66
62 def get_instances(cls, name=None, root=None):
67 def get_instances(cls, name=None, root=None, classname=None):
63 68 """Get all instances of cls and its subclasses.
64 69
65 70 Parameters
@@ -68,21 +73,26 b' class MetaComponentTracker(type):'
68 73 Limit to components with this name.
69 74 root : Component or subclass
70 75 Limit to components having this root.
76 classname : str
77 The string name of a class to match exactly.
71 78 """
72 79 instances = cls.__instance_refs.values()
73 80 if name is not None:
74 81 instances = [i for i in instances if i.name == name]
82 if classname is not None:
83 instances = [i for i in instances if i.__class__.__name__ == classname]
75 84 if root is not None:
76 85 instances = [i for i in instances if i.root == root]
77 86 return instances
78 87
79 def get_instances_by_condition(cls, call, name=None, root=None):
88 def get_instances_by_condition(cls, call, name=None, root=None,
89 classname=None):
80 90 """Get all instances of cls, i such that call(i)==True.
81 91
82 This also takes the ``name`` and ``root`` arguments of
83 :meth:`get_instance`
92 This also takes the ``name`` and ``root`` and ``classname``
93 arguments of :meth:`get_instance`
84 94 """
85 return [i for i in cls.get_instances(name, root) if call(i)]
95 return [i for i in cls.get_instances(name, root, classname) if call(i)]
86 96
87 97
88 98 class ComponentNameGenerator(object):
@@ -118,6 +128,7 b' class Component(HasTraitlets):'
118 128 config = Instance(Struct,(),{})
119 129 parent = This()
120 130 root = This()
131 created = None
121 132
122 133 def __init__(self, parent, name=None, config=None):
123 134 """Create a component given a parent and possibly and name and config.
@@ -159,13 +170,15 b' class Component(HasTraitlets):'
159 170 else:
160 171 self.name = name
161 172 self.root = self # This is the default, it is set when parent is set
162 self.parent = parent
173 self.parent = parent
163 174 if config is not None:
164 175 self.config = deepcopy(config)
165 176 else:
166 177 if self.parent is not None:
167 178 self.config = deepcopy(self.parent.config)
168 179
180 self.created = datetime.datetime.now()
181
169 182 #-------------------------------------------------------------------------
170 183 # Static traitlet notifiations
171 184 #-------------------------------------------------------------------------
@@ -124,7 +124,7 b' $self.bug_tracker'
124 124 #color_scheme = 'Linux' # dbg
125 125
126 126 try:
127 rptdir = self.IP.rc.ipythondir
127 rptdir = self.IP.config.IPYTHONDIR
128 128 except:
129 129 rptdir = os.getcwd()
130 130 if not os.path.isdir(rptdir):
@@ -171,7 +171,7 b' $self.bug_tracker'
171 171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
172 172 (os.name,sys.platform) )
173 173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
174 rpt_add(pformat(self.IP.rc.dict()))
174 rpt_add(pformat(self.IP.dict()))
175 175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 176 try:
177 177 rpt_add(sec_sep+"History of session input:")
@@ -215,7 +215,7 b' class IPythonCrashHandler(CrashHandler):'
215 215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
216 216 (os.name,sys.platform) )
217 217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
218 rpt_add(pformat(self.IP.rc.dict()))
218 # rpt_add(pformat(self.IP.dict()))
219 219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
220 220 try:
221 221 rpt_add(sec_sep+"History of session input:")
@@ -110,7 +110,7 b' class Tracer(object):'
110 110 __IPYTHON__
111 111 except NameError:
112 112 # Outside of ipython, we set our own exception hook manually
113 __IPYTHON__ = ipapi.get(True,False)
113 __IPYTHON__ = ipapi.get()
114 114 BdbQuit_excepthook.excepthook_ori = sys.excepthook
115 115 sys.excepthook = BdbQuit_excepthook
116 116 def_colors = 'NoColor'
@@ -123,7 +123,7 b' class Tracer(object):'
123 123 else:
124 124 # In ipython, we use its custom exception handler mechanism
125 125 ip = ipapi.get()
126 def_colors = ip.options.colors
126 def_colors = ip.colors
127 127 ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook)
128 128
129 129 if colors is None:
@@ -47,9 +47,7 b" def magic_history(self, parameter_s = ''):"
47 47 confirmation first if it already exists.
48 48 """
49 49
50 ip = self.api
51 shell = self.shell
52 if not shell.outputcache.do_full_cache:
50 if not self.outputcache.do_full_cache:
53 51 print 'This feature is only available if numbered prompts are in use.'
54 52 return
55 53 opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
@@ -71,11 +69,11 b" def magic_history(self, parameter_s = ''):"
71 69 close_at_end = True
72 70
73 71 if 't' in opts:
74 input_hist = shell.input_hist
72 input_hist = self.input_hist
75 73 elif 'r' in opts:
76 input_hist = shell.input_hist_raw
74 input_hist = self.input_hist_raw
77 75 else:
78 input_hist = shell.input_hist
76 input_hist = self.input_hist
79 77
80 78 default_length = 40
81 79 pattern = None
@@ -105,7 +103,7 b" def magic_history(self, parameter_s = ''):"
105 103
106 104 found = False
107 105 if pattern is not None:
108 sh = ip.IP.shadowhist.all()
106 sh = self.shadowhist.all()
109 107 for idx, s in sh:
110 108 if fnmatch.fnmatch(s, pattern):
111 109 print "0%d: %s" %(idx, s)
@@ -168,9 +166,8 b' def rep_f(self, arg):'
168 166 """
169 167
170 168 opts,args = self.parse_options(arg,'',mode='list')
171 ip = self.api
172 169 if not args:
173 ip.set_next_input(str(ip.user_ns["_"]))
170 self.set_next_input(str(self.user_ns["_"]))
174 171 return
175 172
176 173 if len(args) == 1 and not '-' in args[0]:
@@ -179,33 +176,33 b' def rep_f(self, arg):'
179 176 # get from shadow hist
180 177 num = int(arg[1:])
181 178 line = self.shadowhist.get(num)
182 ip.set_next_input(str(line))
179 self.set_next_input(str(line))
183 180 return
184 181 try:
185 182 num = int(args[0])
186 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
183 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
187 184 return
188 185 except ValueError:
189 186 pass
190 187
191 for h in reversed(self.shell.input_hist_raw):
188 for h in reversed(self.input_hist_raw):
192 189 if 'rep' in h:
193 190 continue
194 191 if fnmatch.fnmatch(h,'*' + arg + '*'):
195 ip.set_next_input(str(h).rstrip())
192 self.set_next_input(str(h).rstrip())
196 193 return
197 194
198 195 try:
199 196 lines = self.extract_input_slices(args, True)
200 197 print "lines",lines
201 ip.runlines(lines)
198 self.runlines(lines)
202 199 except ValueError:
203 200 print "Not found in recent history:", args
204 201
205 202
206 203 _sentinel = object()
207 204
208 class ShadowHist:
205 class ShadowHist(object):
209 206 def __init__(self,db):
210 207 # cmd => idx mapping
211 208 self.curidx = 0
@@ -228,7 +225,7 b' class ShadowHist:'
228 225 #print "new",newidx # dbg
229 226 self.db.hset('shadowhist',ent, newidx)
230 227 except:
231 ipapi.get().IP.showtraceback()
228 ipapi.get().showtraceback()
232 229 print "WARNING: disabling shadow history"
233 230 self.disabled = True
234 231
@@ -250,8 +247,8 b' class ShadowHist:'
250 247 def init_ipython(ip):
251 248 import ipy_completers
252 249
253 ip.expose_magic("rep",rep_f)
254 ip.expose_magic("hist",magic_hist)
255 ip.expose_magic("history",magic_history)
250 ip.define_magic("rep",rep_f)
251 ip.define_magic("hist",magic_hist)
252 ip.define_magic("history",magic_history)
256 253
257 254 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -26,7 +26,7 b' def calljed(self,filename, linenum):'
26 26 "My editor hook calls the jed editor directly."
27 27 print "Calling my own editor, jed ..."
28 28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise ipapi.TryNext()
29 raise TryNext()
30 30
31 31 ip.set_hook('editor', calljed)
32 32
@@ -41,22 +41,21 b' somewhere in your configuration files or ipython command line.'
41 41 # the file COPYING, distributed as part of this software.
42 42 #*****************************************************************************
43 43
44 from IPython.core import ipapi
45
46 44 import os, bisect
47 45 import sys
48 46 from IPython.utils.genutils import Term, shell
49 47 from pprint import PrettyPrinter
50 48
49 from IPython.core.error import TryNext
50
51 51 # List here all the default hooks. For now it's just the editor functions
52 52 # but over time we'll move here all the public API for user-accessible things.
53 # vds: >>
53
54 54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
55 55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
56 56 'generate_prompt', 'generate_output_prompt','shell_hook',
57 57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
58 58 'clipboard_get']
59 # vds: <<
60 59
61 60 pformat = PrettyPrinter().pformat
62 61
@@ -69,7 +68,7 b' def editor(self,filename, linenum=None):'
69 68
70 69 # IPython configures a default editor at startup by reading $EDITOR from
71 70 # the environment, and falling back on vi (unix) or notepad (win32).
72 editor = self.rc.editor
71 editor = self.editor
73 72
74 73 # marker for at which line to open the file (for existing objects)
75 74 if linenum is None or editor=='notepad':
@@ -83,7 +82,7 b' def editor(self,filename, linenum=None):'
83 82
84 83 # Call the actual editor
85 84 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
86 raise ipapi.TryNext()
85 raise TryNext()
87 86
88 87 import tempfile
89 88 def fix_error_editor(self,filename,linenum,column,msg):
@@ -99,20 +98,20 b' def fix_error_editor(self,filename,linenum,column,msg):'
99 98 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
100 99 t.flush()
101 100 return t
102 if os.path.basename(self.rc.editor) != 'vim':
101 if os.path.basename(self.editor) != 'vim':
103 102 self.hooks.editor(filename,linenum)
104 103 return
105 104 t = vim_quickfix_file()
106 105 try:
107 106 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
108 raise ipapi.TryNext()
107 raise TryNext()
109 108 finally:
110 109 t.close()
111 110
112 # vds: >>
111
113 112 def synchronize_with_editor(self, filename, linenum, column):
114 113 pass
115 # vds: <<
114
116 115
117 116 class CommandChainDispatcher:
118 117 """ Dispatch calls to a chain of commands until some func can handle it
@@ -140,12 +139,12 b' class CommandChainDispatcher:'
140 139 try:
141 140 ret = cmd(*args, **kw)
142 141 return ret
143 except ipapi.TryNext, exc:
142 except TryNext, exc:
144 143 if exc.args or exc.kwargs:
145 144 args = exc.args
146 145 kw = exc.kwargs
147 146 # if no function will accept it, raise TryNext up to the caller
148 raise ipapi.TryNext
147 raise TryNext
149 148
150 149 def __str__(self):
151 150 return str(self.chain)
@@ -160,14 +159,15 b' class CommandChainDispatcher:'
160 159 Handy if the objects are not callable.
161 160 """
162 161 return iter(self.chain)
163
162
163
164 164 def result_display(self,arg):
165 165 """ Default display hook.
166 166
167 167 Called for displaying the result to the user.
168 168 """
169 169
170 if self.rc.pprint:
170 if self.pprint:
171 171 out = pformat(arg)
172 172 if '\n' in out:
173 173 # So that multi-line strings line up with the left column of
@@ -183,6 +183,7 b' def result_display(self,arg):'
183 183 # the default display hook doesn't manipulate the value to put in history
184 184 return None
185 185
186
186 187 def input_prefilter(self,line):
187 188 """ Default input prefilter
188 189
@@ -197,6 +198,7 b' def input_prefilter(self,line):'
197 198 #print "attempt to rewrite",line #dbg
198 199 return line
199 200
201
200 202 def shutdown_hook(self):
201 203 """ default shutdown hook
202 204
@@ -206,32 +208,36 b' def shutdown_hook(self):'
206 208 #print "default shutdown hook ok" # dbg
207 209 return
208 210
211
209 212 def late_startup_hook(self):
210 213 """ Executed after ipython has been constructed and configured
211 214
212 215 """
213 216 #print "default startup hook ok" # dbg
214 217
218
215 219 def generate_prompt(self, is_continuation):
216 220 """ calculate and return a string with the prompt to display """
217 ip = self.api
218 221 if is_continuation:
219 return str(ip.IP.outputcache.prompt2)
220 return str(ip.IP.outputcache.prompt1)
222 return str(self.outputcache.prompt2)
223 return str(self.outputcache.prompt1)
224
221 225
222 226 def generate_output_prompt(self):
223 ip = self.api
224 return str(ip.IP.outputcache.prompt_out)
227 return str(self.outputcache.prompt_out)
228
225 229
226 230 def shell_hook(self,cmd):
227 231 """ Run system/shell command a'la os.system() """
228 232
229 shell(cmd, header=self.rc.system_header, verbose=self.rc.system_verbose)
233 shell(cmd, header=self.system_header, verbose=self.system_verbose)
234
230 235
231 236 def show_in_pager(self,s):
232 237 """ Run a string through pager """
233 238 # raising TryNext here will use the default paging functionality
234 raise ipapi.TryNext
239 raise TryNext
240
235 241
236 242 def pre_prompt_hook(self):
237 243 """ Run before displaying the next prompt
@@ -242,10 +248,12 b' def pre_prompt_hook(self):'
242 248
243 249 return None
244 250
251
245 252 def pre_runcode_hook(self):
246 253 """ Executed before running the (prefiltered) code in IPython """
247 254 return None
248 255
256
249 257 def clipboard_get(self):
250 258 """ Get text from the clipboard.
251 259 """
This diff has been collapsed as it changes many lines, (701 lines changed) Show them Hide them
@@ -1,685 +1,58 b''
1 """IPython customization API
2
3 Your one-stop module for configuring & extending ipython
4
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
7
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
10
11 Below is an example that you can just put to a module and import from ipython.
12
13 A good practice is to install the config script below as e.g.
14
15 ~/.ipython/my_private_conf.py
16
17 And do
18
19 import_mod my_private_conf
20
21 in ~/.ipython/ipythonrc
22
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
26
27 from IPython.core import ipapi
28 ip = ipapi.get()
29
30 def ankka_f(self, arg):
31 print 'Ankka',self,'says uppercase:',arg.upper()
32
33 ip.expose_magic('ankka',ankka_f)
34
35 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias helloworld echo "Hello world"')
37 ip.system('pwd')
38
39 ip.ex('import re')
40 ip.ex('''
41 def funcci(a,b):
42 print a+b
43 print funcci(3,4)
44 ''')
45 ip.ex('funcci(348,9)')
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Oh my @#*%, where did ipapi go?
46 5
47 def jed_editor(self,filename, linenum=None):
48 print 'Calling my own editor, jed ... via hook!'
49 import os
50 if linenum is None: linenum = 0
51 os.system('jed +%d %s' % (linenum, filename))
52 print 'exiting jed'
6 Originally, this module was designed to be a public api for IPython. It is
7 now deprecated and replaced by :class:`IPython.core.Interactive` shell.
8 Almost all of the methods that were here are now there, but possibly renamed.
53 9
54 ip.set_hook('editor',jed_editor)
10 During our transition, we will keep this simple module with its :func:`get`
11 function. It too will eventually go away when the new component querying
12 interface is fully used.
55 13
56 o = ip.options
57 o.autocall = 2 # FULL autocall mode
14 Authors:
58 15
59 print 'done!'
16 * Brian Granger
60 17 """
61 18
62 19 #-----------------------------------------------------------------------------
63 # Modules and globals
64
65 # stdlib imports
66 import __builtin__
67 import sys
68
69 # contains the most recently instantiated IPApi
70 _RECENT_IP = None
71
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
72 24 #-----------------------------------------------------------------------------
73 # Code begins
74
75 class TryNext(Exception):
76 """Try next hook exception.
77
78 Raise this in your hook function to indicate that the next hook handler
79 should be used to handle the operation. If you pass arguments to the
80 constructor those arguments will be used by the next hook instead of the
81 original ones.
82 """
83
84 def __init__(self, *args, **kwargs):
85 self.args = args
86 self.kwargs = kwargs
87
88
89 class UsageError(Exception):
90 """ Error in magic function arguments, etc.
91
92 Something that probably won't warrant a full traceback, but should
93 nevertheless interrupt a macro / batch file.
94 """
95
96
97 class IPyAutocall:
98 """ Instances of this class are always autocalled
99
100 This happens regardless of 'autocall' variable state. Use this to
101 develop macro-like mechanisms.
102 """
103
104 def set_ip(self,ip):
105 """ Will be used to set _ip point to current ipython instance b/f call
106
107 Override this method if you don't want this to happen.
108
109 """
110 self._ip = ip
111
112
113 class IPythonNotRunning:
114 """Dummy do-nothing class.
115
116 Instances of this class return a dummy attribute on all accesses, which
117 can be called and warns. This makes it easier to write scripts which use
118 the ipapi.get() object for informational purposes to operate both with and
119 without ipython. Obviously code which uses the ipython object for
120 computations will not work, but this allows a wider range of code to
121 transparently work whether ipython is being used or not."""
122
123 def __init__(self,warn=True):
124 if warn:
125 self.dummy = self._dummy_warn
126 else:
127 self.dummy = self._dummy_silent
128
129 def __str__(self):
130 return "<IPythonNotRunning>"
131
132 __repr__ = __str__
133
134 def __getattr__(self,name):
135 return self.dummy
136
137 def _dummy_warn(self,*args,**kw):
138 """Dummy function, which doesn't do anything but warn."""
139
140 print ("IPython is not running, this is a dummy no-op function")
141
142 def _dummy_silent(self,*args,**kw):
143 """Dummy function, which doesn't do anything and emits no warnings."""
144 pass
145
146
147 def get(allow_dummy=False,dummy_warn=True):
148 """Get an IPApi object.
149
150 If allow_dummy is true, returns an instance of IPythonNotRunning
151 instead of None if not running under IPython.
152
153 If dummy_warn is false, the dummy instance will be completely silent.
154
155 Running this should be the first thing you do when writing extensions that
156 can be imported as normal modules. You can then direct all the
157 configuration operations against the returned object.
158 """
159 global _RECENT_IP
160 if allow_dummy and not _RECENT_IP:
161 _RECENT_IP = IPythonNotRunning(dummy_warn)
162 return _RECENT_IP
163
164
165 class IPApi(object):
166 """ The actual API class for configuring IPython
167
168 You should do all of the IPython configuration by getting an IPApi object
169 with IPython.ipapi.get() and using the attributes and methods of the
170 returned object."""
171
172 def __init__(self,ip):
173
174 global _RECENT_IP
175
176 # All attributes exposed here are considered to be the public API of
177 # IPython. As needs dictate, some of these may be wrapped as
178 # properties.
179
180 self.magic = ip.ipmagic
181
182 self.system = ip.system
183
184 self.set_hook = ip.set_hook
185
186 self.set_custom_exc = ip.set_custom_exc
187
188 self.user_ns = ip.user_ns
189
190 self.set_crash_handler = ip.set_crash_handler
191
192 # Session-specific data store, which can be used to store
193 # data that should persist through the ipython session.
194 self.meta = ip.meta
195
196 # The ipython instance provided
197 self.IP = ip
198
199 self.extensions = {}
200
201 self.dbg = DebugTools(self)
202
203 _RECENT_IP = self
204
205 # Use a property for some things which are added to the instance very
206 # late. I don't have time right now to disentangle the initialization
207 # order issues, so a property lets us delay item extraction while
208 # providing a normal attribute API.
209 def get_db(self):
210 """A handle to persistent dict-like database (a PickleShareDB object)"""
211 return self.IP.db
212
213 db = property(get_db,None,None,get_db.__doc__)
214 25
215 def get_options(self):
216 """All configurable variables."""
217
218 # catch typos by disabling new attribute creation. If new attr creation
219 # is in fact wanted (e.g. when exposing new options), do
220 # allow_new_attr(True) for the received rc struct.
221
222 self.IP.rc.allow_new_attr(False)
223 return self.IP.rc
224
225 options = property(get_options,None,None,get_options.__doc__)
226
227 def expose_magic(self,magicname, func):
228 """Expose own function as magic function for ipython
229
230 def foo_impl(self,parameter_s=''):
231 'My very own magic!. (Use docstrings, IPython reads them).'
232 print 'Magic function. Passed parameter is between < >:'
233 print '<%s>' % parameter_s
234 print 'The self object is:',self
235
236 ipapi.expose_magic('foo',foo_impl)
237 """
238
239 import new
240 im = new.instancemethod(func,self.IP, self.IP.__class__)
241 old = getattr(self.IP, "magic_" + magicname, None)
242 if old:
243 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
244 (magicname,old) )
245
246 setattr(self.IP, "magic_" + magicname, im)
247
248 def ex(self,cmd):
249 """ Execute a normal python statement in user namespace """
250 exec cmd in self.user_ns
251
252 def ev(self,expr):
253 """ Evaluate python expression expr in user namespace
254
255 Returns the result of evaluation"""
256 return eval(expr,self.user_ns)
257
258 def runlines(self,lines):
259 """ Run the specified lines in interpreter, honoring ipython directives.
260
261 This allows %magic and !shell escape notations.
262
263 Takes either all lines in one string or list of lines.
264 """
265
266 def cleanup_ipy_script(script):
267 """ Make a script safe for _ip.runlines()
268
269 - Removes empty lines Suffixes all indented blocks that end with
270 - unindented lines with empty lines
271 """
272
273 res = []
274 lines = script.splitlines()
275
276 level = 0
277 for l in lines:
278 lstripped = l.lstrip()
279 stripped = l.strip()
280 if not stripped:
281 continue
282 newlevel = len(l) - len(lstripped)
283 def is_secondary_block_start(s):
284 if not s.endswith(':'):
285 return False
286 if (s.startswith('elif') or
287 s.startswith('else') or
288 s.startswith('except') or
289 s.startswith('finally')):
290 return True
291
292 if level > 0 and newlevel == 0 and \
293 not is_secondary_block_start(stripped):
294 # add empty line
295 res.append('')
296
297 res.append(l)
298 level = newlevel
299 return '\n'.join(res) + '\n'
300
301 if isinstance(lines,basestring):
302 script = lines
303 else:
304 script = '\n'.join(lines)
305 clean=cleanup_ipy_script(script)
306 # print "_ip.runlines() script:\n",clean # dbg
307 self.IP.runlines(clean)
308
309 def to_user_ns(self,vars, interactive = True):
310 """Inject a group of variables into the IPython user namespace.
311
312 Inputs:
313
314 - vars: string with variable names separated by whitespace, or a
315 dict with name/value pairs.
316
317 - interactive: if True (default), the var will be listed with
318 %whos et. al.
319
320 This utility routine is meant to ease interactive debugging work,
321 where you want to easily propagate some internal variable in your code
322 up to the interactive namespace for further exploration.
323
324 When you run code via %run, globals in your script become visible at
325 the interactive prompt, but this doesn't happen for locals inside your
326 own functions and methods. Yet when debugging, it is common to want
327 to explore some internal variables further at the interactive propmt.
328
329 Examples:
330
331 To use this, you first must obtain a handle on the ipython object as
332 indicated above, via:
333
334 from IPython.core import ipapi
335 ip = ipapi.get()
336
337 Once this is done, inside a routine foo() where you want to expose
338 variables x and y, you do the following:
339
340 def foo():
341 ...
342 x = your_computation()
343 y = something_else()
344
345 # This pushes x and y to the interactive prompt immediately, even
346 # if this routine crashes on the next line after:
347 ip.to_user_ns('x y')
348 ...
349
350 # To expose *ALL* the local variables from the function, use:
351 ip.to_user_ns(locals())
352
353 ...
354 # return
355
356
357 If you need to rename variables, the dict input makes it easy. For
358 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
359 in IPython user namespace:
360
361 ip.to_user_ns(dict(x=foo,y=bar))
362 """
363
364 # print 'vars given:',vars # dbg
365
366 # We need a dict of name/value pairs to do namespace updates.
367 if isinstance(vars,dict):
368 # If a dict was given, no need to change anything.
369 vdict = vars
370 elif isinstance(vars,basestring):
371 # If a string with names was given, get the caller's frame to
372 # evaluate the given names in
373 cf = sys._getframe(1)
374 vdict = {}
375 for name in vars.split():
376 try:
377 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
378 except:
379 print ('could not get var. %s from %s' %
380 (name,cf.f_code.co_name))
381 else:
382 raise ValueError('vars must be a string or a dict')
383
384 # Propagate variables to user namespace
385 self.user_ns.update(vdict)
386
387 # And configure interactive visibility
388 config_ns = self.IP.user_config_ns
389 if interactive:
390 for name,val in vdict.iteritems():
391 config_ns.pop(name,None)
392 else:
393 for name,val in vdict.iteritems():
394 config_ns[name] = val
395
396 def expand_alias(self,line):
397 """ Expand an alias in the command line
398
399 Returns the provided command line, possibly with the first word
400 (command) translated according to alias expansion rules.
401
402 [ipython]|16> _ip.expand_aliases("np myfile.txt")
403 <16> 'q:/opt/np/notepad++.exe myfile.txt'
404 """
405
406 pre,fn,rest = self.IP.split_user_input(line)
407 res = pre + self.IP.expand_aliases(fn,rest)
408 return res
409
410 def itpl(self, s, depth = 1):
411 """ Expand Itpl format string s.
412
413 Only callable from command line (i.e. prefilter results);
414 If you use in your scripts, you need to use a bigger depth!
415 """
416 return self.IP.var_expand(s, depth)
417
418 def defalias(self, name, cmd):
419 """ Define a new alias
420
421 _ip.defalias('bb','bldmake bldfiles')
422
423 Creates a new alias named 'bb' in ipython user namespace
424 """
425
426 self.dbg.check_hotname(name)
427
428 if name in self.IP.alias_table:
429 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
430 % (name, cmd, self.IP.alias_table[name]))
431
432 if callable(cmd):
433 self.IP.alias_table[name] = cmd
434 from IPython.core import shadowns
435 setattr(shadowns, name,cmd)
436 return
437
438 if isinstance(cmd,basestring):
439 nargs = cmd.count('%s')
440 if nargs>0 and cmd.find('%l')>=0:
441 raise Exception('The %s and %l specifiers are mutually '
442 'exclusive in alias definitions.')
443
444 self.IP.alias_table[name] = (nargs,cmd)
445 return
446
447 # just put it in - it's probably (0,'foo')
448 self.IP.alias_table[name] = cmd
449
450 def defmacro(self, *args):
451 """ Define a new macro
452
453 2 forms of calling:
454
455 mac = _ip.defmacro('print "hello"\nprint "world"')
456
457 (doesn't put the created macro on user namespace)
458
459 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
460
461 (creates a macro named 'build' in user namespace)
462 """
463
464 from IPython.core import macro
465
466 if len(args) == 1:
467 return macro.Macro(args[0])
468 elif len(args) == 2:
469 self.user_ns[args[0]] = macro.Macro(args[1])
470 else:
471 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
472
473 def set_next_input(self, s):
474 """ Sets the 'default' input string for the next command line.
475
476 Requires readline.
477
478 Example:
479
480 [D:\ipython]|1> _ip.set_next_input("Hello Word")
481 [D:\ipython]|2> Hello Word_ # cursor is here
482 """
483
484 self.IP.rl_next_input = s
485
486 def load(self, mod):
487 """ Load an extension.
488
489 Some modules should (or must) be 'load()':ed, rather than just imported.
490
491 Loading will do:
492
493 - run init_ipython(ip)
494 - run ipython_firstrun(ip)
495 """
496
497 if mod in self.extensions:
498 # just to make sure we don't init it twice
499 # note that if you 'load' a module that has already been
500 # imported, init_ipython gets run anyway
501
502 return self.extensions[mod]
503 __import__(mod)
504 m = sys.modules[mod]
505 if hasattr(m,'init_ipython'):
506 m.init_ipython(self)
507
508 if hasattr(m,'ipython_firstrun'):
509 already_loaded = self.db.get('firstrun_done', set())
510 if mod not in already_loaded:
511 m.ipython_firstrun(self)
512 already_loaded.add(mod)
513 self.db['firstrun_done'] = already_loaded
514
515 self.extensions[mod] = m
516 return m
517
518
519 class DebugTools:
520 """ Used for debugging mishaps in api usage
521
522 So far, tracing redefinitions is supported.
523 """
524
525 def __init__(self, ip):
526 self.ip = ip
527 self.debugmode = False
528 self.hotnames = set()
529
530 def hotname(self, name_to_catch):
531 self.hotnames.add(name_to_catch)
532
533 def debug_stack(self, msg = None):
534 if not self.debugmode:
535 return
536
537 import traceback
538 if msg is not None:
539 print '====== %s ========' % msg
540 traceback.print_stack()
541
542 def check_hotname(self,name):
543 if name in self.hotnames:
544 self.debug_stack( "HotName '%s' caught" % name)
545
546
547 def launch_new_instance(user_ns = None,shellclass = None):
548 """ Make and start a new ipython instance.
549
550 This can be called even without having an already initialized
551 ipython session running.
552
553 This is also used as the egg entry point for the 'ipython' script.
554
555 """
556 ses = make_session(user_ns,shellclass)
557 ses.mainloop()
558
559
560 def make_user_ns(user_ns = None):
561 """Return a valid user interactive namespace.
562
563 This builds a dict with the minimal information needed to operate as a
564 valid IPython user namespace, which you can pass to the various embedding
565 classes in ipython.
566
567 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
568 to make both the local and global namespace objects simultaneously.
569
570 :Parameters:
571 user_ns : dict-like, optional
572 The current user namespace. The items in this namespace should be
573 included in the output. If None, an appropriate blank namespace
574 should be created.
575
576 :Returns:
577 A dictionary-like object to be used as the local namespace of the
578 interpreter.
579 """
580
581 raise NotImplementedError
582
583
584 def make_user_global_ns(ns = None):
585 """Return a valid user global namespace.
586
587 Similar to make_user_ns(), but global namespaces are really only needed in
588 embedded applications, where there is a distinction between the user's
589 interactive namespace and the global one where ipython is running.
590
591 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
592 to make both the local and global namespace objects simultaneously.
593
594 :Parameters:
595 ns : dict, optional
596 The current user global namespace. The items in this namespace
597 should be included in the output. If None, an appropriate blank
598 namespace should be created.
599
600 :Returns:
601 A true dict to be used as the global namespace of the interpreter.
602 """
603
604 raise NotImplementedError
605
606 # Record the true objects in order to be able to test if the user has overridden
607 # these API functions.
608 _make_user_ns = make_user_ns
609 _make_user_global_ns = make_user_global_ns
610
611
612 def make_user_namespaces(user_ns = None,user_global_ns = None):
613 """Return a valid local and global user interactive namespaces.
26 #-----------------------------------------------------------------------------
27 # Imports
28 #-----------------------------------------------------------------------------
614 29
615 This builds a dict with the minimal information needed to operate as a
616 valid IPython user namespace, which you can pass to the various embedding
617 classes in ipython. The default implementation returns the same dict for
618 both the locals and the globals to allow functions to refer to variables in
619 the namespace. Customized implementations can return different dicts. The
620 locals dictionary can actually be anything following the basic mapping
621 protocol of a dict, but the globals dict must be a true dict, not even
622 a subclass. It is recommended that any custom object for the locals
623 namespace synchronize with the globals dict somehow.
30 from IPython.core.error import TryNext, UsageError
624 31
625 Raises TypeError if the provided globals namespace is not a true dict.
32 #-----------------------------------------------------------------------------
33 # Classes and functions
34 #-----------------------------------------------------------------------------
626 35
627 :Parameters:
628 user_ns : dict-like, optional
629 The current user namespace. The items in this namespace should be
630 included in the output. If None, an appropriate blank namespace
631 should be created.
632 user_global_ns : dict, optional
633 The current user global namespace. The items in this namespace
634 should be included in the output. If None, an appropriate blank
635 namespace should be created.
36 def get():
37 """Get the most recently created InteractiveShell instance."""
38 from IPython.core.iplib import InteractiveShell
39 insts = InteractiveShell.get_instances()
40 most_recent = insts[0]
41 for inst in insts[1:]:
42 if inst.created > most_recent.created:
43 most_recent = inst
44 return most_recent
636 45
637 :Returns:
638 A tuple pair of dictionary-like object to be used as the local namespace
639 of the interpreter and a dict to be used as the global namespace.
640 """
46 def launch_new_instance():
47 """Create a run a full blown IPython instance"""
48 from IPython.core.ipapp import IPythonApp
49 app = IPythonApp()
50 app.start()
641 51
642 if user_ns is None:
643 if make_user_ns is not _make_user_ns:
644 # Old API overridden.
645 # FIXME: Issue DeprecationWarning, or just let the old API live on?
646 user_ns = make_user_ns(user_ns)
647 else:
648 # Set __name__ to __main__ to better match the behavior of the
649 # normal interpreter.
650 user_ns = {'__name__' :'__main__',
651 '__builtins__' : __builtin__,
652 }
653 else:
654 user_ns.setdefault('__name__','__main__')
655 user_ns.setdefault('__builtins__',__builtin__)
656 52
657 if user_global_ns is None:
658 if make_user_global_ns is not _make_user_global_ns:
659 # Old API overridden.
660 user_global_ns = make_user_global_ns(user_global_ns)
661 else:
662 user_global_ns = user_ns
663 if type(user_global_ns) is not dict:
664 raise TypeError("user_global_ns must be a true dict; got %r"
665 % type(user_global_ns))
666 53
667 return user_ns, user_global_ns
668 54
669 55
670 def make_session(user_ns = None, shellclass = None):
671 """Makes, but does not launch an IPython session.
672
673 Later on you can call obj.mainloop() on the returned object.
674 56
675 Inputs:
676 57
677 - user_ns(None): a dict to be used as the user's namespace with initial
678 data.
679
680 WARNING: This should *not* be run when a session exists already."""
681 58
682 import IPython.core.shell
683 if shellclass is None:
684 return IPython.core.shell.start(user_ns)
685 return shellclass(user_ns = user_ns)
This diff has been collapsed as it changes many lines, (1831 lines changed) Show them Hide them
@@ -1,32 +1,23 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 IPython -- An enhanced Interactive Python
4
5 Requires Python 2.4 or newer.
6
7 This file contains all the classes and helper functions specific to IPython.
3 Main IPython Component
8 4 """
9 5
10 #*****************************************************************************
11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
13 10 #
14 11 # Distributed under the terms of the BSD License. The full license is in
15 12 # the file COPYING, distributed as part of this software.
16 #
17 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Python standard library. Over time, all of that class has been copied
19 # verbatim here for modifications which could not be accomplished by
20 # subclassing. At this point, there are no dependencies at all on the code
21 # module anymore (it is not even imported). The Python License (sec. 2)
22 # allows for this, but it's always nice to acknowledge credit where credit is
23 # due.
24 #*****************************************************************************
25
26 #****************************************************************************
27 # Modules and globals
28
29 # Python standard modules
13 #-----------------------------------------------------------------------------
14
15 #-----------------------------------------------------------------------------
16 # Imports
17 #-----------------------------------------------------------------------------
18
19 from __future__ import with_statement
20
30 21 import __main__
31 22 import __builtin__
32 23 import StringIO
@@ -43,26 +34,40 b' import string'
43 34 import sys
44 35 import tempfile
45 36
46 # IPython's own modules
47 #import IPython
48 37 from IPython.core import ultratb
49 from IPython.utils import PyColorize
50 38 from IPython.core import debugger, oinspect
51 from IPython.extensions import pickleshare
39 from IPython.core import shadowns
40 from IPython.core import history as ipcorehist
41 from IPython.core import prefilter
42 from IPython.core.autocall import IPyAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
52 44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
53 from IPython.external.Itpl import ItplNS
54 45 from IPython.core.logger import Logger
55 46 from IPython.core.magic import Magic
56 47 from IPython.core.prompts import CachedOutput
57 from IPython.utils.ipstruct import Struct
48 from IPython.core.page import page
49 from IPython.core.component import Component
50 from IPython.core.oldusersetup import user_setup
51 from IPython.core.usage import interactive_usage, default_banner
52 from IPython.core.error import TryNext, UsageError
53
54 from IPython.extensions import pickleshare
55 from IPython.external.Itpl import ItplNS
58 56 from IPython.lib.backgroundjobs import BackgroundJobManager
57 from IPython.utils.ipstruct import Struct
58 from IPython.utils import PyColorize
59 59 from IPython.utils.genutils import *
60 60 from IPython.utils.strdispatch import StrDispatch
61 from IPython.core import ipapi
62 import IPython.core.history
63 import IPython.core.prefilter as prefilter
64 from IPython.core import shadowns
61 from IPython.utils.platutils import toggle_set_term_title, set_term_title
62
63 from IPython.utils.traitlets import (
64 Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode
65 )
66
67 #-----------------------------------------------------------------------------
65 68 # Globals
69 #-----------------------------------------------------------------------------
70
66 71
67 72 # store the builtin raw_input globally, and use this always, in case user code
68 73 # overwrites it (like wx.py.PyShell does)
@@ -72,11 +77,14 b' raw_input_original = raw_input'
72 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
73 78
74 79
75 #****************************************************************************
76 # Some utility function definitions
80 #-----------------------------------------------------------------------------
81 # Utilities
82 #-----------------------------------------------------------------------------
83
77 84
78 85 ini_spaces_re = re.compile(r'^(\s+)')
79 86
87
80 88 def num_ini_spaces(strng):
81 89 """Return the number of initial spaces in a string"""
82 90
@@ -86,6 +94,7 b' def num_ini_spaces(strng):'
86 94 else:
87 95 return 0
88 96
97
89 98 def softspace(file, newvalue):
90 99 """Copied from code.py, to remove the dependency"""
91 100
@@ -102,229 +111,10 b' def softspace(file, newvalue):'
102 111 return oldvalue
103 112
104 113
105 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
106 """Install or upgrade the user configuration directory.
107
108 Can be called when running for the first time or to upgrade the user's
109 .ipython/ directory.
110
111 Parameters
112 ----------
113 ipythondir : path
114 The directory to be used for installation/upgrade. In 'install' mode,
115 if this path already exists, the function exits immediately.
116
117 rc_suffix : str
118 Extension for the config files. On *nix platforms it is typically the
119 empty string, while Windows normally uses '.ini'.
120
121 mode : str, optional
122 Valid modes are 'install' and 'upgrade'.
123
124 interactive : bool, optional
125 If False, do not wait for user input on any errors. Normally after
126 printing its status information, this function waits for the user to
127 hit Return before proceeding. This is because the default use case is
128 when first installing the IPython configuration, so we want the user to
129 acknowledge the initial message, which contains some useful
130 information.
131 """
132
133 # For automatic use, deactivate all i/o
134 if interactive:
135 def wait():
136 try:
137 raw_input("Please press <RETURN> to start IPython.")
138 except EOFError:
139 print >> Term.cout
140 print '*'*70
141
142 def printf(s):
143 print s
144 else:
145 wait = lambda : None
146 printf = lambda s : None
147
148 # Install mode should be re-entrant: if the install dir already exists,
149 # bail out cleanly.
150 # XXX. This is too hasty to return. We need to check to make sure that
151 # all the expected config files and directories are actually there. We
152 # currently have a failure mode if someone deletes a needed config file
153 # but still has the ipythondir.
154 if mode == 'install' and os.path.isdir(ipythondir):
155 return
156
157 cwd = os.getcwd() # remember where we started
158 glb = glob.glob
159
160 printf('*'*70)
161 if mode == 'install':
162 printf(
163 """Welcome to IPython. I will try to create a personal configuration directory
164 where you can customize many aspects of IPython's functionality in:\n""")
165 else:
166 printf('I am going to upgrade your configuration in:')
167
168 printf(ipythondir)
169
170 rcdirend = os.path.join('IPython','config','userconfig')
171 cfg = lambda d: os.path.join(d,rcdirend)
172 try:
173 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
174 printf("Initializing from configuration: %s" % rcdir)
175 except IndexError:
176 warning = """
177 Installation error. IPython's directory was not found.
178
179 Check the following:
180
181 The ipython/IPython directory should be in a directory belonging to your
182 PYTHONPATH environment variable (that is, it should be in a directory
183 belonging to sys.path). You can copy it explicitly there or just link to it.
184
185 IPython will create a minimal default configuration for you.
186
187 """
188 warn(warning)
189 wait()
190
191 if sys.platform =='win32':
192 inif = 'ipythonrc.ini'
193 else:
194 inif = 'ipythonrc'
195 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
196 inif : '# intentionally left blank' }
197 os.makedirs(ipythondir, mode = 0777)
198 for f, cont in minimal_setup.items():
199 # In 2.5, this can be more cleanly done using 'with'
200 fobj = file(ipythondir + '/' + f,'w')
201 fobj.write(cont)
202 fobj.close()
203
204 return
205
206 if mode == 'install':
207 try:
208 shutil.copytree(rcdir,ipythondir)
209 os.chdir(ipythondir)
210 rc_files = glb("ipythonrc*")
211 for rc_file in rc_files:
212 os.rename(rc_file,rc_file+rc_suffix)
213 except:
214 warning = """
215
216 There was a problem with the installation:
217 %s
218 Try to correct it or contact the developers if you think it's a bug.
219 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
220 warn(warning)
221 wait()
222 return
223
224 elif mode == 'upgrade':
225 try:
226 os.chdir(ipythondir)
227 except:
228 printf("""
229 Can not upgrade: changing to directory %s failed. Details:
230 %s
231 """ % (ipythondir,sys.exc_info()[1]) )
232 wait()
233 return
234 else:
235 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
236 for new_full_path in sources:
237 new_filename = os.path.basename(new_full_path)
238 if new_filename.startswith('ipythonrc'):
239 new_filename = new_filename + rc_suffix
240 # The config directory should only contain files, skip any
241 # directories which may be there (like CVS)
242 if os.path.isdir(new_full_path):
243 continue
244 if os.path.exists(new_filename):
245 old_file = new_filename+'.old'
246 if os.path.exists(old_file):
247 os.remove(old_file)
248 os.rename(new_filename,old_file)
249 shutil.copy(new_full_path,new_filename)
250 else:
251 raise ValueError('unrecognized mode for install: %r' % mode)
252
253 # Fix line-endings to those native to each platform in the config
254 # directory.
255 try:
256 os.chdir(ipythondir)
257 except:
258 printf("""
259 Problem: changing to directory %s failed.
260 Details:
261 %s
262
263 Some configuration files may have incorrect line endings. This should not
264 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
265 wait()
266 else:
267 for fname in glb('ipythonrc*'):
268 try:
269 native_line_ends(fname,backup=0)
270 except IOError:
271 pass
272
273 if mode == 'install':
274 printf("""
275 Successful installation!
276
277 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
278 IPython manual (there are both HTML and PDF versions supplied with the
279 distribution) to make sure that your system environment is properly configured
280 to take advantage of IPython's features.
281
282 Important note: the configuration system has changed! The old system is
283 still in place, but its setting may be partly overridden by the settings in
284 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
285 if some of the new settings bother you.
286
287 """)
288 else:
289 printf("""
290 Successful upgrade!
291
292 All files in your directory:
293 %(ipythondir)s
294 which would have been overwritten by the upgrade were backed up with a .old
295 extension. If you had made particular customizations in those files you may
296 want to merge them back into the new files.""" % locals() )
297 wait()
298 os.chdir(cwd)
299
300 #****************************************************************************
301 # Local use exceptions
302 114 class SpaceInInput(exceptions.Exception): pass
303 115
304
305 #****************************************************************************
306 # Local use classes
307 116 class Bunch: pass
308 117
309 class Undefined: pass
310
311 class Quitter(object):
312 """Simple class to handle exit, similar to Python 2.5's.
313
314 It handles exiting in an ipython-safe manner, which the one in Python 2.5
315 doesn't do (obviously, since it doesn't know about ipython)."""
316
317 def __init__(self,shell,name):
318 self.shell = shell
319 self.name = name
320
321 def __repr__(self):
322 return 'Type %s() to exit.' % self.name
323 __str__ = __repr__
324
325 def __call__(self):
326 self.shell.exit()
327
328 118 class InputList(list):
329 119 """Class to store user input.
330 120
@@ -340,6 +130,7 b' class InputList(list):'
340 130 def __getslice__(self,i,j):
341 131 return ''.join(list.__getslice__(self,i,j))
342 132
133
343 134 class SyntaxTB(ultratb.ListTB):
344 135 """Extension which holds some state: the last exception value"""
345 136
@@ -357,55 +148,229 b' class SyntaxTB(ultratb.ListTB):'
357 148 self.last_syntax_error = None
358 149 return e
359 150
360 #****************************************************************************
361 # Main IPython class
362 151
363 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
364 # until a full rewrite is made. I've cleaned all cross-class uses of
365 # attributes and methods, but too much user code out there relies on the
366 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
367 #
368 # But at least now, all the pieces have been separated and we could, in
369 # principle, stop using the mixin. This will ease the transition to the
370 # chainsaw branch.
152 def get_default_editor():
153 try:
154 ed = os.environ['EDITOR']
155 except KeyError:
156 if os.name == 'posix':
157 ed = 'vi' # the only one guaranteed to be there!
158 else:
159 ed = 'notepad' # same in Windows!
160 return ed
161
162
163 class SeparateStr(Str):
164 """A Str subclass to validate separate_in, separate_out, etc.
371 165
372 # For reference, the following is the list of 'self.foo' uses in the Magic
373 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
374 # class, to prevent clashes.
166 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
167 """
375 168
376 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
377 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
378 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
379 # 'self.value']
169 def validate(self, obj, value):
170 if value == '0': value = ''
171 value = value.replace('\\n','\n')
172 return super(SeparateStr, self).validate(obj, value)
380 173
381 class InteractiveShell(object,Magic):
382 """An enhanced console for Python."""
174
175 #-----------------------------------------------------------------------------
176 # Main IPython class
177 #-----------------------------------------------------------------------------
178
179
180 class InteractiveShell(Component, Magic):
181 """An enhanced, interactive shell for Python."""
182
183 autocall = Enum((0,1,2), config_key='AUTOCALL')
184 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
185 autoindent = CBool(True, config_key='AUTOINDENT')
186 automagic = CBool(True, config_key='AUTOMAGIC')
187 display_banner = CBool(True, config_key='DISPLAY_BANNER')
188 banner = Str('')
189 banner1 = Str(default_banner, config_key='BANNER1')
190 banner2 = Str('', config_key='BANNER2')
191 c = Str('', config_key='C')
192 cache_size = Int(1000, config_key='CACHE_SIZE')
193 classic = CBool(False, config_key='CLASSIC')
194 color_info = CBool(True, config_key='COLOR_INFO')
195 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
196 default_value='LightBG', config_key='COLORS')
197 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
198 debug = CBool(False, config_key='DEBUG')
199 deep_reload = CBool(False, config_key='DEEP_RELOAD')
200 embedded = CBool(False)
201 embedded_active = CBool(False)
202 editor = Str(get_default_editor(), config_key='EDITOR')
203 filename = Str("<ipython console>")
204 interactive = CBool(False, config_key='INTERACTIVE')
205 ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__
206 logstart = CBool(False, config_key='LOGSTART')
207 logfile = Str('', config_key='LOGFILE')
208 logplay = Str('', config_key='LOGPLAY')
209 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
210 object_info_string_level = Enum((0,1,2), default_value=0,
211 config_keys='OBJECT_INFO_STRING_LEVEL')
212 pager = Str('less', config_key='PAGER')
213 pdb = CBool(False, config_key='PDB')
214 pprint = CBool(True, config_key='PPRINT')
215 profile = Str('', config_key='PROFILE')
216 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
217 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
218 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
219 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
220 quiet = CBool(False, config_key='QUIET')
221
222 readline_use = CBool(True, config_key='READLINE_USE')
223 readline_merge_completions = CBool(True,
224 config_key='READLINE_MERGE_COMPLETIONS')
225 readline_omit__names = Enum((0,1,2), default_value=0,
226 config_key='READLINE_OMIT_NAMES')
227 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
228 readline_parse_and_bind = List([
229 'tab: complete',
230 '"\C-l": possible-completions',
231 'set show-all-if-ambiguous on',
232 '"\C-o": tab-insert',
233 '"\M-i": " "',
234 '"\M-o": "\d\d\d\d"',
235 '"\M-I": "\d\d\d\d"',
236 '"\C-r": reverse-search-history',
237 '"\C-s": forward-search-history',
238 '"\C-p": history-search-backward',
239 '"\C-n": history-search-forward',
240 '"\e[A": history-search-backward',
241 '"\e[B": history-search-forward',
242 '"\C-k": kill-line',
243 '"\C-u": unix-line-discard',
244 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
245 )
246
247 screen_length = Int(0, config_key='SCREEN_LENGTH')
248
249 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
250 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
251 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
252 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
253
254 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
255 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
256 term_title = CBool(False, config_key='TERM_TITLE')
257 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
258 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
259 default_value='Context', config_key='XMODE')
260
261 alias = List(allow_none=False, config_key='ALIAS')
262 autoexec = List(allow_none=False)
383 263
384 264 # class attribute to indicate whether the class supports threads or not.
385 265 # Subclasses with thread support should override this as needed.
386 266 isthreaded = False
387 267
388 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
389 user_ns=None,user_global_ns=None,banner2='',
390 custom_exceptions=((),None),embedded=False):
268 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
269 user_ns=None, user_global_ns=None,
270 banner1=None, banner2=None,
271 custom_exceptions=((),None)):
272
273 # This is where traitlets with a config_key argument are updated
274 # from the values on config.
275 super(InteractiveShell, self).__init__(parent, config=config, name='__IP')
276
277 # These are relatively independent and stateless
278 self.init_ipythondir(ipythondir)
279 self.init_instance_attrs()
280 self.init_term_title()
281 self.init_usage(usage)
282 self.init_banner(banner1, banner2)
283
284 # Create namespaces (user_ns, user_global_ns, alias_table, etc.)
285 self.init_create_namespaces(user_ns, user_global_ns)
286 # This has to be done after init_create_namespaces because it uses
287 # something in self.user_ns, but before init_sys_modules, which
288 # is the first thing to modify sys.
289 self.save_sys_module_state()
290 self.init_sys_modules()
291
292 self.init_history()
293 self.init_encoding()
294 self.init_handlers()
295
296 Magic.__init__(self, self)
297
298 self.init_syntax_highlighting()
299 self.init_hooks()
300 self.init_pushd_popd_magic()
301 self.init_traceback_handlers(custom_exceptions)
302 self.init_user_ns()
303 self.init_logger()
304 self.init_aliases()
305 self.init_builtins()
306
307 # pre_config_initialization
308 self.init_shadow_hist()
309
310 # The next section should contain averything that was in ipmaker.
311 self.init_logstart()
312
313 # The following was in post_config_initialization
314 self.init_inspector()
315 self.init_readline()
316 self.init_prompts()
317 self.init_displayhook()
318 self.init_reload_doctest()
319 self.init_magics()
320 self.init_pdb()
321 self.hooks.late_startup_hook()
391 322
392 # log system
393 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
394
395 # Job manager (for jobs run as background threads)
396 self.jobs = BackgroundJobManager()
323 def cleanup(self):
324 self.restore_sys_module_state()
397 325
398 # Store the actual shell's name
399 self.name = name
400 self.more = False
326 #-------------------------------------------------------------------------
327 # Traitlet changed handlers
328 #-------------------------------------------------------------------------
401 329
402 # We need to know whether the instance is meant for embedding, since
403 # global/local namespaces need to be handled differently in that case
404 self.embedded = embedded
405 if embedded:
406 # Control variable so users can, from within the embedded instance,
407 # permanently deactivate it.
408 self.embedded_active = True
330 def _banner1_changed(self):
331 self.compute_banner()
332
333 def _banner2_changed(self):
334 self.compute_banner()
335
336 @property
337 def usable_screen_length(self):
338 if self.screen_length == 0:
339 return 0
340 else:
341 num_lines_bot = self.separate_in.count('\n')+1
342 return self.screen_length - num_lines_bot
343
344 def _term_title_changed(self, name, new_value):
345 self.init_term_title()
346
347 #-------------------------------------------------------------------------
348 # init_* methods called by __init__
349 #-------------------------------------------------------------------------
350
351 def init_ipythondir(self, ipythondir):
352 if ipythondir is not None:
353 self.ipythondir = ipythondir
354 self.config.IPYTHONDIR = self.ipythondir
355 return
356
357 if hasattr(self.config, 'IPYTHONDIR'):
358 self.ipythondir = self.config.IPYTHONDIR
359 if not hasattr(self.config, 'IPYTHONDIR'):
360 # cdw is always defined
361 self.ipythondir = os.getcwd()
362
363 # The caller must make sure that ipythondir exists. We should
364 # probably handle this using a Dir traitlet.
365 if not os.path.isdir(self.ipythondir):
366 raise IOError('IPython dir does not exist: %s' % self.ipythondir)
367
368 # All children can just read this
369 self.config.IPYTHONDIR = self.ipythondir
370
371 def init_instance_attrs(self):
372 self.jobs = BackgroundJobManager()
373 self.more = False
409 374
410 375 # command compiler
411 376 self.compile = codeop.CommandCompiler()
@@ -413,14 +378,6 b' class InteractiveShell(object,Magic):'
413 378 # User input buffer
414 379 self.buffer = []
415 380
416 # Default name given in compilation of code
417 self.filename = '<ipython console>'
418
419 # Install our own quitter instead of the builtins. For python2.3-2.4,
420 # this brings in behavior like 2.5, and for 2.5 it's identical.
421 __builtin__.exit = Quitter(self,'exit')
422 __builtin__.quit = Quitter(self,'quit')
423
424 381 # Make an empty namespace, which extension writers can rely on both
425 382 # existing and NEVER being used by ipython itself. This gives them a
426 383 # convenient location for storing additional information and state
@@ -428,6 +385,59 b' class InteractiveShell(object,Magic):'
428 385 # ipython names that may develop later.
429 386 self.meta = Struct()
430 387
388 # Object variable to store code object waiting execution. This is
389 # used mainly by the multithreaded shells, but it can come in handy in
390 # other situations. No need to use a Queue here, since it's a single
391 # item which gets cleared once run.
392 self.code_to_run = None
393
394 # Flag to mark unconditional exit
395 self.exit_now = False
396
397 # Temporary files used for various purposes. Deleted at exit.
398 self.tempfiles = []
399
400 # Keep track of readline usage (later set by init_readline)
401 self.has_readline = False
402
403 # keep track of where we started running (mainly for crash post-mortem)
404 # This is not being used anywhere currently.
405 self.starting_dir = os.getcwd()
406
407 # Indentation management
408 self.indent_current_nsp = 0
409
410 def init_term_title(self):
411 # Enable or disable the terminal title.
412 if self.term_title:
413 toggle_set_term_title(True)
414 set_term_title('IPython: ' + abbrev_cwd())
415 else:
416 toggle_set_term_title(False)
417
418 def init_usage(self, usage=None):
419 if usage is None:
420 self.usage = interactive_usage
421 else:
422 self.usage = usage
423
424 def init_banner(self, banner1, banner2):
425 if self.c: # regular python doesn't print the banner with -c
426 self.display_banner = False
427 if banner1 is not None:
428 self.banner1 = banner1
429 if banner2 is not None:
430 self.banner2 = banner2
431 self.compute_banner()
432
433 def compute_banner(self):
434 self.banner = self.banner1 + '\n'
435 if self.profile:
436 self.banner += '\nIPython profile: %s\n' % self.profile
437 if self.banner2:
438 self.banner += '\n' + self.banner2 + '\n'
439
440 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
431 441 # Create the namespace where the user will operate. user_ns is
432 442 # normally the only one used, and it is passed to the exec calls as
433 443 # the locals argument. But we do carry a user_global_ns namespace
@@ -464,7 +474,7 b' class InteractiveShell(object,Magic):'
464 474 # These routines return properly built dicts as needed by the rest of
465 475 # the code, and can also be used by extension writers to generate
466 476 # properly initialized namespaces.
467 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
477 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
468 478 user_global_ns)
469 479
470 480 # Assign namespaces
@@ -532,6 +542,7 b' class InteractiveShell(object,Magic):'
532 542 self.alias_table, self.internal_ns,
533 543 self._main_ns_cache ]
534 544
545 def init_sys_modules(self):
535 546 # We need to insert into sys.modules something that looks like a
536 547 # module but which accesses the IPython namespace, for shelve and
537 548 # pickle to work interactively. Normally they rely on getting
@@ -547,16 +558,65 b' class InteractiveShell(object,Magic):'
547 558 # shouldn't overtake the execution environment of the script they're
548 559 # embedded in).
549 560
550 if not embedded:
551 try:
552 main_name = self.user_ns['__name__']
553 except KeyError:
554 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
555 else:
556 #print "pickle hack in place" # dbg
557 #print 'main_name:',main_name # dbg
558 sys.modules[main_name] = FakeModule(self.user_ns)
559
561 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
562
563 try:
564 main_name = self.user_ns['__name__']
565 except KeyError:
566 raise KeyError('user_ns dictionary MUST have a "__name__" key')
567 else:
568 sys.modules[main_name] = FakeModule(self.user_ns)
569
570 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
571 """Return a valid local and global user interactive namespaces.
572
573 This builds a dict with the minimal information needed to operate as a
574 valid IPython user namespace, which you can pass to the various
575 embedding classes in ipython. The default implementation returns the
576 same dict for both the locals and the globals to allow functions to
577 refer to variables in the namespace. Customized implementations can
578 return different dicts. The locals dictionary can actually be anything
579 following the basic mapping protocol of a dict, but the globals dict
580 must be a true dict, not even a subclass. It is recommended that any
581 custom object for the locals namespace synchronize with the globals
582 dict somehow.
583
584 Raises TypeError if the provided globals namespace is not a true dict.
585
586 :Parameters:
587 user_ns : dict-like, optional
588 The current user namespace. The items in this namespace should
589 be included in the output. If None, an appropriate blank
590 namespace should be created.
591 user_global_ns : dict, optional
592 The current user global namespace. The items in this namespace
593 should be included in the output. If None, an appropriate
594 blank namespace should be created.
595
596 :Returns:
597 A tuple pair of dictionary-like object to be used as the local namespace
598 of the interpreter and a dict to be used as the global namespace.
599 """
600
601 if user_ns is None:
602 # Set __name__ to __main__ to better match the behavior of the
603 # normal interpreter.
604 user_ns = {'__name__' :'__main__',
605 '__builtins__' : __builtin__,
606 }
607 else:
608 user_ns.setdefault('__name__','__main__')
609 user_ns.setdefault('__builtins__',__builtin__)
610
611 if user_global_ns is None:
612 user_global_ns = user_ns
613 if type(user_global_ns) is not dict:
614 raise TypeError("user_global_ns must be a true dict; got %r"
615 % type(user_global_ns))
616
617 return user_ns, user_global_ns
618
619 def init_history(self):
560 620 # List of input with multi-line handling.
561 621 self.input_hist = InputList()
562 622 # This one will hold the 'raw' input history, without any
@@ -573,6 +633,18 b' class InteractiveShell(object,Magic):'
573 633 # dict of output history
574 634 self.output_hist = {}
575 635
636 # Now the history file
637 try:
638 histfname = 'history-%s' % self.profile
639 except AttributeError:
640 histfname = 'history'
641 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
642
643 # Fill the history zero entry, user counter starts at 1
644 self.input_hist.append('\n')
645 self.input_hist_raw.append('\n')
646
647 def init_encoding(self):
576 648 # Get system encoding at startup time. Certain terminals (like Emacs
577 649 # under Win32 have it set to None, and we need to have a known valid
578 650 # encoding to use in the raw_input() method
@@ -581,20 +653,7 b' class InteractiveShell(object,Magic):'
581 653 except AttributeError:
582 654 self.stdin_encoding = 'ascii'
583 655
584 # dict of things NOT to alias (keywords, builtins and some magics)
585 no_alias = {}
586 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
587 for key in keyword.kwlist + no_alias_magics:
588 no_alias[key] = 1
589 no_alias.update(__builtin__.__dict__)
590 self.no_alias = no_alias
591
592 # Object variable to store code object waiting execution. This is
593 # used mainly by the multithreaded shells, but it can come in handy in
594 # other situations. No need to use a Queue here, since it's a single
595 # item which gets cleared once run.
596 self.code_to_run = None
597
656 def init_handlers(self):
598 657 # escapes for automatic behavior on the command line
599 658 self.ESC_SHELL = '!'
600 659 self.ESC_SH_CAP = '!!'
@@ -614,13 +673,12 b' class InteractiveShell(object,Magic):'
614 673 self.ESC_SH_CAP : self.handle_shell_escape,
615 674 }
616 675
617 # class initializations
618 Magic.__init__(self,self)
619
676 def init_syntax_highlighting(self):
620 677 # Python source parser/formatter for syntax highlighting
621 678 pyformat = PyColorize.Parser().format
622 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
679 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
623 680
681 def init_hooks(self):
624 682 # hooks holds pointers used for user-side customizations
625 683 self.hooks = Struct()
626 684
@@ -633,81 +691,17 b' class InteractiveShell(object,Magic):'
633 691 # default hooks have priority 100, i.e. low; user hooks should have
634 692 # 0-100 priority
635 693 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
636 #print "bound hook",hook_name
637
638 # Flag to mark unconditional exit
639 self.exit_now = False
640
641 self.usage_min = """\
642 An enhanced console for Python.
643 Some of its features are:
644 - Readline support if the readline library is present.
645 - Tab completion in the local namespace.
646 - Logging of input, see command-line options.
647 - System shell escape via ! , eg !ls.
648 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
649 - Keeps track of locally defined variables via %who, %whos.
650 - Show object information with a ? eg ?x or x? (use ?? for more info).
651 """
652 if usage: self.usage = usage
653 else: self.usage = self.usage_min
654
655 # Storage
656 self.rc = rc # This will hold all configuration information
657 self.pager = 'less'
658 # temporary files used for various purposes. Deleted at exit.
659 self.tempfiles = []
660 694
661 # Keep track of readline usage (later set by init_readline)
662 self.has_readline = False
663
664 # template for logfile headers. It gets resolved at runtime by the
665 # logstart method.
666 self.loghead_tpl = \
667 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
668 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
669 #log# opts = %s
670 #log# args = %s
671 #log# It is safe to make manual edits below here.
672 #log#-----------------------------------------------------------------------
673 """
695 def init_pushd_popd_magic(self):
674 696 # for pushd/popd management
675 697 try:
676 698 self.home_dir = get_home_dir()
677 except HomeDirError,msg:
699 except HomeDirError, msg:
678 700 fatal(msg)
679 701
680 702 self.dir_stack = []
681 703
682 # Functions to call the underlying shell.
683
684 # The first is similar to os.system, but it doesn't return a value,
685 # and it allows interpolation of variables in the user's namespace.
686 self.system = lambda cmd: \
687 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
688
689 # These are for getoutput and getoutputerror:
690 self.getoutput = lambda cmd: \
691 getoutput(self.var_expand(cmd,depth=2),
692 header=self.rc.system_header,
693 verbose=self.rc.system_verbose)
694
695 self.getoutputerror = lambda cmd: \
696 getoutputerror(self.var_expand(cmd,depth=2),
697 header=self.rc.system_header,
698 verbose=self.rc.system_verbose)
699
700
701 # keep track of where we started running (mainly for crash post-mortem)
702 self.starting_dir = os.getcwd()
703
704 # Various switches which can be set
705 self.CACHELENGTH = 5000 # this is cheap, it's just text
706 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
707 self.banner2 = banner2
708
709 # TraceBack handlers:
710
704 def init_traceback_handlers(self, custom_exceptions):
711 705 # Syntax error handler.
712 706 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
713 707
@@ -734,9 +728,37 b' class InteractiveShell(object,Magic):'
734 728 # and add any custom exception handlers the user may have specified
735 729 self.set_custom_exc(*custom_exceptions)
736 730
737 # indentation management
738 self.autoindent = False
739 self.indent_current_nsp = 0
731 def init_logger(self):
732 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
733 # local shortcut, this is used a LOT
734 self.log = self.logger.log
735 # template for logfile headers. It gets resolved at runtime by the
736 # logstart method.
737 self.loghead_tpl = \
738 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
739 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
740 #log# opts = %s
741 #log# args = %s
742 #log# It is safe to make manual edits below here.
743 #log#-----------------------------------------------------------------------
744 """
745
746 def init_logstart(self):
747 if self.logplay:
748 self.magic_logstart(self.logplay + ' append')
749 elif self.logfile:
750 self.magic_logstart(self.logfile)
751 elif self.logstart:
752 self.magic_logstart()
753
754 def init_aliases(self):
755 # dict of things NOT to alias (keywords, builtins and some magics)
756 no_alias = {}
757 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
758 for key in keyword.kwlist + no_alias_magics:
759 no_alias[key] = 1
760 no_alias.update(__builtin__.__dict__)
761 self.no_alias = no_alias
740 762
741 763 # Make some aliases automatically
742 764 # Prepare list of shell aliases to auto-define
@@ -783,93 +805,133 b' class InteractiveShell(object,Magic):'
783 805 auto_alias = ()
784 806 self.auto_alias = [s.split(None,1) for s in auto_alias]
785 807
786 # Produce a public API instance
787 self.api = ipapi.IPApi(self)
788
789 # Initialize all user-visible namespaces
790 self.init_namespaces()
791
792 # Call the actual (public) initializer
793 self.init_auto_alias()
794
795 # track which builtins we add, so we can clean up later
796 self.builtins_added = {}
797 # This method will add the necessary builtins for operation, but
798 # tracking what it did via the builtins_added dict.
799
800 #TODO: remove this, redundant
801 self.add_builtins()
802 # end __init__
803
804 def var_expand(self,cmd,depth=0):
805 """Expand python variables in a string.
806
807 The depth argument indicates how many frames above the caller should
808 be walked to look for the local namespace where to expand variables.
809
810 The global namespace for expansion is always the user's interactive
811 namespace.
812 """
808 # Load default aliases
809 for alias, cmd in self.auto_alias:
810 self.define_alias(alias,cmd)
813 811
814 return str(ItplNS(cmd,
815 self.user_ns, # globals
816 # Skip our own frame in searching for locals:
817 sys._getframe(depth+1).f_locals # locals
818 ))
812 # Load user aliases
813 for alias in self.alias:
814 self.magic_alias(alias)
819 815
820 def pre_config_initialization(self):
821 """Pre-configuration init method
816 def init_builtins(self):
817 self.builtin_trap = BuiltinTrap(self)
822 818
823 This is called before the configuration files are processed to
824 prepare the services the config files might need.
825
826 self.rc already has reasonable default values at this point.
827 """
828 rc = self.rc
819 def init_shadow_hist(self):
829 820 try:
830 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
821 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
831 822 except exceptions.UnicodeDecodeError:
832 823 print "Your ipythondir can't be decoded to unicode!"
833 824 print "Please set HOME environment variable to something that"
834 825 print r"only has ASCII characters, e.g. c:\home"
835 print "Now it is",rc.ipythondir
826 print "Now it is", self.config.IPYTHONDIR
836 827 sys.exit()
837 self.shadowhist = IPython.core.history.ShadowHist(self.db)
838
839 def post_config_initialization(self):
840 """Post configuration init method
841
842 This is called after the configuration files have been processed to
843 'finalize' the initialization."""
844
845 rc = self.rc
828 self.shadowhist = ipcorehist.ShadowHist(self.db)
846 829
830 def init_inspector(self):
847 831 # Object inspector
848 832 self.inspector = oinspect.Inspector(oinspect.InspectColors,
849 833 PyColorize.ANSICodeColors,
850 834 'NoColor',
851 rc.object_info_string_level)
852
835 self.object_info_string_level)
836
837 def init_readline(self):
838 """Command history completion/saving/reloading."""
839
853 840 self.rl_next_input = None
854 841 self.rl_do_indent = False
855 # Load readline proper
856 if rc.readline:
857 self.init_readline()
858
859 # local shortcut, this is used a LOT
860 self.log = self.logger.log
861 842
843 if not self.readline_use:
844 return
845
846 import IPython.utils.rlineimpl as readline
847
848 if not readline.have_readline:
849 self.has_readline = 0
850 self.readline = None
851 # no point in bugging windows users with this every time:
852 warn('Readline services not available on this platform.')
853 else:
854 sys.modules['readline'] = readline
855 import atexit
856 from IPython.core.completer import IPCompleter
857 self.Completer = IPCompleter(self,
858 self.user_ns,
859 self.user_global_ns,
860 self.readline_omit__names,
861 self.alias_table)
862 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
863 self.strdispatchers['complete_command'] = sdisp
864 self.Completer.custom_completers = sdisp
865 # Platform-specific configuration
866 if os.name == 'nt':
867 self.readline_startup_hook = readline.set_pre_input_hook
868 else:
869 self.readline_startup_hook = readline.set_startup_hook
870
871 # Load user's initrc file (readline config)
872 # Or if libedit is used, load editrc.
873 inputrc_name = os.environ.get('INPUTRC')
874 if inputrc_name is None:
875 home_dir = get_home_dir()
876 if home_dir is not None:
877 inputrc_name = '.inputrc'
878 if readline.uses_libedit:
879 inputrc_name = '.editrc'
880 inputrc_name = os.path.join(home_dir, inputrc_name)
881 if os.path.isfile(inputrc_name):
882 try:
883 readline.read_init_file(inputrc_name)
884 except:
885 warn('Problems reading readline initialization file <%s>'
886 % inputrc_name)
887
888 self.has_readline = 1
889 self.readline = readline
890 # save this in sys so embedded copies can restore it properly
891 sys.ipcompleter = self.Completer.complete
892 self.set_completer()
893
894 # Configure readline according to user's prefs
895 # This is only done if GNU readline is being used. If libedit
896 # is being used (as on Leopard) the readline config is
897 # not run as the syntax for libedit is different.
898 if not readline.uses_libedit:
899 for rlcommand in self.readline_parse_and_bind:
900 #print "loading rl:",rlcommand # dbg
901 readline.parse_and_bind(rlcommand)
902
903 # Remove some chars from the delimiters list. If we encounter
904 # unicode chars, discard them.
905 delims = readline.get_completer_delims().encode("ascii", "ignore")
906 delims = delims.translate(string._idmap,
907 self.readline_remove_delims)
908 readline.set_completer_delims(delims)
909 # otherwise we end up with a monster history after a while:
910 readline.set_history_length(1000)
911 try:
912 #print '*** Reading readline history' # dbg
913 readline.read_history_file(self.histfile)
914 except IOError:
915 pass # It doesn't exist yet.
916
917 atexit.register(self.atexit_operations)
918 del atexit
919
920 # Configure auto-indent for all platforms
921 self.set_autoindent(self.autoindent)
922
923 def init_prompts(self):
862 924 # Initialize cache, set in/out prompts and printing system
863 925 self.outputcache = CachedOutput(self,
864 rc.cache_size,
865 rc.pprint,
866 input_sep = rc.separate_in,
867 output_sep = rc.separate_out,
868 output_sep2 = rc.separate_out2,
869 ps1 = rc.prompt_in1,
870 ps2 = rc.prompt_in2,
871 ps_out = rc.prompt_out,
872 pad_left = rc.prompts_pad_left)
926 self.cache_size,
927 self.pprint,
928 input_sep = self.separate_in,
929 output_sep = self.separate_out,
930 output_sep2 = self.separate_out2,
931 ps1 = self.prompt_in1,
932 ps2 = self.prompt_in2,
933 ps_out = self.prompt_out,
934 pad_left = self.prompts_pad_left)
873 935
874 936 # user may have over-ridden the default print hook:
875 937 try:
@@ -877,6 +939,7 b' class InteractiveShell(object,Magic):'
877 939 except AttributeError:
878 940 pass
879 941
942 def init_displayhook(self):
880 943 # I don't like assigning globally to sys, because it means when
881 944 # embedding instances, each embedded instance overrides the previous
882 945 # choice. But sys.displayhook seems to be called internally by exec,
@@ -885,43 +948,75 b' class InteractiveShell(object,Magic):'
885 948 self.sys_displayhook = sys.displayhook
886 949 sys.displayhook = self.outputcache
887 950
951 def init_reload_doctest(self):
888 952 # Do a proper resetting of doctest, including the necessary displayhook
889 953 # monkeypatching
890 954 try:
891 955 doctest_reload()
892 956 except ImportError:
893 957 warn("doctest module does not exist.")
894
958
959 def init_magics(self):
895 960 # Set user colors (don't do it in the constructor above so that it
896 961 # doesn't crash if colors option is invalid)
897 self.magic_colors(rc.colors)
962 self.magic_colors(self.colors)
898 963
964 def init_pdb(self):
899 965 # Set calling of pdb on exceptions
900 self.call_pdb = rc.pdb
901
902 # Load user aliases
903 for alias in rc.alias:
904 self.magic_alias(alias)
905
906 self.hooks.late_startup_hook()
907
908 for cmd in self.rc.autoexec:
909 #print "autoexec>",cmd #dbg
910 self.api.runlines(cmd)
911
912 batchrun = False
913 for batchfile in [path(arg) for arg in self.rc.args
914 if arg.lower().endswith('.ipy')]:
915 if not batchfile.isfile():
916 print "No such batch file:", batchfile
917 continue
918 self.api.runlines(batchfile.text())
919 batchrun = True
920 # without -i option, exit after running the batch file
921 if batchrun and not self.rc.interact:
922 self.ask_exit()
923
924 def init_namespaces(self):
966 # self.call_pdb is a property
967 self.call_pdb = self.pdb
968
969 # def init_exec_commands(self):
970 # for cmd in self.config.EXECUTE:
971 # print "execute:", cmd
972 # self.api.runlines(cmd)
973 #
974 # batchrun = False
975 # if self.config.has_key('EXECFILE'):
976 # for batchfile in [path(arg) for arg in self.config.EXECFILE
977 # if arg.lower().endswith('.ipy')]:
978 # if not batchfile.isfile():
979 # print "No such batch file:", batchfile
980 # continue
981 # self.api.runlines(batchfile.text())
982 # batchrun = True
983 # # without -i option, exit after running the batch file
984 # if batchrun and not self.interactive:
985 # self.ask_exit()
986
987 # def load(self, mod):
988 # """ Load an extension.
989 #
990 # Some modules should (or must) be 'load()':ed, rather than just imported.
991 #
992 # Loading will do:
993 #
994 # - run init_ipython(ip)
995 # - run ipython_firstrun(ip)
996 # """
997 #
998 # if mod in self.extensions:
999 # # just to make sure we don't init it twice
1000 # # note that if you 'load' a module that has already been
1001 # # imported, init_ipython gets run anyway
1002 #
1003 # return self.extensions[mod]
1004 # __import__(mod)
1005 # m = sys.modules[mod]
1006 # if hasattr(m,'init_ipython'):
1007 # m.init_ipython(self)
1008 #
1009 # if hasattr(m,'ipython_firstrun'):
1010 # already_loaded = self.db.get('firstrun_done', set())
1011 # if mod not in already_loaded:
1012 # m.ipython_firstrun(self)
1013 # already_loaded.add(mod)
1014 # self.db['firstrun_done'] = already_loaded
1015 #
1016 # self.extensions[mod] = m
1017 # return m
1018
1019 def init_user_ns(self):
925 1020 """Initialize all user-visible namespaces to their minimum defaults.
926 1021
927 1022 Certain history lists are also initialized here, as they effectively
@@ -936,8 +1031,8 b' class InteractiveShell(object,Magic):'
936 1031 # The user namespace MUST have a pointer to the shell itself.
937 1032 self.user_ns[self.name] = self
938 1033
939 # Store the public api instance
940 self.user_ns['_ip'] = self.api
1034 # Store myself as the public api!!!
1035 self.user_ns['_ip'] = self
941 1036
942 1037 # make global variables for user access to the histories
943 1038 self.user_ns['_ih'] = self.input_hist
@@ -950,51 +1045,46 b' class InteractiveShell(object,Magic):'
950 1045
951 1046 self.user_ns['_sh'] = shadowns
952 1047
953 # Fill the history zero entry, user counter starts at 1
954 self.input_hist.append('\n')
955 self.input_hist_raw.append('\n')
1048 # Put 'help' in the user namespace
1049 try:
1050 from site import _Helper
1051 self.user_ns['help'] = _Helper()
1052 except ImportError:
1053 warn('help() not available - check site.py')
1054
1055 def save_sys_module_state(self):
1056 """Save the state of hooks in the sys module.
1057
1058 This has to be called after self.user_ns is created.
1059 """
1060 self._orig_sys_module_state = {}
1061 self._orig_sys_module_state['stdin'] = sys.stdin
1062 self._orig_sys_module_state['stdout'] = sys.stdout
1063 self._orig_sys_module_state['stderr'] = sys.stderr
1064 self._orig_sys_module_state['displayhook'] = sys.displayhook
1065 self._orig_sys_module_state['excepthook'] = sys.excepthook
1066 try:
1067 self._orig_sys_modules_main_name = self.user_ns['__name__']
1068 except KeyError:
1069 pass
1070
1071 def restore_sys_module_state(self):
1072 """Restore the state of the sys module."""
1073 try:
1074 for k, v in self._orig_sys_module_state.items():
1075 setattr(sys, k, v)
1076 except AttributeError:
1077 pass
1078 try:
1079 delattr(sys, 'ipcompleter')
1080 except AttributeError:
1081 pass
1082 # Reset what what done in self.init_sys_modules
1083 try:
1084 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
1085 except (AttributeError, KeyError):
1086 pass
956 1087
957 def add_builtins(self):
958 """Store ipython references into the builtin namespace.
959
960 Some parts of ipython operate via builtins injected here, which hold a
961 reference to IPython itself."""
962
963 # TODO: deprecate all of these, they are unsafe
964 builtins_new = dict(__IPYTHON__ = self,
965 ip_set_hook = self.set_hook,
966 jobs = self.jobs,
967 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
968 ipalias = wrap_deprecated(self.ipalias),
969 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
970 #_ip = self.api
971 )
972 for biname,bival in builtins_new.items():
973 try:
974 # store the orignal value so we can restore it
975 self.builtins_added[biname] = __builtin__.__dict__[biname]
976 except KeyError:
977 # or mark that it wasn't defined, and we'll just delete it at
978 # cleanup
979 self.builtins_added[biname] = Undefined
980 __builtin__.__dict__[biname] = bival
981
982 # Keep in the builtins a flag for when IPython is active. We set it
983 # with setdefault so that multiple nested IPythons don't clobber one
984 # another. Each will increase its value by one upon being activated,
985 # which also gives us a way to determine the nesting level.
986 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
987
988 def clean_builtins(self):
989 """Remove any builtins which might have been added by add_builtins, or
990 restore overwritten ones to their previous values."""
991 for biname,bival in self.builtins_added.items():
992 if bival is Undefined:
993 del __builtin__.__dict__[biname]
994 else:
995 __builtin__.__dict__[biname] = bival
996 self.builtins_added.clear()
997
998 1088 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
999 1089 """set_hook(name,hook) -> sets an internal IPython hook.
1000 1090
@@ -1033,11 +1123,8 b' class InteractiveShell(object,Magic):'
1033 1123 dp = f
1034 1124
1035 1125 setattr(self.hooks,name, dp)
1036
1037
1038 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1039 1126
1040 def set_crash_handler(self,crashHandler):
1127 def set_crash_handler(self, crashHandler):
1041 1128 """Set the IPython crash handler.
1042 1129
1043 1130 This must be a callable with a signature suitable for use as
@@ -1052,7 +1139,6 b' class InteractiveShell(object,Magic):'
1052 1139 # frameworks).
1053 1140 self.sys_excepthook = sys.excepthook
1054 1141
1055
1056 1142 def set_custom_exc(self,exc_tuple,handler):
1057 1143 """set_custom_exc(exc_tuple,handler)
1058 1144
@@ -1133,33 +1219,24 b' class InteractiveShell(object,Magic):'
1133 1219
1134 1220 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1135 1221 'Control auto-activation of pdb at exceptions')
1136
1137 # These special functions get installed in the builtin namespace, to
1138 # provide programmatic (pure python) access to magics, aliases and system
1139 # calls. This is important for logging, user scripting, and more.
1140 1222
1141 # We are basically exposing, via normal python functions, the three
1142 # mechanisms in which ipython offers special call modes (magics for
1143 # internal control, aliases for direct system access via pre-selected
1144 # names, and !cmd for calling arbitrary system commands).
1145
1146 def ipmagic(self,arg_s):
1223 def magic(self,arg_s):
1147 1224 """Call a magic function by name.
1148 1225
1149 1226 Input: a string containing the name of the magic function to call and any
1150 1227 additional arguments to be passed to the magic.
1151 1228
1152 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1229 magic('name -opt foo bar') is equivalent to typing at the ipython
1153 1230 prompt:
1154 1231
1155 1232 In[1]: %name -opt foo bar
1156 1233
1157 To call a magic without arguments, simply use ipmagic('name').
1234 To call a magic without arguments, simply use magic('name').
1158 1235
1159 1236 This provides a proper Python function to call IPython's magics in any
1160 1237 valid Python code you can type at the interpreter, including loops and
1161 compound statements. It is added by IPython to the Python builtin
1162 namespace upon initialization."""
1238 compound statements.
1239 """
1163 1240
1164 1241 args = arg_s.split(' ',1)
1165 1242 magic_name = args[0]
@@ -1174,7 +1251,67 b' class InteractiveShell(object,Magic):'
1174 1251 error("Magic function `%s` not found." % magic_name)
1175 1252 else:
1176 1253 magic_args = self.var_expand(magic_args,1)
1177 return fn(magic_args)
1254 with self.builtin_trap:
1255 result = fn(magic_args)
1256 return result
1257
1258 def define_magic(self, magicname, func):
1259 """Expose own function as magic function for ipython
1260
1261 def foo_impl(self,parameter_s=''):
1262 'My very own magic!. (Use docstrings, IPython reads them).'
1263 print 'Magic function. Passed parameter is between < >:'
1264 print '<%s>' % parameter_s
1265 print 'The self object is:',self
1266
1267 self.define_magic('foo',foo_impl)
1268 """
1269
1270 import new
1271 im = new.instancemethod(func,self, self.__class__)
1272 old = getattr(self, "magic_" + magicname, None)
1273 setattr(self, "magic_" + magicname, im)
1274 return old
1275
1276 def define_macro(self, name, themacro):
1277 """Define a new macro
1278
1279 Parameters
1280 ----------
1281 name : str
1282 The name of the macro.
1283 themacro : str or Macro
1284 The action to do upon invoking the macro. If a string, a new
1285 Macro object is created by passing the string to it.
1286 """
1287
1288 from IPython.core import macro
1289
1290 if isinstance(themacro, basestring):
1291 themacro = macro.Macro(themacro)
1292 if not isinstance(themacro, macro.Macro):
1293 raise ValueError('A macro must be a string or a Macro instance.')
1294 self.user_ns[name] = themacro
1295
1296 def define_alias(self, name, cmd):
1297 """ Define a new alias."""
1298
1299 if callable(cmd):
1300 self.alias_table[name] = cmd
1301 from IPython.core import shadowns
1302 setattr(shadowns, name, cmd)
1303 return
1304
1305 if isinstance(cmd, basestring):
1306 nargs = cmd.count('%s')
1307 if nargs>0 and cmd.find('%l')>=0:
1308 raise Exception('The %s and %l specifiers are mutually '
1309 'exclusive in alias definitions.')
1310
1311 self.alias_table[name] = (nargs,cmd)
1312 return
1313
1314 self.alias_table[name] = cmd
1178 1315
1179 1316 def ipalias(self,arg_s):
1180 1317 """Call an alias by name.
@@ -1205,12 +1342,35 b' class InteractiveShell(object,Magic):'
1205 1342 else:
1206 1343 error("Alias `%s` not found." % alias_name)
1207 1344
1208 def ipsystem(self,arg_s):
1345 def system(self, cmd):
1209 1346 """Make a system call, using IPython."""
1347 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1348
1349 def ex(self, cmd):
1350 """Execute a normal python statement in user namespace."""
1351 with self.builtin_trap:
1352 exec cmd in self.user_global_ns, self.user_ns
1210 1353
1211 self.system(arg_s)
1354 def ev(self, expr):
1355 """Evaluate python expression expr in user namespace.
1212 1356
1213 def complete(self,text):
1357 Returns the result of evaluation
1358 """
1359 with self.builtin_trap:
1360 result = eval(expr, self.user_global_ns, self.user_ns)
1361 return result
1362
1363 def getoutput(self, cmd):
1364 return getoutput(self.var_expand(cmd,depth=2),
1365 header=self.system_header,
1366 verbose=self.system_verbose)
1367
1368 def getoutputerror(self, cmd):
1369 return getoutputerror(self.var_expand(cmd,depth=2),
1370 header=self.system_header,
1371 verbose=self.system_verbose)
1372
1373 def complete(self, text):
1214 1374 """Return a sorted list of all possible completions on text.
1215 1375
1216 1376 Inputs:
@@ -1232,26 +1392,28 b' class InteractiveShell(object,Magic):'
1232 1392 In [9]: print x
1233 1393 hello
1234 1394
1235 In [10]: _ip.IP.complete('x.l')
1395 In [10]: _ip.complete('x.l')
1236 1396 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1237 1397 """
1238
1239 complete = self.Completer.complete
1240 state = 0
1241 # use a dict so we get unique keys, since ipyhton's multiple
1242 # completers can return duplicates. When we make 2.4 a requirement,
1243 # start using sets instead, which are faster.
1244 comps = {}
1245 while True:
1246 newcomp = complete(text,state,line_buffer=text)
1247 if newcomp is None:
1248 break
1249 comps[newcomp] = 1
1250 state += 1
1251 outcomps = comps.keys()
1252 outcomps.sort()
1253 #print "T:",text,"OC:",outcomps # dbg
1254 #print "vars:",self.user_ns.keys()
1398
1399 # Inject names into __builtin__ so we can complete on the added names.
1400 with self.builtin_trap:
1401 complete = self.Completer.complete
1402 state = 0
1403 # use a dict so we get unique keys, since ipyhton's multiple
1404 # completers can return duplicates. When we make 2.4 a requirement,
1405 # start using sets instead, which are faster.
1406 comps = {}
1407 while True:
1408 newcomp = complete(text,state,line_buffer=text)
1409 if newcomp is None:
1410 break
1411 comps[newcomp] = 1
1412 state += 1
1413 outcomps = comps.keys()
1414 outcomps.sort()
1415 #print "T:",text,"OC:",outcomps # dbg
1416 #print "vars:",self.user_ns.keys()
1255 1417 return outcomps
1256 1418
1257 1419 def set_completer_frame(self, frame=None):
@@ -1268,8 +1430,7 b' class InteractiveShell(object,Magic):'
1268 1430 These are ALL parameter-less aliases"""
1269 1431
1270 1432 for alias,cmd in self.auto_alias:
1271 self.getapi().defalias(alias,cmd)
1272
1433 self.define_alias(alias,cmd)
1273 1434
1274 1435 def alias_table_validate(self,verbose=0):
1275 1436 """Update information about the alias table.
@@ -1283,7 +1444,20 b' class InteractiveShell(object,Magic):'
1283 1444 if verbose:
1284 1445 print ("Deleting alias <%s>, it's a Python "
1285 1446 "keyword or builtin." % k)
1286
1447
1448 def set_next_input(self, s):
1449 """ Sets the 'default' input string for the next command line.
1450
1451 Requires readline.
1452
1453 Example:
1454
1455 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1456 [D:\ipython]|2> Hello Word_ # cursor is here
1457 """
1458
1459 self.rl_next_input = s
1460
1287 1461 def set_autoindent(self,value=None):
1288 1462 """Set the autoindent flag, checking for readline support.
1289 1463
@@ -1299,28 +1473,6 b' class InteractiveShell(object,Magic):'
1299 1473 else:
1300 1474 self.autoindent = value
1301 1475
1302 def rc_set_toggle(self,rc_field,value=None):
1303 """Set or toggle a field in IPython's rc config. structure.
1304
1305 If called with no arguments, it acts as a toggle.
1306
1307 If called with a non-existent field, the resulting AttributeError
1308 exception will propagate out."""
1309
1310 rc_val = getattr(self.rc,rc_field)
1311 if value is None:
1312 value = not rc_val
1313 setattr(self.rc,rc_field,value)
1314
1315 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1316 """Install the user configuration directory.
1317
1318 Notes
1319 -----
1320 DEPRECATED: use the top-level user_setup() function instead.
1321 """
1322 return user_setup(ipythondir,rc_suffix,mode)
1323
1324 1476 def atexit_operations(self):
1325 1477 """This will be executed at the time of exit.
1326 1478
@@ -1357,7 +1509,7 b' class InteractiveShell(object,Magic):'
1357 1509 self.input_hist_raw[:] = []
1358 1510 self.output_hist.clear()
1359 1511 # Restore the user namespaces to minimal usability
1360 self.init_namespaces()
1512 self.init_user_ns()
1361 1513
1362 1514 def savehist(self):
1363 1515 """Save input history to a file (via readline library)."""
@@ -1412,89 +1564,8 b' class InteractiveShell(object,Magic):'
1412 1564 self.readline.insert_text(self.rl_next_input)
1413 1565 self.rl_next_input = None
1414 1566
1415 def init_readline(self):
1416 """Command history completion/saving/reloading."""
1417
1418
1419 import IPython.utils.rlineimpl as readline
1420
1421 if not readline.have_readline:
1422 self.has_readline = 0
1423 self.readline = None
1424 # no point in bugging windows users with this every time:
1425 warn('Readline services not available on this platform.')
1426 else:
1427 sys.modules['readline'] = readline
1428 import atexit
1429 from IPython.core.completer import IPCompleter
1430 self.Completer = IPCompleter(self,
1431 self.user_ns,
1432 self.user_global_ns,
1433 self.rc.readline_omit__names,
1434 self.alias_table)
1435 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1436 self.strdispatchers['complete_command'] = sdisp
1437 self.Completer.custom_completers = sdisp
1438 # Platform-specific configuration
1439 if os.name == 'nt':
1440 self.readline_startup_hook = readline.set_pre_input_hook
1441 else:
1442 self.readline_startup_hook = readline.set_startup_hook
1443
1444 # Load user's initrc file (readline config)
1445 # Or if libedit is used, load editrc.
1446 inputrc_name = os.environ.get('INPUTRC')
1447 if inputrc_name is None:
1448 home_dir = get_home_dir()
1449 if home_dir is not None:
1450 inputrc_name = '.inputrc'
1451 if readline.uses_libedit:
1452 inputrc_name = '.editrc'
1453 inputrc_name = os.path.join(home_dir, inputrc_name)
1454 if os.path.isfile(inputrc_name):
1455 try:
1456 readline.read_init_file(inputrc_name)
1457 except:
1458 warn('Problems reading readline initialization file <%s>'
1459 % inputrc_name)
1460
1461 self.has_readline = 1
1462 self.readline = readline
1463 # save this in sys so embedded copies can restore it properly
1464 sys.ipcompleter = self.Completer.complete
1465 self.set_completer()
1466
1467 # Configure readline according to user's prefs
1468 # This is only done if GNU readline is being used. If libedit
1469 # is being used (as on Leopard) the readline config is
1470 # not run as the syntax for libedit is different.
1471 if not readline.uses_libedit:
1472 for rlcommand in self.rc.readline_parse_and_bind:
1473 #print "loading rl:",rlcommand # dbg
1474 readline.parse_and_bind(rlcommand)
1475
1476 # Remove some chars from the delimiters list. If we encounter
1477 # unicode chars, discard them.
1478 delims = readline.get_completer_delims().encode("ascii", "ignore")
1479 delims = delims.translate(string._idmap,
1480 self.rc.readline_remove_delims)
1481 readline.set_completer_delims(delims)
1482 # otherwise we end up with a monster history after a while:
1483 readline.set_history_length(1000)
1484 try:
1485 #print '*** Reading readline history' # dbg
1486 readline.read_history_file(self.histfile)
1487 except IOError:
1488 pass # It doesn't exist yet.
1489
1490 atexit.register(self.atexit_operations)
1491 del atexit
1492
1493 # Configure auto-indent for all platforms
1494 self.set_autoindent(self.rc.autoindent)
1495
1496 1567 def ask_yes_no(self,prompt,default=True):
1497 if self.rc.quiet:
1568 if self.quiet:
1498 1569 return True
1499 1570 return ask_yes_no(prompt,default)
1500 1571
@@ -1539,9 +1610,9 b' class InteractiveShell(object,Magic):'
1539 1610
1540 1611 In [10]: import IPython
1541 1612
1542 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1613 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1543 1614
1544 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1615 In [12]: IPython.__file__ in _ip._main_ns_cache
1545 1616 Out[12]: True
1546 1617 """
1547 1618 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
@@ -1556,14 +1627,14 b' class InteractiveShell(object,Magic):'
1556 1627
1557 1628 In [15]: import IPython
1558 1629
1559 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1630 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
1560 1631
1561 In [17]: len(_ip.IP._main_ns_cache) > 0
1632 In [17]: len(_ip._main_ns_cache) > 0
1562 1633 Out[17]: True
1563 1634
1564 In [18]: _ip.IP.clear_main_mod_cache()
1635 In [18]: _ip.clear_main_mod_cache()
1565 1636
1566 In [19]: len(_ip.IP._main_ns_cache) == 0
1637 In [19]: len(_ip._main_ns_cache) == 0
1567 1638 Out[19]: True
1568 1639 """
1569 1640 self._main_ns_cache.clear()
@@ -1577,7 +1648,7 b' class InteractiveShell(object,Magic):'
1577 1648
1578 1649 return False
1579 1650 try:
1580 if (self.rc.autoedit_syntax and
1651 if (self.autoedit_syntax and
1581 1652 not self.ask_yes_no('Return to editor to correct syntax error? '
1582 1653 '[Y/n] ','y')):
1583 1654 return False
@@ -1593,7 +1664,7 b' class InteractiveShell(object,Magic):'
1593 1664 try:
1594 1665 self.hooks.fix_error_editor(e.filename,
1595 1666 int0(e.lineno),int0(e.offset),e.msg)
1596 except ipapi.TryNext:
1667 except TryNext:
1597 1668 warn('Could not open editor')
1598 1669 return False
1599 1670 return True
@@ -1707,7 +1778,7 b' class InteractiveShell(object,Magic):'
1707 1778
1708 1779 if etype is SyntaxError:
1709 1780 self.showsyntaxerror(filename)
1710 elif etype is ipapi.UsageError:
1781 elif etype is UsageError:
1711 1782 print "UsageError:", value
1712 1783 else:
1713 1784 # WARNING: these variables are somewhat deprecated and not
@@ -1728,41 +1799,37 b' class InteractiveShell(object,Magic):'
1728 1799 except KeyboardInterrupt:
1729 1800 self.write("\nKeyboardInterrupt\n")
1730 1801
1731 def mainloop(self,banner=None):
1732 """Creates the local namespace and starts the mainloop.
1802 def mainloop(self, banner=None):
1803 """Start the mainloop.
1733 1804
1734 1805 If an optional banner argument is given, it will override the
1735 internally created default banner."""
1736
1737 if self.rc.c: # Emulate Python's -c option
1738 self.exec_init_cmd()
1739 if banner is None:
1740 if not self.rc.banner:
1741 banner = ''
1742 # banner is string? Use it directly!
1743 elif isinstance(self.rc.banner,basestring):
1744 banner = self.rc.banner
1745 else:
1746 banner = self.BANNER+self.banner2
1747
1748 # if you run stuff with -c <cmd>, raw hist is not updated
1749 # ensure that it's in sync
1750 if len(self.input_hist) != len (self.input_hist_raw):
1751 self.input_hist_raw = InputList(self.input_hist)
1806 internally created default banner.
1807 """
1808
1809 with self.builtin_trap:
1810 if self.c: # Emulate Python's -c option
1811 self.exec_init_cmd()
1752 1812
1753 while 1:
1754 try:
1755 self.interact(banner)
1756 #self.interact_with_readline()
1813 if self.display_banner:
1814 if banner is None:
1815 banner = self.banner
1757 1816
1758 # XXX for testing of a readline-decoupled repl loop, call
1759 # interact_with_readline above
1817 # if you run stuff with -c <cmd>, raw hist is not updated
1818 # ensure that it's in sync
1819 if len(self.input_hist) != len (self.input_hist_raw):
1820 self.input_hist_raw = InputList(self.input_hist)
1760 1821
1761 break
1762 except KeyboardInterrupt:
1763 # this should not be necessary, but KeyboardInterrupt
1764 # handling seems rather unpredictable...
1765 self.write("\nKeyboardInterrupt in interact()\n")
1822 while 1:
1823 try:
1824 self.interact()
1825 #self.interact_with_readline()
1826 # XXX for testing of a readline-decoupled repl loop, call
1827 # interact_with_readline above
1828 break
1829 except KeyboardInterrupt:
1830 # this should not be necessary, but KeyboardInterrupt
1831 # handling seems rather unpredictable...
1832 self.write("\nKeyboardInterrupt in interact()\n")
1766 1833
1767 1834 def exec_init_cmd(self):
1768 1835 """Execute a command given at the command line.
@@ -1770,81 +1837,10 b' class InteractiveShell(object,Magic):'
1770 1837 This emulates Python's -c option."""
1771 1838
1772 1839 #sys.argv = ['-c']
1773 self.push(self.prefilter(self.rc.c, False))
1774 if not self.rc.interact:
1840 self.push_line(self.prefilter(self.c, False))
1841 if not self.interactive:
1775 1842 self.ask_exit()
1776 1843
1777 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1778 """Embeds IPython into a running python program.
1779
1780 Input:
1781
1782 - header: An optional header message can be specified.
1783
1784 - local_ns, global_ns: working namespaces. If given as None, the
1785 IPython-initialized one is updated with __main__.__dict__, so that
1786 program variables become visible but user-specific configuration
1787 remains possible.
1788
1789 - stack_depth: specifies how many levels in the stack to go to
1790 looking for namespaces (when local_ns and global_ns are None). This
1791 allows an intermediate caller to make sure that this function gets
1792 the namespace from the intended level in the stack. By default (0)
1793 it will get its locals and globals from the immediate caller.
1794
1795 Warning: it's possible to use this in a program which is being run by
1796 IPython itself (via %run), but some funny things will happen (a few
1797 globals get overwritten). In the future this will be cleaned up, as
1798 there is no fundamental reason why it can't work perfectly."""
1799
1800 # Get locals and globals from caller
1801 if local_ns is None or global_ns is None:
1802 call_frame = sys._getframe(stack_depth).f_back
1803
1804 if local_ns is None:
1805 local_ns = call_frame.f_locals
1806 if global_ns is None:
1807 global_ns = call_frame.f_globals
1808
1809 # Update namespaces and fire up interpreter
1810
1811 # The global one is easy, we can just throw it in
1812 self.user_global_ns = global_ns
1813
1814 # but the user/local one is tricky: ipython needs it to store internal
1815 # data, but we also need the locals. We'll copy locals in the user
1816 # one, but will track what got copied so we can delete them at exit.
1817 # This is so that a later embedded call doesn't see locals from a
1818 # previous call (which most likely existed in a separate scope).
1819 local_varnames = local_ns.keys()
1820 self.user_ns.update(local_ns)
1821 #self.user_ns['local_ns'] = local_ns # dbg
1822
1823 # Patch for global embedding to make sure that things don't overwrite
1824 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1825 # FIXME. Test this a bit more carefully (the if.. is new)
1826 if local_ns is None and global_ns is None:
1827 self.user_global_ns.update(__main__.__dict__)
1828
1829 # make sure the tab-completer has the correct frame information, so it
1830 # actually completes using the frame's locals/globals
1831 self.set_completer_frame()
1832
1833 # before activating the interactive mode, we need to make sure that
1834 # all names in the builtin namespace needed by ipython point to
1835 # ourselves, and not to other instances.
1836 self.add_builtins()
1837
1838 self.interact(header)
1839
1840 # now, purge out the user namespace from anything we might have added
1841 # from the caller's local namespace
1842 delvar = self.user_ns.pop
1843 for var in local_varnames:
1844 delvar(var,None)
1845 # and clean builtins we may have overridden
1846 self.clean_builtins()
1847
1848 1844 def interact_prompt(self):
1849 1845 """ Print the prompt (in read-eval-print loop)
1850 1846
@@ -1883,9 +1879,9 b' class InteractiveShell(object,Magic):'
1883 1879 self.input_hist_raw.append('%s\n' % line)
1884 1880
1885 1881
1886 self.more = self.push(lineout)
1882 self.more = self.push_line(lineout)
1887 1883 if (self.SyntaxTB.last_syntax_error and
1888 self.rc.autoedit_syntax):
1884 self.autoedit_syntax):
1889 1885 self.edit_syntax_error()
1890 1886
1891 1887 def interact_with_readline(self):
@@ -1904,28 +1900,16 b' class InteractiveShell(object,Magic):'
1904 1900 line = raw_input_original().decode(self.stdin_encoding)
1905 1901 self.interact_handle_input(line)
1906 1902
1907
1908 1903 def interact(self, banner=None):
1909 """Closely emulate the interactive Python console.
1904 """Closely emulate the interactive Python console."""
1910 1905
1911 The optional banner argument specify the banner to print
1912 before the first interaction; by default it prints a banner
1913 similar to the one printed by the real Python interpreter,
1914 followed by the current class name in parentheses (so as not
1915 to confuse this with the real interpreter -- since it's so
1916 close!).
1917
1918 """
1919
1906 # batch run -> do not interact
1920 1907 if self.exit_now:
1921 # batch run -> do not interact
1922 1908 return
1923 cprt = 'Type "copyright", "credits" or "license" for more information.'
1924 if banner is None:
1925 self.write("Python %s on %s\n%s\n(%s)\n" %
1926 (sys.version, sys.platform, cprt,
1927 self.__class__.__name__))
1928 else:
1909
1910 if self.display_banner:
1911 if banner is None:
1912 banner = self.banner
1929 1913 self.write(banner)
1930 1914
1931 1915 more = 0
@@ -1954,7 +1938,7 b' class InteractiveShell(object,Magic):'
1954 1938 except:
1955 1939 self.showtraceback()
1956 1940 try:
1957 line = self.raw_input(prompt,more)
1941 line = self.raw_input(prompt, more)
1958 1942 if self.exit_now:
1959 1943 # quick exit on sys.std[in|out] close
1960 1944 break
@@ -1990,9 +1974,9 b' class InteractiveShell(object,Magic):'
1990 1974 # asynchronously by signal handlers, for example.
1991 1975 self.showtraceback()
1992 1976 else:
1993 more = self.push(line)
1977 more = self.push_line(line)
1994 1978 if (self.SyntaxTB.last_syntax_error and
1995 self.rc.autoedit_syntax):
1979 self.autoedit_syntax):
1996 1980 self.edit_syntax_error()
1997 1981
1998 1982 # We are off again...
@@ -2022,8 +2006,22 b' class InteractiveShell(object,Magic):'
2022 2006 """
2023 2007 self.showtraceback((etype,value,tb),tb_offset=0)
2024 2008
2025 def expand_aliases(self,fn,rest):
2026 """ Expand multiple levels of aliases:
2009 def expand_alias(self, line):
2010 """ Expand an alias in the command line
2011
2012 Returns the provided command line, possibly with the first word
2013 (command) translated according to alias expansion rules.
2014
2015 [ipython]|16> _ip.expand_aliases("np myfile.txt")
2016 <16> 'q:/opt/np/notepad++.exe myfile.txt'
2017 """
2018
2019 pre,fn,rest = self.split_user_input(line)
2020 res = pre + self.expand_aliases(fn, rest)
2021 return res
2022
2023 def expand_aliases(self, fn, rest):
2024 """Expand multiple levels of aliases:
2027 2025
2028 2026 if:
2029 2027
@@ -2130,40 +2128,137 b' class InteractiveShell(object,Magic):'
2130 2128 else:
2131 2129 self.indent_current_nsp = 0
2132 2130
2133 def runlines(self,lines):
2131 def push(self, variables, interactive=True):
2132 """Inject a group of variables into the IPython user namespace.
2133
2134 Parameters
2135 ----------
2136 variables : dict, str or list/tuple of str
2137 The variables to inject into the user's namespace. If a dict,
2138 a simple update is done. If a str, the string is assumed to
2139 have variable names separated by spaces. A list/tuple of str
2140 can also be used to give the variable names. If just the variable
2141 names are give (list/tuple/str) then the variable values looked
2142 up in the callers frame.
2143 interactive : bool
2144 If True (default), the variables will be listed with the ``who``
2145 magic.
2146 """
2147 vdict = None
2148
2149 # We need a dict of name/value pairs to do namespace updates.
2150 if isinstance(variables, dict):
2151 vdict = variables
2152 elif isinstance(variables, (basestring, list, tuple)):
2153 if isinstance(variables, basestring):
2154 vlist = variables.split()
2155 else:
2156 vlist = variables
2157 vdict = {}
2158 cf = sys._getframe(1)
2159 for name in vlist:
2160 try:
2161 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
2162 except:
2163 print ('Could not get variable %s from %s' %
2164 (name,cf.f_code.co_name))
2165 else:
2166 raise ValueError('variables must be a dict/str/list/tuple')
2167
2168 # Propagate variables to user namespace
2169 self.user_ns.update(vdict)
2170
2171 # And configure interactive visibility
2172 config_ns = self.user_config_ns
2173 if interactive:
2174 for name, val in vdict.iteritems():
2175 config_ns.pop(name, None)
2176 else:
2177 for name,val in vdict.iteritems():
2178 config_ns[name] = val
2179
2180 def cleanup_ipy_script(self, script):
2181 """Make a script safe for self.runlines()
2182
2183 Notes
2184 -----
2185 This was copied over from the old ipapi and probably can be done
2186 away with once we move to block based interpreter.
2187
2188 - Removes empty lines Suffixes all indented blocks that end with
2189 - unindented lines with empty lines
2190 """
2191
2192 res = []
2193 lines = script.splitlines()
2194
2195 level = 0
2196 for l in lines:
2197 lstripped = l.lstrip()
2198 stripped = l.strip()
2199 if not stripped:
2200 continue
2201 newlevel = len(l) - len(lstripped)
2202 def is_secondary_block_start(s):
2203 if not s.endswith(':'):
2204 return False
2205 if (s.startswith('elif') or
2206 s.startswith('else') or
2207 s.startswith('except') or
2208 s.startswith('finally')):
2209 return True
2210
2211 if level > 0 and newlevel == 0 and \
2212 not is_secondary_block_start(stripped):
2213 # add empty line
2214 res.append('')
2215
2216 res.append(l)
2217 level = newlevel
2218 return '\n'.join(res) + '\n'
2219
2220 def runlines(self, lines, clean=False):
2134 2221 """Run a string of one or more lines of source.
2135 2222
2136 2223 This method is capable of running a string containing multiple source
2137 2224 lines, as if they had been entered at the IPython prompt. Since it
2138 2225 exposes IPython's processing machinery, the given strings can contain
2139 magic calls (%magic), special shell access (!cmd), etc."""
2226 magic calls (%magic), special shell access (!cmd), etc.
2227 """
2228
2229 if isinstance(lines, (list, tuple)):
2230 lines = '\n'.join(lines)
2231
2232 if clean:
2233 lines = self.cleanup_ipy_script(lines)
2140 2234
2141 2235 # We must start with a clean buffer, in case this is run from an
2142 2236 # interactive IPython session (via a magic, for example).
2143 2237 self.resetbuffer()
2144 lines = lines.split('\n')
2238 lines = lines.splitlines()
2145 2239 more = 0
2146
2147 for line in lines:
2148 # skip blank lines so we don't mess up the prompt counter, but do
2149 # NOT skip even a blank line if we are in a code block (more is
2150 # true)
2240
2241 with self.builtin_trap:
2242 for line in lines:
2243 # skip blank lines so we don't mess up the prompt counter, but do
2244 # NOT skip even a blank line if we are in a code block (more is
2245 # true)
2151 2246
2152 if line or more:
2153 # push to raw history, so hist line numbers stay in sync
2154 self.input_hist_raw.append("# " + line + "\n")
2155 more = self.push(self.prefilter(line,more))
2156 # IPython's runsource returns None if there was an error
2157 # compiling the code. This allows us to stop processing right
2158 # away, so the user gets the error message at the right place.
2159 if more is None:
2160 break
2161 else:
2162 self.input_hist_raw.append("\n")
2163 # final newline in case the input didn't have it, so that the code
2164 # actually does get executed
2165 if more:
2166 self.push('\n')
2247 if line or more:
2248 # push to raw history, so hist line numbers stay in sync
2249 self.input_hist_raw.append("# " + line + "\n")
2250 more = self.push_line(self.prefilter(line,more))
2251 # IPython's runsource returns None if there was an error
2252 # compiling the code. This allows us to stop processing right
2253 # away, so the user gets the error message at the right place.
2254 if more is None:
2255 break
2256 else:
2257 self.input_hist_raw.append("\n")
2258 # final newline in case the input didn't have it, so that the code
2259 # actually does get executed
2260 if more:
2261 self.push_line('\n')
2167 2262
2168 2263 def runsource(self, source, filename='<input>', symbol='single'):
2169 2264 """Compile and run some source in the interpreter.
@@ -2271,7 +2366,7 b' class InteractiveShell(object,Magic):'
2271 2366 self.code_to_run = None
2272 2367 return outflag
2273 2368
2274 def push(self, line):
2369 def push_line(self, line):
2275 2370 """Push a line to the interpreter.
2276 2371
2277 2372 The line should not have a trailing newline; it may have
@@ -2419,7 +2514,7 b' class InteractiveShell(object,Magic):'
2419 2514
2420 2515 # print '***cont',continue_prompt # dbg
2421 2516 # special handlers are only allowed for single line statements
2422 if continue_prompt and not self.rc.multi_line_specials:
2517 if continue_prompt and not self.multi_line_specials:
2423 2518 return self.handle_normal(line_info)
2424 2519
2425 2520
@@ -2481,7 +2576,7 b' class InteractiveShell(object,Magic):'
2481 2576 # print "=>",tgt #dbg
2482 2577 if callable(tgt):
2483 2578 if '$' in line_info.line:
2484 call_meth = '(_ip, _ip.itpl(%s))'
2579 call_meth = '(_ip, _ip.var_expand(%s))'
2485 2580 else:
2486 2581 call_meth = '(_ip,%s)'
2487 2582 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
@@ -2549,7 +2644,7 b' class InteractiveShell(object,Magic):'
2549 2644 self.log(line,line,continue_prompt)
2550 2645 return line
2551 2646
2552 force_auto = isinstance(obj, ipapi.IPyAutocall)
2647 force_auto = isinstance(obj, IPyAutocall)
2553 2648 auto_rewrite = True
2554 2649
2555 2650 if pre == self.ESC_QUOTE:
@@ -2565,7 +2660,7 b' class InteractiveShell(object,Magic):'
2565 2660 # We only apply it to argument-less calls if the autocall
2566 2661 # parameter is set to 2. We only need to check that autocall is <
2567 2662 # 2, since this function isn't called unless it's at least 1.
2568 if not theRest and (self.rc.autocall < 2) and not force_auto:
2663 if not theRest and (self.autocall < 2) and not force_auto:
2569 2664 newcmd = '%s %s' % (iFun,theRest)
2570 2665 auto_rewrite = False
2571 2666 else:
@@ -2623,7 +2718,7 b' class InteractiveShell(object,Magic):'
2623 2718 #print 'line:<%r>' % line # dbg
2624 2719 self.magic_pinfo(line)
2625 2720 else:
2626 page(self.usage,screen_lines=self.rc.screen_length)
2721 page(self.usage,screen_lines=self.usable_screen_length)
2627 2722 return '' # Empty string is needed here!
2628 2723 except:
2629 2724 # Pass any other exceptions through to the normal handler
@@ -2632,18 +2727,6 b' class InteractiveShell(object,Magic):'
2632 2727 # If the code compiles ok, we should handle it normally
2633 2728 return self.handle_normal(line_info)
2634 2729
2635 def getapi(self):
2636 """ Get an IPApi object for this shell instance
2637
2638 Getting an IPApi object is always preferable to accessing the shell
2639 directly, but this holds true especially for extensions.
2640
2641 It should always be possible to implement an extension with IPApi
2642 alone. If not, contact maintainer to request an addition.
2643
2644 """
2645 return self.api
2646
2647 2730 def handle_emacs(self, line_info):
2648 2731 """Handle input lines marked by python-mode."""
2649 2732
@@ -2653,6 +2736,21 b' class InteractiveShell(object,Magic):'
2653 2736 # The input cache shouldn't be updated
2654 2737 return line_info.line
2655 2738
2739 def var_expand(self,cmd,depth=0):
2740 """Expand python variables in a string.
2741
2742 The depth argument indicates how many frames above the caller should
2743 be walked to look for the local namespace where to expand variables.
2744
2745 The global namespace for expansion is always the user's interactive
2746 namespace.
2747 """
2748
2749 return str(ItplNS(cmd,
2750 self.user_ns, # globals
2751 # Skip our own frame in searching for locals:
2752 sys._getframe(depth+1).f_locals # locals
2753 ))
2656 2754
2657 2755 def mktempfile(self,data=None):
2658 2756 """Make a new tempfile and return its filename.
@@ -2690,8 +2788,7 b' class InteractiveShell(object,Magic):'
2690 2788 """Handle interactive exit.
2691 2789
2692 2790 This method calls the ask_exit callback."""
2693
2694 if self.rc.confirm_exit:
2791 if self.confirm_exit:
2695 2792 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2696 2793 self.ask_exit()
2697 2794 else:
@@ -7,10 +7,8 b''
7 7 # the file COPYING, distributed as part of this software.
8 8 #*****************************************************************************
9 9
10 from IPython.core import ipapi
11
12 10 from IPython.utils.genutils import Term
13 from IPython.core.ipapi import IPyAutocall
11 from IPython.core.autocall import IPyAutocall
14 12
15 13 class Macro(IPyAutocall):
16 14 """Simple class to store the value of macros as strings.
@@ -45,16 +45,17 b' except ImportError:'
45 45 import IPython
46 46 from IPython.utils import wildcard
47 47 from IPython.core import debugger, oinspect
48 from IPython.core.error import TryNext
48 49 from IPython.core.fakemodule import FakeModule
49 50 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
50 51 from IPython.utils.PyColorize import Parser
51 52 from IPython.utils.ipstruct import Struct
52 53 from IPython.core.macro import Macro
53 54 from IPython.utils.genutils import *
55 from IPython.core.page import page
54 56 from IPython.utils import platutils
55 57 import IPython.utils.generics
56 from IPython.core import ipapi
57 from IPython.core.ipapi import UsageError
58 from IPython.core.error import UsageError
58 59 from IPython.testing import decorators as testdec
59 60
60 61 #***************************************************************************
@@ -378,7 +379,7 b' python-profiler package from non-free.""")'
378 379 mesc = self.shell.ESC_MAGIC
379 380 print 'Available magic functions:\n'+mesc+\
380 381 (' '+mesc).join(self.lsmagic())
381 print '\n' + Magic.auto_status[self.shell.rc.automagic]
382 print '\n' + Magic.auto_status[self.shell.automagic]
382 383 return None
383 384
384 385 def magic_magic(self, parameter_s = ''):
@@ -470,8 +471,8 b' ipythonrc file, placing a line like:'
470 471
471 472 will define %pf as a new name for %profile.
472 473
473 You can also call magics in code using the ipmagic() function, which IPython
474 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
474 You can also call magics in code using the magic() function, which IPython
475 automatically adds to the builtin namespace. Type 'magic?' for details.
475 476
476 477 For a list of the available magic functions, use %lsmagic. For a description
477 478 of any of them, type %magic_name?, e.g. '%cd?'.
@@ -483,9 +484,9 b' Currently the magic system has the following functions:\\n"""'
483 484 "\n\n%s%s\n\n%s" % (outmsg,
484 485 magic_docs,mesc,mesc,
485 486 (' '+mesc).join(self.lsmagic()),
486 Magic.auto_status[self.shell.rc.automagic] ) )
487 Magic.auto_status[self.shell.automagic] ) )
487 488
488 page(outmsg,screen_lines=self.shell.rc.screen_length)
489 page(outmsg,screen_lines=self.shell.usable_screen_length)
489 490
490 491
491 492 def magic_autoindent(self, parameter_s = ''):
@@ -512,15 +513,14 b' Currently the magic system has the following functions:\\n"""'
512 513 delete the variable (del var), the previously shadowed magic function
513 514 becomes visible to automagic again."""
514 515
515 rc = self.shell.rc
516 516 arg = parameter_s.lower()
517 517 if parameter_s in ('on','1','true'):
518 rc.automagic = True
518 self.shell.automagic = True
519 519 elif parameter_s in ('off','0','false'):
520 rc.automagic = False
520 self.shell.automagic = False
521 521 else:
522 rc.automagic = not rc.automagic
523 print '\n' + Magic.auto_status[rc.automagic]
522 self.shell.automagic = not self.shell.automagic
523 print '\n' + Magic.auto_status[self.shell.automagic]
524 524
525 525 @testdec.skip_doctest
526 526 def magic_autocall(self, parameter_s = ''):
@@ -566,8 +566,6 b' Currently the magic system has the following functions:\\n"""'
566 566 # all-random (note for auto-testing)
567 567 """
568 568
569 rc = self.shell.rc
570
571 569 if parameter_s:
572 570 arg = int(parameter_s)
573 571 else:
@@ -578,18 +576,18 b' Currently the magic system has the following functions:\\n"""'
578 576 return
579 577
580 578 if arg in (0,1,2):
581 rc.autocall = arg
579 self.shell.autocall = arg
582 580 else: # toggle
583 if rc.autocall:
584 self._magic_state.autocall_save = rc.autocall
585 rc.autocall = 0
581 if self.shell.autocall:
582 self._magic_state.autocall_save = self.shell.autocall
583 self.shell.autocall = 0
586 584 else:
587 585 try:
588 rc.autocall = self._magic_state.autocall_save
586 self.shell.autocall = self._magic_state.autocall_save
589 587 except AttributeError:
590 rc.autocall = self._magic_state.autocall_save = 1
588 self.shell.autocall = self._magic_state.autocall_save = 1
591 589
592 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
590 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
593 591
594 592 def magic_system_verbose(self, parameter_s = ''):
595 593 """Set verbose printing of system calls.
@@ -600,10 +598,13 b' Currently the magic system has the following functions:\\n"""'
600 598 val = bool(eval(parameter_s))
601 599 else:
602 600 val = None
603
604 self.shell.rc_set_toggle('system_verbose',val)
601
602 if self.shell.system_verbose:
603 self.shell.system_verbose = False
604 else:
605 self.shell.system_verbose = True
605 606 print "System verbose printing is:",\
606 ['OFF','ON'][self.shell.rc.system_verbose]
607 ['OFF','ON'][self.shell.system_verbose]
607 608
608 609
609 610 def magic_page(self, parameter_s=''):
@@ -633,8 +634,8 b' Currently the magic system has the following functions:\\n"""'
633 634
634 635 def magic_profile(self, parameter_s=''):
635 636 """Print your currently active IPyhton profile."""
636 if self.shell.rc.profile:
637 printpl('Current IPython profile: $self.shell.rc.profile.')
637 if self.shell.profile:
638 printpl('Current IPython profile: $self.shell.profile.')
638 639 else:
639 640 print 'No profile active.'
640 641
@@ -720,7 +721,7 b' Currently the magic system has the following functions:\\n"""'
720 721 try:
721 722 IPython.utils.generics.inspect_object(info.obj)
722 723 return
723 except ipapi.TryNext:
724 except TryNext:
724 725 pass
725 726 # Get the docstring of the class property if it exists.
726 727 path = oname.split('.')
@@ -848,7 +849,7 b' Currently the magic system has the following functions:\\n"""'
848 849 elif opts.has_key('c'):
849 850 ignore_case = False
850 851 else:
851 ignore_case = not shell.rc.wildcards_case_sensitive
852 ignore_case = not shell.wildcards_case_sensitive
852 853
853 854 # Build list of namespaces to search from user options
854 855 def_search.extend(opt('s',[]))
@@ -1132,7 +1133,6 b' Currently the magic system has the following functions:\\n"""'
1132 1133 log_raw_input = 'r' in opts
1133 1134 timestamp = 't' in opts
1134 1135
1135 rc = self.shell.rc
1136 1136 logger = self.shell.logger
1137 1137
1138 1138 # if no args are given, the defaults set in the logger constructor by
@@ -1149,11 +1149,14 b' Currently the magic system has the following functions:\\n"""'
1149 1149 # put logfname into rc struct as if it had been called on the command
1150 1150 # line, so it ends up saved in the log header Save it in case we need
1151 1151 # to restore it...
1152 old_logfile = rc.opts.get('logfile','')
1152 old_logfile = self.shell.logfile
1153 1153 if logfname:
1154 1154 logfname = os.path.expanduser(logfname)
1155 rc.opts.logfile = logfname
1156 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1155 self.shell.logfile = logfname
1156 # TODO: we need to re-think how logs with args/opts are replayed
1157 # and tracked.
1158 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1159 loghead = self.shell.loghead_tpl % ('','')
1157 1160 try:
1158 1161 started = logger.logstart(logfname,loghead,logmode,
1159 1162 log_output,timestamp,log_raw_input)
@@ -1421,7 +1424,7 b' Currently the magic system has the following functions:\\n"""'
1421 1424 output = stdout_trap.getvalue()
1422 1425 output = output.rstrip()
1423 1426
1424 page(output,screen_lines=self.shell.rc.screen_length)
1427 page(output,screen_lines=self.shell.usable_screen_length)
1425 1428 print sys_exit,
1426 1429
1427 1430 dump_file = opts.D[0]
@@ -1569,7 +1572,7 b' Currently the magic system has the following functions:\\n"""'
1569 1572 return
1570 1573
1571 1574 if filename.lower().endswith('.ipy'):
1572 self.api.runlines(open(filename).read())
1575 self.runlines(open(filename).read(), clean=True)
1573 1576 return
1574 1577
1575 1578 # Control the response to exit() calls made by the script being run
@@ -1622,7 +1625,7 b' Currently the magic system has the following functions:\\n"""'
1622 1625 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1623 1626 else:
1624 1627 if opts.has_key('d'):
1625 deb = debugger.Pdb(self.shell.rc.colors)
1628 deb = debugger.Pdb(self.shell.colors)
1626 1629 # reset Breakpoint state, which is moronically kept
1627 1630 # in a class
1628 1631 bdb.Breakpoint.next = 1
@@ -2061,7 +2064,7 b' Currently the magic system has the following functions:\\n"""'
2061 2064 #print 'rng',ranges # dbg
2062 2065 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2063 2066 macro = Macro(lines)
2064 self.shell.user_ns.update({name:macro})
2067 self.shell.define_macro(name, macro)
2065 2068 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2066 2069 print 'Macro contents:'
2067 2070 print macro,
@@ -2391,7 +2394,7 b' Currently the magic system has the following functions:\\n"""'
2391 2394 sys.stdout.flush()
2392 2395 try:
2393 2396 self.shell.hooks.editor(filename,lineno)
2394 except ipapi.TryNext:
2397 except TryNext:
2395 2398 warn('Could not open editor')
2396 2399 return
2397 2400
@@ -2492,7 +2495,7 b' Defaulting color scheme to \'NoColor\'"""'
2492 2495 except:
2493 2496 color_switch_err('prompt')
2494 2497 else:
2495 shell.rc.colors = \
2498 shell.colors = \
2496 2499 shell.outputcache.color_table.active_scheme_name
2497 2500 # Set exception colors
2498 2501 try:
@@ -2509,7 +2512,7 b' Defaulting color scheme to \'NoColor\'"""'
2509 2512 color_switch_err('system exception handler')
2510 2513
2511 2514 # Set info (for 'object?') colors
2512 if shell.rc.color_info:
2515 if shell.color_info:
2513 2516 try:
2514 2517 shell.inspector.set_active_scheme(new_scheme)
2515 2518 except:
@@ -2528,17 +2531,17 b' Defaulting color scheme to \'NoColor\'"""'
2528 2531 than more) in your system, using colored object information displays
2529 2532 will not work properly. Test it and see."""
2530 2533
2531 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2532 self.magic_colors(self.shell.rc.colors)
2534 self.shell.color_info = not self.shell.color_info
2535 self.magic_colors(self.shell.colors)
2533 2536 print 'Object introspection functions have now coloring:',
2534 print ['OFF','ON'][self.shell.rc.color_info]
2537 print ['OFF','ON'][int(self.shell.color_info)]
2535 2538
2536 2539 def magic_Pprint(self, parameter_s=''):
2537 2540 """Toggle pretty printing on/off."""
2538 2541
2539 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2542 self.shell.pprint = 1 - self.shell.pprint
2540 2543 print 'Pretty printing has been turned', \
2541 ['OFF','ON'][self.shell.rc.pprint]
2544 ['OFF','ON'][self.shell.pprint]
2542 2545
2543 2546 def magic_exit(self, parameter_s=''):
2544 2547 """Exit IPython, confirming if configured to do so.
@@ -2683,12 +2686,9 b' Defaulting color scheme to \'NoColor\'"""'
2683 2686 This function also resets the root module cache of module completer,
2684 2687 used on slow filesystems.
2685 2688 """
2686
2687
2688 ip = self.api
2689 2689
2690 2690 # for the benefit of module completer in ipy_completers.py
2691 del ip.db['rootmodules']
2691 del self.db['rootmodules']
2692 2692
2693 2693 path = [os.path.abspath(os.path.expanduser(p)) for p in
2694 2694 os.environ.get('PATH','').split(os.pathsep)]
@@ -2743,7 +2743,7 b' Defaulting color scheme to \'NoColor\'"""'
2743 2743 # no, we don't want them. if %rehashx clobbers them, good,
2744 2744 # we'll probably get better versions
2745 2745 # self.shell.init_auto_alias()
2746 db = ip.db
2746 db = self.db
2747 2747 db['syscmdlist'] = syscmdlist
2748 2748 finally:
2749 2749 os.chdir(savedir)
@@ -2853,9 +2853,8 b' Defaulting color scheme to \'NoColor\'"""'
2853 2853 if ps:
2854 2854 try:
2855 2855 os.chdir(os.path.expanduser(ps))
2856 if self.shell.rc.term_title:
2857 #print 'set term title:',self.shell.rc.term_title # dbg
2858 platutils.set_term_title('IPy ' + abbrev_cwd())
2856 if self.shell.term_title:
2857 platutils.set_term_title('IPython: ' + abbrev_cwd())
2859 2858 except OSError:
2860 2859 print sys.exc_info()[1]
2861 2860 else:
@@ -2867,8 +2866,8 b' Defaulting color scheme to \'NoColor\'"""'
2867 2866
2868 2867 else:
2869 2868 os.chdir(self.shell.home_dir)
2870 if self.shell.rc.term_title:
2871 platutils.set_term_title("IPy ~")
2869 if self.shell.term_title:
2870 platutils.set_term_title('IPython: ' + '~')
2872 2871 cwd = os.getcwd()
2873 2872 dhist = self.shell.user_ns['_dh']
2874 2873
@@ -3171,7 +3170,7 b' Defaulting color scheme to \'NoColor\'"""'
3171 3170 esc_magic = self.shell.ESC_MAGIC
3172 3171 # Identify magic commands even if automagic is on (which means
3173 3172 # the in-memory version is different from that typed by the user).
3174 if self.shell.rc.automagic:
3173 if self.shell.automagic:
3175 3174 start_magic = esc_magic+start
3176 3175 else:
3177 3176 start_magic = start
@@ -3265,7 +3264,7 b' Defaulting color scheme to \'NoColor\'"""'
3265 3264 return
3266 3265
3267 3266 page(self.shell.pycolorize(cont),
3268 screen_lines=self.shell.rc.screen_length)
3267 screen_lines=self.shell.usable_screen_length)
3269 3268
3270 3269 def _rerun_pasted(self):
3271 3270 """ Rerun a previously pasted command.
@@ -3438,7 +3437,7 b' Defaulting color scheme to \'NoColor\'"""'
3438 3437 ipinstallation = path(IPython.__file__).dirname()
3439 3438 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3440 3439 src_config = ipinstallation / 'config' / 'userconfig'
3441 userdir = path(ip.options.ipythondir)
3440 userdir = path(ip.config.IPYTHONDIR)
3442 3441 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3443 3442 print ">",cmd
3444 3443 shell(cmd)
@@ -3478,7 +3477,6 b' Defaulting color scheme to \'NoColor\'"""'
3478 3477 # Shorthands
3479 3478 shell = self.shell
3480 3479 oc = shell.outputcache
3481 rc = shell.rc
3482 3480 meta = shell.meta
3483 3481 # dstore is a data store kept in the instance metadata bag to track any
3484 3482 # changes we make, so we can undo them later.
@@ -3487,12 +3485,12 b' Defaulting color scheme to \'NoColor\'"""'
3487 3485
3488 3486 # save a few values we'll need to recover later
3489 3487 mode = save_dstore('mode',False)
3490 save_dstore('rc_pprint',rc.pprint)
3488 save_dstore('rc_pprint',shell.pprint)
3491 3489 save_dstore('xmode',shell.InteractiveTB.mode)
3492 save_dstore('rc_separate_out',rc.separate_out)
3493 save_dstore('rc_separate_out2',rc.separate_out2)
3494 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3495 save_dstore('rc_separate_in',rc.separate_in)
3490 save_dstore('rc_separate_out',shell.separate_out)
3491 save_dstore('rc_separate_out2',shell.separate_out2)
3492 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3493 save_dstore('rc_separate_in',shell.separate_in)
3496 3494
3497 3495 if mode == False:
3498 3496 # turn on
@@ -3510,7 +3508,7 b' Defaulting color scheme to \'NoColor\'"""'
3510 3508 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3511 3509 oc.prompt_out.pad_left = False
3512 3510
3513 rc.pprint = False
3511 shell.pprint = False
3514 3512
3515 3513 shell.magic_xmode('Plain')
3516 3514
@@ -3518,9 +3516,9 b' Defaulting color scheme to \'NoColor\'"""'
3518 3516 # turn off
3519 3517 ipaste.deactivate_prefilter()
3520 3518
3521 oc.prompt1.p_template = rc.prompt_in1
3522 oc.prompt2.p_template = rc.prompt_in2
3523 oc.prompt_out.p_template = rc.prompt_out
3519 oc.prompt1.p_template = shell.prompt_in1
3520 oc.prompt2.p_template = shell.prompt_in2
3521 oc.prompt_out.p_template = shell.prompt_out
3524 3522
3525 3523 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3526 3524
@@ -28,7 +28,8 b' import types'
28 28
29 29 # IPython's own
30 30 from IPython.utils import PyColorize
31 from IPython.utils.genutils import page,indent,Term
31 from IPython.utils.genutils import indent, Term
32 from IPython.core.page import page
32 33 from IPython.external.Itpl import itpl
33 34 from IPython.utils.wildcard import list_namespace
34 35 from IPython.utils.coloransi import *
@@ -8,7 +8,8 b' transforming work.'
8 8 __docformat__ = "restructuredtext en"
9 9
10 10 import re
11 from IPython.core import ipapi
11 from IPython.core.autocall import IPyAutocall
12
12 13
13 14 class LineInfo(object):
14 15 """A single line of input and associated info.
@@ -178,8 +179,8 b' def checkEmacs(l_info,ip):'
178 179 def checkIPyAutocall(l_info,ip):
179 180 "Instances of IPyAutocall in user_ns get autocalled immediately"
180 181 obj = ip.user_ns.get(l_info.iFun, None)
181 if isinstance(obj, ipapi.IPyAutocall):
182 obj.set_ip(ip.api)
182 if isinstance(obj, IPyAutocall):
183 obj.set_ip(ip)
183 184 return ip.handle_auto
184 185 else:
185 186 return None
@@ -191,7 +192,7 b' def checkMultiLineMagic(l_info,ip):'
191 192 # iFun and *not* the preChar. Also note that the below test matches
192 193 # both ! and !!.
193 194 if l_info.continue_prompt \
194 and ip.rc.multi_line_specials:
195 and ip.multi_line_specials:
195 196 if l_info.iFun.startswith(ip.ESC_MAGIC):
196 197 return ip.handle_magic
197 198 else:
@@ -231,11 +232,11 b' def checkAutomagic(l_info,ip):'
231 232 check_esc_chars. This just checks for automagic. Also, before
232 233 triggering the magic handler, make sure that there is nothing in the
233 234 user namespace which could shadow it."""
234 if not ip.rc.automagic or not hasattr(ip,'magic_'+l_info.iFun):
235 if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun):
235 236 return None
236 237
237 238 # We have a likely magic method. Make sure we should actually call it.
238 if l_info.continue_prompt and not ip.rc.multi_line_specials:
239 if l_info.continue_prompt and not ip.multi_line_specials:
239 240 return None
240 241
241 242 head = l_info.iFun.split('.',1)[0]
@@ -271,7 +272,7 b' def checkPythonOps(l_info,ip):'
271 272
272 273 def checkAutocall(l_info,ip):
273 274 "Check if the initial word/function is callable and autocall is on."
274 if not ip.rc.autocall:
275 if not ip.autocall:
275 276 return None
276 277
277 278 oinfo = l_info.ofind(ip) # This can mutate state via getattr
@@ -23,7 +23,7 b' import time'
23 23 from IPython.utils import coloransi
24 24 from IPython.core import release
25 25 from IPython.external.Itpl import ItplNS
26 from IPython.core.ipapi import TryNext
26 from IPython.core.error import TryNext
27 27 from IPython.utils.ipstruct import Struct
28 28 from IPython.core.macro import Macro
29 29 import IPython.utils.generics
@@ -31,4 +31,4 b' class A(object):'
31 31 a = A()
32 32
33 33 # Now, we force an exit, the caller will check that the del printout was given
34 _ip.IP.ask_exit()
34 _ip.ask_exit()
@@ -28,9 +28,6 b' def test_import_ipapi():'
28 28 def test_import_iplib():
29 29 from IPython.core import iplib
30 30
31 def test_import_ipmaker():
32 from IPython.core import ipmaker
33
34 31 def test_import_logger():
35 32 from IPython.core import logger
36 33
@@ -15,6 +15,7 b' import nose.tools as nt'
15 15 # our own packages
16 16 from IPython.core import iplib
17 17 from IPython.core import ipapi
18 from IPython.core.oldusersetup import user_setup
18 19
19 20 #-----------------------------------------------------------------------------
20 21 # Globals
@@ -37,8 +38,6 b' if ip is None:'
37 38 # consistency when the test suite is being run via iptest
38 39 from IPython.testing.plugin import ipdoctest
39 40 ip = ipapi.get()
40
41 IP = ip.IP # This is the actual IPython shell 'raw' object.
42 41
43 42 #-----------------------------------------------------------------------------
44 43 # Test functions
@@ -46,10 +45,10 b" IP = ip.IP # This is the actual IPython shell 'raw' object."
46 45
47 46 def test_reset():
48 47 """reset must clear most namespaces."""
49 IP.reset() # first, it should run without error
48 ip.reset() # first, it should run without error
50 49 # Then, check that most namespaces end up empty
51 for ns in IP.ns_refs_table:
52 if ns is IP.user_ns:
50 for ns in ip.ns_refs_table:
51 if ns is ip.user_ns:
53 52 # The user namespace is reset with some data, so we can't check for
54 53 # it being empty
55 54 continue
@@ -59,12 +58,12 b' def test_reset():'
59 58 # make sure that user_setup can be run re-entrantly in 'install' mode.
60 59 def test_user_setup():
61 60 # use a lambda to pass kwargs to the generator
62 user_setup = lambda a,k: iplib.user_setup(*a,**k)
61 user_setup = lambda a,k: user_setup(*a,**k)
63 62 kw = dict(mode='install', interactive=False)
64 63
65 64 # Call the user setup and verify that the directory exists
66 yield user_setup, (ip.options.ipythondir,''), kw
67 yield os.path.isdir, ip.options.ipythondir
65 yield user_setup, (ip.config.IPYTHONDIR,''), kw
66 yield os.path.isdir, ip.config.IPYTHONDIR
68 67
69 68 # Now repeat the operation with a non-existent directory. Check both that
70 69 # the call succeeds and that the directory is created.
@@ -20,14 +20,14 b' from IPython.testing import tools as tt'
20 20
21 21 def test_rehashx():
22 22 # clear up everything
23 _ip.IP.alias_table.clear()
23 _ip.alias_table.clear()
24 24 del _ip.db['syscmdlist']
25 25
26 26 _ip.magic('rehashx')
27 27 # Practically ALL ipython development systems will have more than 10 aliases
28 28
29 yield (nt.assert_true, len(_ip.IP.alias_table) > 10)
30 for key, val in _ip.IP.alias_table.items():
29 yield (nt.assert_true, len(_ip.alias_table) > 10)
30 for key, val in _ip.alias_table.items():
31 31 # we must strip dots from alias names
32 32 nt.assert_true('.' not in key)
33 33
@@ -52,7 +52,7 b' def doctest_hist_r():'
52 52
53 53 XXX - This test is not recording the output correctly. Not sure why...
54 54
55 In [20]: 'hist' in _ip.IP.lsmagic()
55 In [20]: 'hist' in _ip.lsmagic()
56 56 Out[20]: True
57 57
58 58 In [6]: x=1
@@ -69,7 +69,7 b' def test_obj_del():'
69 69 test_dir = os.path.dirname(__file__)
70 70 del_file = os.path.join(test_dir,'obj_del.py')
71 71 ipython_cmd = find_cmd('ipython')
72 out = _ip.IP.getoutput('%s %s' % (ipython_cmd, del_file))
72 out = _ip.getoutput('%s %s' % (ipython_cmd, del_file))
73 73 nt.assert_equals(out,'obj_del.py: object A deleted')
74 74
75 75
@@ -124,7 +124,7 b' def doctest_refbug():'
124 124 """Very nasty problem with references held by multiple runs of a script.
125 125 See: https://bugs.launchpad.net/ipython/+bug/269966
126 126
127 In [1]: _ip.IP.clear_main_mod_cache()
127 In [1]: _ip.clear_main_mod_cache()
128 128
129 129 In [2]: run refbug
130 130
@@ -247,7 +247,7 b' class TestMagicRun(object):'
247 247 def test_prompts(self):
248 248 """Test that prompts correctly generate after %run"""
249 249 self.run_tmpfile()
250 p2 = str(_ip.IP.outputcache.prompt2).strip()
250 p2 = str(_ip.outputcache.prompt2).strip()
251 251 nt.assert_equals(p2[:3], '...')
252 252
253 253 def teardown(self):
@@ -268,7 +268,7 b' def test_paste():'
268 268 _ip.magic('paste '+flags)
269 269
270 270 # Inject fake clipboard hook but save original so we can restore it later
271 hooks = _ip.IP.hooks
271 hooks = _ip.hooks
272 272 user_ns = _ip.user_ns
273 273 original_clip = hooks.clipboard_get
274 274
@@ -305,8 +305,8 b' def test_paste():'
305 305
306 306 # Also test paste echoing, by temporarily faking the writer
307 307 w = StringIO()
308 writer = _ip.IP.write
309 _ip.IP.write = w.write
308 writer = _ip.write
309 _ip.write = w.write
310 310 code = """
311 311 a = 100
312 312 b = 200"""
@@ -314,7 +314,7 b' def test_paste():'
314 314 paste(code,'')
315 315 out = w.getvalue()
316 316 finally:
317 _ip.IP.write = writer
317 _ip.write = writer
318 318 yield (nt.assert_equal, user_ns['a'], 100)
319 319 yield (nt.assert_equal, user_ns['b'], 200)
320 320 yield (nt.assert_equal, out, code+"\n## -- End pasted text --\n")
@@ -270,7 +270,7 b' def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):'
270 270 if scheme is None:
271 271 ipinst = ipapi.get()
272 272 if ipinst is not None:
273 scheme = ipinst.IP.rc.colors
273 scheme = ipinst.colors
274 274 else:
275 275 scheme = DEFAULT_SCHEME
276 276
@@ -494,7 +494,7 b' class ListTB(TBTools):'
494 494 if have_filedata:
495 495 ipinst = ipapi.get()
496 496 if ipinst is not None:
497 ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0)
497 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
498 498 # vds:<<
499 499
500 500 return list
@@ -816,7 +816,7 b' class VerboseTB(TBTools):'
816 816 filepath = os.path.abspath(filepath)
817 817 ipinst = ipapi.get()
818 818 if ipinst is not None:
819 ipinst.IP.hooks.synchronize_with_editor(filepath, lnum, 0)
819 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
820 820 # vds: <<
821 821
822 822 # return all our info assembled as a single string
@@ -6,6 +6,9 b''
6 6 # the file COPYING, distributed as part of this software.
7 7 #*****************************************************************************
8 8
9 import sys
10 from IPython.core import release
11
9 12 __doc__ = """
10 13 IPython -- An enhanced Interactive Python
11 14 =========================================
@@ -504,6 +507,18 b' MAIN FEATURES'
504 507 >>> x = ,my_function /home/me # syntax error
505 508 """
506 509
510 interactive_usage_min = """\
511 An enhanced console for Python.
512 Some of its features are:
513 - Readline support if the readline library is present.
514 - Tab completion in the local namespace.
515 - Logging of input, see command-line options.
516 - System shell escape via ! , eg !ls.
517 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
518 - Keeps track of locally defined variables via %who, %whos.
519 - Show object information with a ? eg ?x or x? (use ?? for more info).
520 """
521
507 522 quick_reference = r"""
508 523 IPython -- An enhanced Interactive Python - Quick Reference Card
509 524 ================================================================
@@ -556,3 +571,18 b' or python names.'
556 571 The following magic functions are currently available:
557 572
558 573 """
574
575 quick_guide = """\
576 ? -> Introduction and overview of IPython's features.
577 %quickref -> Quick reference.
578 help -> Python's own help system.
579 object? -> Details about 'object'. ?object also works, ?? prints more."""
580
581 default_banner_parts = [
582 'Python %s' % (sys.version.split('\n')[0],),
583 'Type "copyright", "credits" or "license" for more information.\n',
584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
585 quick_guide
586 ]
587
588 default_banner = '\n'.join(default_banner_parts)
@@ -16,7 +16,8 b" __all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot',"
16 16 'gphelp']
17 17
18 18 import IPython.GnuplotRuntime as GRun
19 from IPython.utils.genutils import page,warn
19 from IPython.utils.genutils import warn
20 from IPython.core.page import page
20 21
21 22 # Set global names for interactive use
22 23 Gnuplot = GRun.Gnuplot
@@ -77,7 +77,7 b' def idoctest(ns=None,eraise=False):'
77 77 if ns is None:
78 78 ns = ip.user_ns
79 79
80 ip.IP.savehist()
80 ip.savehist()
81 81 try:
82 82 while True:
83 83 line = raw_input()
@@ -96,7 +96,7 b' def idoctest(ns=None,eraise=False):'
96 96 print "KeyboardInterrupt - Discarding input."
97 97 run_test = False
98 98
99 ip.IP.reloadhist()
99 ip.reloadhist()
100 100
101 101 if run_test:
102 102 # Extra blank line at the end to ensure that the final docstring has a
@@ -81,7 +81,7 b' def clear_f(self,arg):'
81 81 gc.collect()
82 82
83 83 # Activate the extension
84 ip.expose_magic("clear",clear_f)
84 ip.define_magic("clear",clear_f)
85 85 import ipy_completers
86 86 ipy_completers.quick_completer(
87 87 '%clear','in out shadow_nuke shadow_compress dhist')
@@ -3,6 +3,8 b''
3 3 """
4 4
5 5 from IPython.core import ipapi
6 from IPython.core.error import TryNext
7
6 8 ip = ipapi.get()
7 9
8 10 import os,sys
@@ -16,7 +18,7 b' def restore_env(self):'
16 18 os.environ[k] = os.environ.get(k,"") + v
17 19 for k,v in env['pre']:
18 20 os.environ[k] = v + os.environ.get(k,"")
19 raise ipapi.TryNext
21 raise TryNext
20 22
21 23 ip.set_hook('late_startup_hook', restore_env)
22 24
@@ -85,6 +87,6 b' def env_completer(self,event):'
85 87 """ Custom completer that lists all env vars """
86 88 return os.environ.keys()
87 89
88 ip.expose_magic('env', persist_env)
90 ip.define_magic('env', persist_env)
89 91 ip.set_hook('complete_command',env_completer, str_key = '%env')
90 92
@@ -9,6 +9,7 b' var = !ls'
9 9 """
10 10
11 11 from IPython.core import ipapi
12 from IPython.core.error import TryNext
12 13 from IPython.utils.genutils import *
13 14
14 15 ip = ipapi.get()
@@ -17,9 +18,6 b' import re'
17 18
18 19 def hnd_magic(line,mo):
19 20 """ Handle a = %mymagic blah blah """
20 #cmd = genutils.make_quoted_expr(mo.group('syscmd'))
21 #mag = 'ipmagic
22 #return "%s = %s"
23 21 var = mo.group('varname')
24 22 cmd = mo.group('cmd')
25 23 expr = make_quoted_expr(cmd)
@@ -27,9 +25,6 b' def hnd_magic(line,mo):'
27 25
28 26 def hnd_syscmd(line,mo):
29 27 """ Handle a = !ls """
30 #cmd = genutils.make_quoted_expr(mo.group('syscmd'))
31 #mag = 'ipmagic
32 #return "%s = %s"
33 28 var = mo.group('varname')
34 29 cmd = mo.group('cmd')
35 30 expr = make_quoted_expr(itpl("sc -l =$cmd"))
@@ -58,6 +53,6 b' def regex_prefilter_f(self,line):'
58 53 if mo:
59 54 return handler(line,mo)
60 55
61 raise ipapi.TryNext
56 raise TryNext
62 57
63 58 ip.set_hook('input_prefilter', regex_prefilter_f)
@@ -1612,10 +1612,10 b' class ihist(Table):'
1612 1612 def __iter__(self):
1613 1613 api = ipapi.get()
1614 1614 if self.raw:
1615 for line in api.IP.input_hist_raw:
1615 for line in api.input_hist_raw:
1616 1616 yield line.rstrip("\n")
1617 1617 else:
1618 for line in api.IP.input_hist:
1618 for line in api.input_hist:
1619 1619 yield line.rstrip("\n")
1620 1620
1621 1621
@@ -1644,7 +1644,7 b' class ialias(Table):'
1644 1644 def __iter__(self):
1645 1645 api = ipapi.get()
1646 1646
1647 for (name, (args, command)) in api.IP.alias_table.iteritems():
1647 for (name, (args, command)) in api.alias_table.iteritems():
1648 1648 yield Alias(name, args, command)
1649 1649
1650 1650
@@ -225,6 +225,7 b' reloader = ModuleReloader()'
225 225 # IPython connectivity
226 226 #------------------------------------------------------------------------------
227 227 from IPython.core import ipapi
228 from IPython.core.error import TryNext
228 229
229 230 ip = ipapi.get()
230 231
@@ -232,7 +233,7 b' autoreload_enabled = False'
232 233
233 234 def runcode_hook(self):
234 235 if not autoreload_enabled:
235 raise ipapi.TryNext
236 raise TryNext
236 237 try:
237 238 reloader.check()
238 239 except:
@@ -339,11 +340,11 b" def aimport_f(self, parameter_s=''):"
339 340 __import__(modname)
340 341 basename = modname.split('.')[0]
341 342 mod = sys.modules[basename]
342 ip.to_user_ns({basename: mod})
343 ip.push({basename: mod})
343 344
344 345 def init():
345 ip.expose_magic('autoreload', autoreload_f)
346 ip.expose_magic('aimport', aimport_f)
346 ip.define_magic('autoreload', autoreload_f)
347 ip.define_magic('aimport', aimport_f)
347 348 ip.set_hook('pre_runcode_hook', runcode_hook)
348 349
349 350 init()
@@ -8,6 +8,8 b" ip.set_hook('complete_command', svn_completer, str_key = 'svn')"
8 8
9 9 """
10 10 from IPython.core import ipapi
11 from IPython.core.error import TryNext
12
11 13 import glob,os,shlex,sys
12 14 import inspect
13 15 from time import time
@@ -169,7 +171,7 b' def vcs_completer(commands, event):'
169 171 if len(cmd_param) == 2 or 'help' in cmd_param:
170 172 return commands.split()
171 173
172 return ip.IP.Completer.file_matches(event.symbol)
174 return ip.Completer.file_matches(event.symbol)
173 175
174 176
175 177 pkg_cache = None
@@ -245,7 +247,7 b' def bzr_completer(self,event):'
245 247 return []
246 248 else:
247 249 # the rest are probably file names
248 return ip.IP.Completer.file_matches(event.symbol)
250 return ip.Completer.file_matches(event.symbol)
249 251
250 252 return bzr_commands()
251 253
@@ -329,7 +331,7 b' def cd_completer(self, event):'
329 331 if ' ' in d:
330 332 # we don't want to deal with any of that, complex code
331 333 # for this is elsewhere
332 raise ipapi.TryNext
334 raise TryNext
333 335 found.append( d )
334 336
335 337 if not found:
@@ -341,7 +343,7 b' def cd_completer(self, event):'
341 343 if bkmatches:
342 344 return bkmatches
343 345
344 raise ipapi.TryNext
346 raise TryNext
345 347
346 348
347 349 def single_dir_expand(matches):
@@ -6,6 +6,7 b' Contributions are *very* welcome.'
6 6 """
7 7
8 8 from IPython.core import ipapi
9 from IPython.core.error import TryNext
9 10 ip = ipapi.get()
10 11
11 12 from IPython.external.Itpl import itplns
@@ -29,7 +30,7 b' def install_editor(run_template, wait = False):'
29 30 cmd = itplns(run_template, locals())
30 31 print ">",cmd
31 32 if os.system(cmd) != 0:
32 raise ipapi.TryNext()
33 raise TryNext()
33 34 if wait:
34 35 raw_input("Press Enter when done editing:")
35 36
@@ -43,7 +43,7 b' def export(filename = None):'
43 43 varstomove.append(k)
44 44 lines.append('%s = %s' % (k,repr(v)))
45 45
46 lines.append('ip.to_user_ns("%s")' % (' '.join(varstomove)))
46 lines.append('ip.push("%s")' % (' '.join(varstomove)))
47 47
48 48 bkms = ip.db.get('bookmarks',{})
49 49
@@ -57,7 +57,7 b' def export(filename = None):'
57 57 lines.extend(['','# === Alias definitions ===',''])
58 58 for k,v in aliases.items():
59 59 try:
60 lines.append("ip.defalias('%s', %s)" % (k, repr(v[1])))
60 lines.append("ip.define_alias('%s', %s)" % (k, repr(v[1])))
61 61 except (AttributeError, TypeError):
62 62 pass
63 63
@@ -9,6 +9,7 b' to.'
9 9
10 10 from IPython.core import ipapi
11 11 ip = ipapi.get()
12 from IPython.core.iplib import InteractiveShell
12 13
13 14 import sys,textwrap,inspect
14 15
@@ -34,10 +35,10 b' class ExtUtil:'
34 35 act = []
35 36 for mname,m in sys.modules.items():
36 37 o = getattr(m, 'ip', None)
37 if isinstance(o, ipapi.IPApi):
38 if isinstance(o, InteractiveShell):
38 39 act.append((mname,m))
39 40 act.sort()
40 41 return act
41 42
42 43 extutil = ExtUtil()
43 ip.to_user_ns('extutil')
44 ip.push('extutil')
@@ -16,12 +16,13 b' Not to be confused with ipipe commands (ils etc.) that also start with i.'
16 16 """
17 17
18 18 from IPython.core import ipapi
19 from IPython.core.error import TryNext
19 20 ip = ipapi.get()
20 21
21 22 import shutil,os,shlex
22 23 from IPython.external import mglob
23 24 from IPython.external.path import path
24 from IPython.core.ipapi import UsageError
25 from IPython.core.error import UsageError
25 26 import IPython.utils.generics
26 27
27 28 def parse_args(args):
@@ -59,7 +60,7 b' def icp(ip,arg):'
59 60 else:
60 61 shutil.copy2(f,targetdir)
61 62 return fs
62 ip.defalias("icp",icp)
63 ip.define_alias("icp",icp)
63 64
64 65 def imv(ip,arg):
65 66 """ imv src tgt
@@ -73,7 +74,7 b' def imv(ip,arg):'
73 74 for f in fs:
74 75 shutil.move(f, target)
75 76 return fs
76 ip.defalias("imv",imv)
77 ip.define_alias("imv",imv)
77 78
78 79 def irm(ip,arg):
79 80 """ irm path[s]...
@@ -92,7 +93,7 b' def irm(ip,arg):'
92 93 else:
93 94 os.remove(p)
94 95
95 ip.defalias("irm",irm)
96 ip.define_alias("irm",irm)
96 97
97 98 def imkdir(ip,arg):
98 99 """ imkdir path
@@ -103,7 +104,7 b' def imkdir(ip,arg):'
103 104 targetdir = arg.split(None,1)[1]
104 105 distutils.dir_util.mkpath(targetdir,verbose =1)
105 106
106 ip.defalias("imkdir",imkdir)
107 ip.define_alias("imkdir",imkdir)
107 108
108 109 def igrep(ip,arg):
109 110 """ igrep PAT files...
@@ -129,7 +130,7 b' def igrep(ip,arg):'
129 130 print l.rstrip()
130 131 return res
131 132
132 ip.defalias("igrep",igrep)
133 ip.define_alias("igrep",igrep)
133 134
134 135 def collect(ip,arg):
135 136 """ collect foo/a.txt rec:bar=*.py
@@ -140,7 +141,7 b' def collect(ip,arg):'
140 141 Without args, try to open ~/_ipython/collect dir (in win32 at least).
141 142 """
142 143 from IPython.external.path import path
143 basedir = path(ip.options.ipythondir + '/collect')
144 basedir = path(ip.options.IPYTHONDIR + '/collect')
144 145 try:
145 146 fs = mglob.expand(arg.split(None,1)[1])
146 147 except IndexError:
@@ -159,7 +160,7 b' def collect(ip,arg):'
159 160 print f,"=>",trg
160 161 shutil.copy2(f,trg)
161 162
162 ip.defalias("collect",collect)
163 ip.define_alias("collect",collect)
163 164
164 165 def inote(ip,arg):
165 166 """ inote Hello world
@@ -169,15 +170,15 b' def inote(ip,arg):'
169 170 Without args, opens notes.txt for editing.
170 171 """
171 172 import time
172 fname = ip.options.ipythondir + '/notes.txt'
173 fname = ip.options.IPYTHONDIR + '/notes.txt'
173 174
174 175 try:
175 176 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
176 177 f= open(fname, 'a').write(entry)
177 178 except IndexError:
178 ip.IP.hooks.editor(fname)
179 ip.hooks.editor(fname)
179 180
180 ip.defalias("inote",inote)
181 ip.define_alias("inote",inote)
181 182
182 183 def pathobj_mangle(p):
183 184 return p.replace(' ', '__').replace('.','DOT')
@@ -229,7 +230,7 b' def complete_pathobj(obj, prev_completions):'
229 230 if res:
230 231 return res
231 232 # just return normal attributes of 'path' object if the dir is empty
232 raise ipapi.TryNext
233 raise TryNext
233 234
234 235 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
235 236
@@ -240,6 +241,6 b' def test_pathobj():'
240 241 rootdir = PathObj("/")
241 242 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
242 243 cwd = PathObj('.')
243 ip.to_user_ns("rootdir startmenu cwd")
244 ip.push("rootdir startmenu cwd")
244 245
245 246 #test_pathobj() No newline at end of file
@@ -28,7 +28,7 b' def global_f(self,cmdline):'
28 28 lines = ['%s [%s]\n%s' % (p[2].rjust(70),p[1],p[3].rstrip()) for p in parts]
29 29 print "\n".join(lines)
30 30
31 ip.expose_magic('global', global_f)
31 ip.define_magic('global', global_f)
32 32
33 33 def global_completer(self,event):
34 34 compl = [l.rstrip() for l in os.popen(global_bin + ' -c ' + event.symbol).readlines()]
@@ -10,6 +10,7 b' do the same in default completer.'
10 10
11 11 """
12 12 from IPython.core import ipapi
13 from IPython.core.error import TryNext
13 14 from IPython.utils import generics
14 15 from IPython.utils.genutils import dir2
15 16
@@ -59,7 +60,7 b' def attr_matches(self, text):'
59 60
60 61 try:
61 62 words = generics.complete_object(obj, words)
62 except ipapi.TryNext:
63 except TryNext:
63 64 pass
64 65 # Build match list to return
65 66 n = len(attr)
@@ -116,14 +116,14 b" def jot_obj(self, obj, name, comment=''):"
116 116 uname = 'jot/'+name+suffix
117 117
118 118 # which one works better?
119 #all = ip.IP.shadowhist.all()
120 all = ip.IP.shell.input_hist
119 #all = ip.shadowhist.all()
120 all = ip.shell.input_hist
121 121
122 122 # We may actually want to make snapshot of files that are run-ned.
123 123
124 124 # get the comment
125 125 try:
126 comment = ip.IP.magic_edit('-x').strip()
126 comment = ip.magic_edit('-x').strip()
127 127 except:
128 128 print "No comment is recorded."
129 129 comment = ''
@@ -307,5 +307,5 b" def magic_read(self, parameter_s=''):"
307 307 return read_variables(ip, toret)
308 308
309 309
310 ip.expose_magic('jot',magic_jot)
311 ip.expose_magic('read',magic_read)
310 ip.define_magic('jot',magic_jot)
311 ip.define_magic('read',magic_read)
@@ -16,7 +16,7 b' def pylaunchers():'
16 16 for f in fs:
17 17 l = PyLauncher(f)
18 18 n = os.path.splitext(f)[0]
19 ip.defalias(n, l)
19 ip.define_alias(n, l)
20 20 ip.magic('store '+n)
21 21
22 22
@@ -39,7 +39,7 b' def main():'
39 39 return
40 40
41 41 os.environ["PATH"] = os.environ["PATH"] + ";" + kitroot() + "\\bin;"
42 ip.to_user_ns("pylaunchers")
42 ip.push("pylaunchers")
43 43 cmds = ip.db.get('syscmdlist', None)
44 44 if cmds is None:
45 45 ip.magic('rehashx')
@@ -63,8 +63,8 b' def ipython_firstrun(ip):'
63 63
64 64 print "First run of ipykit - configuring"
65 65
66 ip.defalias('py',selflaunch)
67 ip.defalias('d','dir /w /og /on')
66 ip.define_alias('py',selflaunch)
67 ip.define_alias('d','dir /w /og /on')
68 68 ip.magic('store py')
69 69 ip.magic('store d')
70 70
@@ -43,7 +43,7 b" def magic_rehash(self, parameter_s = ''):"
43 43 # aliases since %rehash will probably clobber them
44 44 self.shell.init_auto_alias()
45 45
46 ip.expose_magic("rehash", magic_rehash)
46 ip.define_magic("rehash", magic_rehash)
47 47
48 48 # Exit
49 49 def magic_Quit(self, parameter_s=''):
@@ -51,7 +51,7 b" def magic_Quit(self, parameter_s=''):"
51 51
52 52 self.shell.ask_exit()
53 53
54 ip.expose_magic("Quit", magic_Quit)
54 ip.define_magic("Quit", magic_Quit)
55 55
56 56
57 57 # make it autocallable fn if you really need it
@@ -59,4 +59,4 b" def magic_p(self, parameter_s=''):"
59 59 """Just a short alias for Python's 'print'."""
60 60 exec 'print ' + parameter_s in self.shell.user_ns
61 61
62 ip.expose_magic("p", magic_p)
62 ip.define_magic("p", magic_p)
@@ -229,6 +229,6 b" def lookfor_modules_f(self, arg=''):"
229 229 else:
230 230 _lookfor_modules = arg.split()
231 231
232 ip.expose_magic('lookfor', lookfor_f)
233 ip.expose_magic('lookfor_modules', lookfor_modules_f)
232 ip.define_magic('lookfor', lookfor_f)
233 ip.define_magic('lookfor_modules', lookfor_modules_f)
234 234
@@ -25,9 +25,9 b" def p4_f(self, parameter_s=''):"
25 25 def p4d(fname):
26 26 return os.popen('p4 where ' + fname).read().split()[0]
27 27
28 ip.to_user_ns("p4d")
28 ip.push("p4d")
29 29
30 ip.expose_magic('p4', p4_f)
30 ip.define_magic('p4', p4_f)
31 31
32 32 p4_commands = """\
33 33 add admin annotate branch branches change changes changelist
@@ -17,6 +17,7 b' for numpy dtype objects, add the following to your ipy_user_conf.py::'
17 17 """
18 18
19 19 from IPython.core import ipapi
20 from IPython.core.error import TryNext
20 21 from IPython.utils.genutils import Term
21 22
22 23 from IPython.external import pretty
@@ -41,6 +41,6 b' def main():'
41 41 o.xmode = 'plain'
42 42
43 43 # Store the activity flag in the metadata bag from the running shell
44 ip.IP.meta.doctest_mode = True
44 ip.meta.doctest_mode = True
45 45
46 46 main()
@@ -8,6 +8,7 b' compatibility)'
8 8 """
9 9
10 10 from IPython.core import ipapi
11 from IPython.core.error import TryNext
11 12 import os,re,textwrap
12 13
13 14 # The import below effectively obsoletes your old-style ipythonrc[.ini],
@@ -69,10 +70,10 b' def main():'
69 70 o.banner = "IPython %s [on Py %s]\n" % (release.version,sys.version.split(None,1)[0])
70 71
71 72
72 ip.IP.default_option('cd','-q')
73 ip.IP.default_option('macro', '-r')
73 ip.default_option('cd','-q')
74 ip.default_option('macro', '-r')
74 75 # If you only rarely want to execute the things you %edit...
75 #ip.IP.default_option('edit','-x')
76 #ip.default_option('edit','-x')
76 77
77 78
78 79 o.prompts_pad_left="1"
@@ -108,11 +109,11 b' def main():'
108 109 cmd = noext
109 110
110 111 key = mapper(cmd)
111 if key not in ip.IP.alias_table:
112 if key not in ip.alias_table:
112 113 # Dots will be removed from alias names, since ipython
113 114 # assumes names with dots to be python code
114 115
115 ip.defalias(key.replace('.',''), cmd)
116 ip.define_alias(key.replace('.',''), cmd)
116 117
117 118 # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more
118 119 ip.load("IPython.external.mglob")
@@ -121,13 +122,13 b' def main():'
121 122 if sys.platform == 'win32':
122 123 if 'cygwin' in os.environ['PATH'].lower():
123 124 # use the colors of cygwin ls (recommended)
124 ip.defalias('d', 'ls -F --color=auto')
125 ip.define_alias('d', 'ls -F --color=auto')
125 126 else:
126 127 # get icp, imv, imkdir, igrep, irm,...
127 128 ip.load('ipy_fsops')
128 129
129 130 # and the next best thing to real 'ls -F'
130 ip.defalias('d','dir /w /og /on')
131 ip.define_alias('d','dir /w /og /on')
131 132
132 133 ip.set_hook('input_prefilter', slash_prefilter_f)
133 134 extend_shell_behavior(ip)
@@ -141,10 +142,10 b' class LastArgFinder:'
141 142 ip = ipapi.get()
142 143 if hist_idx is None:
143 144 return str(self)
144 return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
145 return ip.input_hist_raw[hist_idx].strip().split()[-1]
145 146 def __str__(self):
146 147 ip = ipapi.get()
147 for cmd in reversed(ip.IP.input_hist_raw):
148 for cmd in reversed(ip.input_hist_raw):
148 149 parts = cmd.strip().split()
149 150 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
150 151 continue
@@ -159,7 +160,7 b' def slash_prefilter_f(self,line):'
159 160 from IPython.utils import genutils
160 161 if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line):
161 162 return "_ip.system(" + genutils.make_quoted_expr(line)+")"
162 raise ipapi.TryNext
163 raise TryNext
163 164
164 165 # XXX You do not need to understand the next function!
165 166 # This should probably be moved out of profile
@@ -169,16 +170,16 b' def extend_shell_behavior(ip):'
169 170 # Instead of making signature a global variable tie it to IPSHELL.
170 171 # In future if it is required to distinguish between different
171 172 # shells we can assign a signature per shell basis
172 ip.IP.__sig__ = 0xa005
173 ip.__sig__ = 0xa005
173 174 # mark the IPSHELL with this signature
174 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
175 ip.user_ns['__builtins__'].__dict__['__sig__'] = ip.__sig__
175 176
176 177 from IPython.external.Itpl import ItplNS
177 178 from IPython.utils.genutils import shell
178 179 # utility to expand user variables via Itpl
179 180 # xxx do something sensible with depth?
180 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
181 str(ItplNS(cmd, ip.IP.user_ns, get_locals()))
181 ip.var_expand = lambda cmd, lvars=None, depth=2: \
182 str(ItplNS(cmd, ip.user_ns, get_locals()))
182 183
183 184 def get_locals():
184 185 """ Substituting a variable through Itpl deep inside the IPSHELL stack
@@ -194,7 +195,7 b' def extend_shell_behavior(ip):'
194 195 getlvars = lambda fno: sys._getframe(fno+1).f_locals
195 196 # trackback until we enter the IPSHELL
196 197 frame_no = 1
197 sig = ip.IP.__sig__
198 sig = ip.__sig__
198 199 fsig = ~sig
199 200 while fsig != sig :
200 201 try:
@@ -230,7 +231,7 b' def extend_shell_behavior(ip):'
230 231
231 232 # We must start with a clean buffer, in case this is run from an
232 233 # interactive IPython session (via a magic, for example).
233 ip.IP.resetbuffer()
234 ip.resetbuffer()
234 235 lines = lines.split('\n')
235 236 more = 0
236 237 command = ''
@@ -251,9 +252,9 b' def extend_shell_behavior(ip):'
251 252 command += line
252 253 if command or more:
253 254 # push to raw history, so hist line numbers stay in sync
254 ip.IP.input_hist_raw.append("# " + command + "\n")
255 ip.input_hist_raw.append("# " + command + "\n")
255 256
256 more = ip.IP.push(ip.IP.prefilter(command,more))
257 more = ip.push_line(ip.prefilter(command,more))
257 258 command = ''
258 259 # IPython's runsource returns None if there was an error
259 260 # compiling the code. This allows us to stop processing right
@@ -263,8 +264,8 b' def extend_shell_behavior(ip):'
263 264 # final newline in case the input didn't have it, so that the code
264 265 # actually does get executed
265 266 if more:
266 ip.IP.push('\n')
267 ip.push_line('\n')
267 268
268 ip.IP.runlines = _runlines
269 ip.runlines = _runlines
269 270
270 271 main()
@@ -18,13 +18,13 b' def call_pydb(self, args):'
18 18 argl = arg_split(args)
19 19 # print argl # dbg
20 20 if len(inspect.getargspec(pydb.runv)[0]) == 2:
21 pdb = debugger.Pdb(color_scheme=self.rc.colors)
22 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
21 pdb = debugger.Pdb(color_scheme=self.colors)
22 ip.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )()
23 23 else:
24 ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )()
24 ip.history_saving_wrapper( lambda : pydb.runv(argl) )()
25 25
26 26
27 ip.expose_magic("pydb",call_pydb)
27 ip.define_magic("pydb",call_pydb)
28 28
29 29
30 30
@@ -42,7 +42,7 b' class PyLauncher:'
42 42 """ Invoke selflanucher on the specified script
43 43
44 44 This is mostly useful for associating with scripts using::
45 _ip.defalias('foo',PyLauncher('foo_script.py'))
45 _ip.define_alias('foo',PyLauncher('foo_script.py'))
46 46
47 47 """
48 48 def __init__(self,script):
@@ -137,4 +137,4 b' def rehashdir_f(self,arg):'
137 137 os.chdir(savedir)
138 138 return created
139 139
140 ip.expose_magic("rehashdir",rehashdir_f)
140 ip.define_magic("rehashdir",rehashdir_f)
@@ -64,5 +64,5 b' def render(tmpl):'
64 64 toclip(res)
65 65 return res
66 66
67 ip.to_user_ns('render')
67 ip.push('render')
68 68 No newline at end of file
@@ -55,7 +55,7 b' def init():'
55 55 o.allow_new_attr (True )
56 56 o.verbose = 0
57 57
58 ip.IP.system = (sys.platform == 'win32' and new_ipsystem_win32 or
58 ip.system = (sys.platform == 'win32' and new_ipsystem_win32 or
59 59 new_ipsystem_posix)
60 60
61 61 init()
@@ -52,7 +52,8 b' Notes'
52 52 from enthought.traits import api as T
53 53
54 54 # IPython imports
55 from IPython.core.ipapi import TryNext, get as ipget
55 from IPython.core.error import TryNext
56 from IPython.core.ipapi import get as ipget
56 57 from IPython.utils.genutils import dir2
57 58 try:
58 59 set
@@ -68,6 +68,7 b' something. Instead of edit, use the vim magic. Thats it!'
68 68 """
69 69
70 70 from IPython.core import ipapi
71 from IPython.core.error import TryNext
71 72
72 73 import socket, select
73 74 import os, threading, subprocess
@@ -161,7 +162,7 b' def shutdown_server(self):'
161 162 if SERVER:
162 163 SERVER.stop()
163 164 SERVER.join(3)
164 raise ipapi.TryNext
165 raise TryNext
165 166
166 167 ip.set_hook('shutdown_hook', shutdown_server, 10)
167 168
@@ -235,5 +236,5 b' def vim(self, argstr):'
235 236 argstr = 'edit -x ' + argstr
236 237 ip.magic(argstr)
237 238
238 ip.expose_magic('vim', vim)
239 ip.define_magic('vim', vim)
239 240
@@ -23,7 +23,7 b' def which(fname):'
23 23 return
24 24
25 25 def which_alias(fname):
26 for al, tgt in ip.IP.alias_table.items():
26 for al, tgt in ip.alias_table.items():
27 27 if not (al == fname or fnmatch(al, fname)):
28 28 continue
29 29 if callable(tgt):
@@ -72,5 +72,5 b' def which_f(self, arg):'
72 72 for e in which(arg):
73 73 print e
74 74
75 ip.expose_magic("which",which_f)
75 ip.define_magic("which",which_f)
76 76
@@ -22,6 +22,7 b' For more details: https://bugs.launchpad.net/ipython/+bug/249036'
22 22 import os
23 23
24 24 from IPython.core import ipapi
25 from IPython.core.error import UsageError
25 26 import rpdb2
26 27
27 28 ip = ipapi.get()
@@ -58,7 +59,7 b' def wdb_f(self, arg):'
58 59
59 60 path = os.path.abspath(arg)
60 61 if not os.path.isfile(path):
61 raise ipapi.UsageError("%%wdb: file %s does not exist" % path)
62 raise UsageError("%%wdb: file %s does not exist" % path)
62 63 if not rpdb_started:
63 64 passwd = ip.db.get('winpdb_pass', None)
64 65 if passwd is None:
@@ -80,4 +81,4 b' def wdb_f(self, arg):'
80 81 ip.magic('%run ' + arg)
81 82
82 83
83 ip.expose_magic('wdb', wdb_f)
84 ip.define_magic('wdb', wdb_f)
@@ -40,4 +40,4 b' def workdir_f(ip,line):'
40 40 finally:
41 41 os.chdir(olddir)
42 42
43 ip.defalias("workdir",workdir_f)
43 ip.define_alias("workdir",workdir_f)
@@ -48,6 +48,7 b' import threading,Queue'
48 48 from IPython.utils import genutils
49 49
50 50 from IPython.core import ipapi
51 from IPython.core.error import TryNext
51 52
52 53 if os.name == 'nt':
53 54 def kill_process(pid):
@@ -123,12 +124,12 b' def jobctrl_prefilter_f(self,line):'
123 124 if line.startswith('&'):
124 125 pre,fn,rest = self.split_user_input(line[1:])
125 126
126 line = ip.IP.expand_aliases(fn,rest)
127 line = ip.expand_aliases(fn,rest)
127 128 if not _jobq:
128 129 return '_ip.startjob(%s)' % genutils.make_quoted_expr(line)
129 130 return '_ip.jobq(%s)' % genutils.make_quoted_expr(line)
130 131
131 raise ipapi.TryNext
132 raise TryNext
132 133
133 134 def jobq_output_hook(self):
134 135 if not _jobq:
@@ -235,8 +236,8 b' def install():'
235 236 ip.startjob = startjob
236 237 ip.set_hook('input_prefilter', jobctrl_prefilter_f)
237 238 ip.set_hook('shell_hook', jobctrl_shellcmd)
238 ip.expose_magic('kill',magic_kill)
239 ip.expose_magic('tasks',magic_tasks)
240 ip.expose_magic('jobqueue',jobqueue_f)
239 ip.define_magic('kill',magic_kill)
240 ip.define_magic('tasks',magic_tasks)
241 ip.define_magic('jobqueue',jobqueue_f)
241 242 ip.set_hook('pre_prompt_hook', jobq_output_hook)
242 243 install()
@@ -95,4 +95,4 b' def line_edit_complete_f(self,event):'
95 95
96 96 ip.set_hook('complete_command', line_edit_complete_f , str_key = '%led')
97 97
98 ip.expose_magic('led', line_edit_f) No newline at end of file
98 ip.define_magic('led', line_edit_f) No newline at end of file
@@ -6,7 +6,7 b' Stores variables, aliases etc. in PickleShare database.'
6 6 """
7 7
8 8 from IPython.core import ipapi
9 from IPython.core.ipapi import UsageError
9 from IPython.core.error import TryNext, UsageError
10 10 ip = ipapi.get()
11 11
12 12 import pickleshare
@@ -20,7 +20,7 b' def restore_aliases(self):'
20 20 for k,v in staliases.items():
21 21 #print "restore alias",k,v # dbg
22 22 #self.alias_table[k] = v
23 ip.defalias(k,v)
23 ip.define_alias(k,v)
24 24
25 25
26 26 def refresh_variables(ip):
@@ -47,7 +47,7 b' def restore_data(self):'
47 47 refresh_variables(ip)
48 48 restore_aliases(self)
49 49 restore_dhist(self)
50 raise ipapi.TryNext
50 raise TryNext
51 51
52 52 ip.set_hook('late_startup_hook', restore_data)
53 53
@@ -179,4 +179,4 b" def magic_store(self, parameter_s=''):"
179 179 self.db[ 'autorestore/' + args[0] ] = obj
180 180 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
181 181
182 ip.expose_magic('store',magic_store)
182 ip.define_magic('store',magic_store)
@@ -42,4 +42,4 b" def clip_f( self, parameter_s = '' ):"
42 42 print 'The following text was written to the clipboard'
43 43 print val
44 44
45 ip.expose_magic( "clip", clip_f )
45 ip.define_magic( "clip", clip_f )
@@ -222,7 +222,7 b' def mglob_f(self, arg):'
222 222 def init_ipython(ip):
223 223 """ register %mglob for IPython """
224 224 mglob_f.__doc__ = globsyntax
225 ip.expose_magic("mglob",mglob_f)
225 ip.define_magic("mglob",mglob_f)
226 226
227 227 # test()
228 228 if __name__ == "__main__":
@@ -28,7 +28,6 b' import re'
28 28 import __builtin__
29 29
30 30 from IPython.core.ipmaker import make_IPython
31 from IPython.core.ipapi import IPApi
32 31 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
33 32
34 33 from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap
@@ -112,7 +111,7 b' class PrefilterFrontEnd(LineFrontEndBase):'
112 111 self.ipython0.set_hook('show_in_pager',
113 112 lambda s, string: self.write("\n" + string))
114 113 self.ipython0.write = self.write
115 self._ip = _ip = IPApi(self.ipython0)
114 self._ip = _ip = self.ipython0
116 115 # Make sure the raw system call doesn't get called, as we don't
117 116 # have a stdin accessible.
118 117 self._ip.system = self.system_call
@@ -61,8 +61,8 b' def isolate_ipython0(func):'
61 61 if ip0 is None:
62 62 return func()
63 63 # We have a real ipython running...
64 user_ns = ip0.IP.user_ns
65 user_global_ns = ip0.IP.user_global_ns
64 user_ns = ip0.user_ns
65 user_global_ns = ip0.user_global_ns
66 66
67 67 # Previously the isolation was attempted with a deep copy of the user
68 68 # dicts, but we found cases where this didn't work correctly. I'm not
@@ -189,7 +189,7 b' class NonBlockingIPShell(object):'
189 189 ip = ipapi.get()
190 190 def bypass_magic(self, arg):
191 191 print '%this magic is currently disabled.'
192 ip.expose_magic('cpaste', bypass_magic)
192 ip.define_magic('cpaste', bypass_magic)
193 193
194 194 import __builtin__
195 195 __builtin__.raw_input = self._raw_input
@@ -492,9 +492,9 b' class NonBlockingIPShell(object):'
492 492 self._IP.showtraceback()
493 493 else:
494 494 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
495 self._iter_more = self._IP.push(line)
495 self._iter_more = self._IP.push_line(line)
496 496 if (self._IP.SyntaxTB.last_syntax_error and \
497 self._IP.rc.autoedit_syntax):
497 self._IP.autoedit_syntax):
498 498 self._IP.edit_syntax_error()
499 499 if self._iter_more:
500 500 self._prompt = str(self._IP.outputcache.prompt2).strip()
@@ -109,7 +109,7 b' class MyFrame(wx.Frame):'
109 109
110 110 def optionSave(self, name, value):
111 111 ip = get()
112 path = ip.IP.rc.ipythondir
112 path = ip.config.IPYTHONDIR
113 113 opt = open(path + '/options.conf','w')
114 114
115 115 try:
@@ -126,7 +126,7 b' class MyFrame(wx.Frame):'
126 126 def optionLoad(self):
127 127 try:
128 128 ip = get()
129 path = ip.IP.rc.ipythondir
129 path = ip.config.IPYTHONDIR
130 130 opt = open(path + '/options.conf','r')
131 131 lines = opt.readlines()
132 132 opt.close()
@@ -25,5 +25,5 b' to use the new IPython.core.ipapi module"""'
25 25
26 26 warn(msg, category=DeprecationWarning, stacklevel=1)
27 27
28 from IPython.core.ipapi import *
28 from IPython.core.ipapi import get, launch_new_instance
29 29
@@ -110,7 +110,7 b' class RemoteContextBase(object):'
110 110 def _findsource_ipython(self,f):
111 111 from IPython.core import ipapi
112 112 self.ip = ipapi.get()
113 buf = self.ip.IP.input_hist_raw[-1].splitlines()[1:]
113 buf = self.ip.input_hist_raw[-1].splitlines()[1:]
114 114 wsource = [l+'\n' for l in buf ]
115 115
116 116 return strip_whitespace(wsource)
@@ -29,7 +29,7 b' from IPython.external.Itpl import ItplNS'
29 29
30 30 from IPython.utils import coloransi
31 31 from IPython.core import release
32 from IPython.core.ipapi import TryNext
32 from IPython.core.error import TryNext
33 33 from IPython.utils.genutils import *
34 34 import IPython.utils.generics
35 35
@@ -314,7 +314,7 b' class InteractiveMultiEngineClient(object):'
314 314 from IPython.core import ipapi
315 315 self.ip = ipapi.get()
316 316 wsource = [l+'\n' for l in
317 self.ip.IP.input_hist_raw[-1].splitlines()[1:]]
317 self.ip.input_hist_raw[-1].splitlines()[1:]]
318 318 return strip_whitespace(wsource)
319 319
320 320 def __enter__(self):
@@ -39,7 +39,7 b' from IPython.kernel.fcutil import have_crypto'
39 39
40 40 # Create various ipython directories if they don't exist.
41 41 # This must be done before IPython.kernel.config is imported.
42 from IPython.core.iplib import user_setup
42 from IPython.core.oldusersetup import user_setup
43 43 if os.name == 'posix':
44 44 rc_suffix = ''
45 45 else:
@@ -41,7 +41,7 b' from IPython.kernel.fcutil import check_furl_file_security'
41 41
42 42 # Create various ipython directories if they don't exist.
43 43 # This must be done before IPython.kernel.config is imported.
44 from IPython.core.iplib import user_setup
44 from IPython.core.oldusersetup import user_setup
45 45 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
46 46 if os.name == 'posix':
47 47 rc_suffix = ''
@@ -36,7 +36,7 b' from IPython.kernel.engineservice import EngineService'
36 36
37 37 # Create various ipython directories if they don't exist.
38 38 # This must be done before IPython.kernel.config is imported.
39 from IPython.core.iplib import user_setup
39 from IPython.core.oldusersetup import user_setup
40 40 from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir
41 41 if os.name == 'posix':
42 42 rc_suffix = ''
@@ -4,7 +4,7 b''
4 4 import subprocess
5 5 import sys
6 6
7 from IPython.core.ipapi import TryNext
7 from IPython.core.error import TryNext
8 8
9 9
10 10 def win32_clipboard_get():
@@ -23,6 +23,6 b' this mode, there is no way to pass IPython any command-line options, as those'
23 23 are trapped first by Python itself.
24 24 """
25 25
26 import IPython.core.shell
26 import IPython.core.ipapi import launch_new_instance
27 27
28 IPython.core.shell.start().mainloop()
28 launch_new_instance()
@@ -105,7 +105,7 b' def _run_ns_sync(self,arg_s,runner=None):'
105 105 fname = arg_s
106 106
107 107 finder = py_file_finder(fname)
108 out = _ip.IP.magic_run_ori(arg_s,runner,finder)
108 out = _ip.magic_run_ori(arg_s,runner,finder)
109 109
110 110 # Simliarly, there is no test_globs when a test is NOT a doctest
111 111 if hasattr(_run_ns_sync,'test_globs'):
@@ -172,7 +172,7 b' def start_ipython():'
172 172 This is just a convenience function to replace the IPython system call
173 173 with one that is more doctest-friendly.
174 174 """
175 cmd = _ip.IP.var_expand(cmd,depth=1)
175 cmd = _ip.var_expand(cmd,depth=1)
176 176 sys.stdout.write(commands.getoutput(cmd))
177 177 sys.stdout.flush()
178 178
@@ -184,8 +184,7 b' def start_ipython():'
184 184 argv = default_argv()
185 185
186 186 # Start IPython instance. We customize it to start with minimal frills.
187 user_ns,global_ns = ipapi.make_user_namespaces(ipnsdict(),dict())
188 IPython.shell.IPShell(argv,user_ns,global_ns)
187 IPython.shell.IPShell(argv,ipnsdict(),global_ns)
189 188
190 189 # Deactivate the various python system hooks added by ipython for
191 190 # interactive convenience so we don't confuse the doctest system
@@ -204,16 +203,16 b' def start_ipython():'
204 203 _ip.system = xsys
205 204
206 205 # Also patch our %run function in.
207 im = new.instancemethod(_run_ns_sync,_ip.IP, _ip.IP.__class__)
208 _ip.IP.magic_run_ori = _ip.IP.magic_run
209 _ip.IP.magic_run = im
206 im = new.instancemethod(_run_ns_sync,_ip, _ip.__class__)
207 _ip.magic_run_ori = _ip.magic_run
208 _ip.magic_run = im
210 209
211 210 # XXX - For some very bizarre reason, the loading of %history by default is
212 211 # failing. This needs to be fixed later, but for now at least this ensures
213 212 # that tests that use %hist run to completion.
214 213 from IPython.core import history
215 214 history.init_ipython(_ip)
216 if not hasattr(_ip.IP,'magic_history'):
215 if not hasattr(_ip,'magic_history'):
217 216 raise RuntimeError("Can't load magics, aborting")
218 217
219 218
@@ -437,8 +436,8 b' class DocTestCase(doctests.DocTestCase):'
437 436 # for IPython examples *only*, we swap the globals with the ipython
438 437 # namespace, after updating it with the globals (which doctest
439 438 # fills with the necessary info from the module being tested).
440 _ip.IP.user_ns.update(self._dt_test.globs)
441 self._dt_test.globs = _ip.IP.user_ns
439 _ip.user_ns.update(self._dt_test.globs)
440 self._dt_test.globs = _ip.user_ns
442 441
443 442 super(DocTestCase, self).setUp()
444 443
@@ -539,7 +538,7 b' class IPDocTestParser(doctest.DocTestParser):'
539 538 # and turned into lines, so it looks to the parser like regular user
540 539 # input
541 540 for lnum,line in enumerate(source.strip().splitlines()):
542 newline(_ip.IP.prefilter(line,lnum>0))
541 newline(_ip.prefilter(line,lnum>0))
543 542 newline('') # ensure a closing newline, needed by doctest
544 543 #print "PYSRC:", '\n'.join(out) # dbg
545 544 return '\n'.join(out)
@@ -1,8 +1,8 b''
1 ''' 'Generic' functions for extending IPython.
1 """Generic functions for extending IPython.
2 2
3 3 See http://cheeseshop.python.org/pypi/simplegeneric.
4 4
5 Here is an example from genutils.py:
5 Here is an example from genutils.py::
6 6
7 7 def print_lsstring(arg):
8 8 "Prettier (non-repr-like) and more informative printer for LSString"
@@ -10,45 +10,34 b' Here is an example from genutils.py:'
10 10 print arg
11 11
12 12 print_lsstring = result_display.when_type(LSString)(print_lsstring)
13 """
13 14
14 (Yes, the nasty syntax is for python 2.3 compatibility. Your own extensions
15 can use the niftier decorator syntax introduced in Python 2.4).
16 '''
17
18 from IPython.core.ipapi import TryNext
15 from IPython.core.error import TryNext
19 16 from IPython.external.simplegeneric import generic
20 17
18 @generic
21 19 def result_display(result):
22 """ print the result of computation """
20 """Print the result of computation."""
23 21 raise TryNext
24 22
25 result_display = generic(result_display)
26
23 @generic
27 24 def inspect_object(obj):
28 """ Called when you do obj? """
25 """Called when you do obj?"""
29 26 raise TryNext
30 inspect_object = generic(inspect_object)
31 27
28 @generic
32 29 def complete_object(obj, prev_completions):
33 """ Custom completer dispatching for python objects
34
35 obj is the object itself.
36 prev_completions is the list of attributes discovered so far.
37
30 """Custom completer dispatching for python objects.
31
32 Parameters
33 ----------
34 obj : object
35 The object to complete.
36 prev_completions : list
37 List of attributes discovered so far.
38
38 39 This should return the list of attributes in obj. If you only wish to
39 add to the attributes already discovered normally, return
40 add to the attributes already discovered normally, return
40 41 own_attrs + prev_completions.
41 42 """
42
43 43 raise TryNext
44 complete_object = generic(complete_object)
45
46 #import os
47 #def my_demo_complete_object(obj, prev_completions):
48 # """ Demo completer that adds 'foobar' to the completions suggested
49 # for any object that has attribute (path), e.g. 'os'"""
50 # if hasattr(obj,'path'):
51 # return prev_completions + ['foobar']
52 # raise TryNext
53 #
54 #my_demo_complete_object = complete_object.when_type(type(os))(my_demo_complete_object)
@@ -15,11 +15,7 b' these things are also convenient when working at the command line.'
15 15 #****************************************************************************
16 16 # required modules from the Python standard library
17 17 import __main__
18 import commands
19 try:
20 import doctest
21 except ImportError:
22 pass
18
23 19 import os
24 20 import platform
25 21 import re
@@ -27,7 +23,6 b' import shlex'
27 23 import shutil
28 24 import subprocess
29 25 import sys
30 import tempfile
31 26 import time
32 27 import types
33 28 import warnings
@@ -46,14 +41,10 b' else:'
46 41
47 42 # Other IPython utilities
48 43 import IPython
49 from IPython.external.Itpl import Itpl,itpl,printpl
44 from IPython.external.Itpl import itpl,printpl
50 45 from IPython.utils import platutils
51 from IPython.utils import DPyGetOpt
52 46 from IPython.utils.generics import result_display
53 from IPython.core import ipapi
54 47 from IPython.external.path import path
55 if os.name == "nt":
56 from IPython.utils.winconsole import get_console_size
57 48
58 49 try:
59 50 set
@@ -642,215 +633,6 b' def unquote_ends(istr):'
642 633 return istr
643 634
644 635 #----------------------------------------------------------------------------
645 def process_cmdline(argv,names=[],defaults={},usage=''):
646 """ Process command-line options and arguments.
647
648 Arguments:
649
650 - argv: list of arguments, typically sys.argv.
651
652 - names: list of option names. See DPyGetOpt docs for details on options
653 syntax.
654
655 - defaults: dict of default values.
656
657 - usage: optional usage notice to print if a wrong argument is passed.
658
659 Return a dict of options and a list of free arguments."""
660
661 getopt = DPyGetOpt.DPyGetOpt()
662 getopt.setIgnoreCase(0)
663 getopt.parseConfiguration(names)
664
665 try:
666 getopt.processArguments(argv)
667 except DPyGetOpt.ArgumentError, exc:
668 print usage
669 warn('"%s"' % exc,level=4)
670
671 defaults.update(getopt.optionValues)
672 args = getopt.freeValues
673
674 return defaults,args
675
676 #----------------------------------------------------------------------------
677 def optstr2types(ostr):
678 """Convert a string of option names to a dict of type mappings.
679
680 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
681
682 This is used to get the types of all the options in a string formatted
683 with the conventions of DPyGetOpt. The 'type' None is used for options
684 which are strings (they need no further conversion). This function's main
685 use is to get a typemap for use with read_dict().
686 """
687
688 typeconv = {None:'',int:'',float:''}
689 typemap = {'s':None,'i':int,'f':float}
690 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
691
692 for w in ostr.split():
693 oname,alias,otype = opt_re.match(w).groups()
694 if otype == '' or alias == '!': # simple switches are integers too
695 otype = 'i'
696 typeconv[typemap[otype]] += oname + ' '
697 return typeconv
698
699 #----------------------------------------------------------------------------
700 def read_dict(filename,type_conv=None,**opt):
701 r"""Read a dictionary of key=value pairs from an input file, optionally
702 performing conversions on the resulting values.
703
704 read_dict(filename,type_conv,**opt) -> dict
705
706 Only one value per line is accepted, the format should be
707 # optional comments are ignored
708 key value\n
709
710 Args:
711
712 - type_conv: A dictionary specifying which keys need to be converted to
713 which types. By default all keys are read as strings. This dictionary
714 should have as its keys valid conversion functions for strings
715 (int,long,float,complex, or your own). The value for each key
716 (converter) should be a whitespace separated string containing the names
717 of all the entries in the file to be converted using that function. For
718 keys to be left alone, use None as the conversion function (only needed
719 with purge=1, see below).
720
721 - opt: dictionary with extra options as below (default in parens)
722
723 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
724 of the dictionary to be returned. If purge is going to be used, the
725 set of keys to be left as strings also has to be explicitly specified
726 using the (non-existent) conversion function None.
727
728 fs(None): field separator. This is the key/value separator to be used
729 when parsing the file. The None default means any whitespace [behavior
730 of string.split()].
731
732 strip(0): if 1, strip string values of leading/trailinig whitespace.
733
734 warn(1): warning level if requested keys are not found in file.
735 - 0: silently ignore.
736 - 1: inform but proceed.
737 - 2: raise KeyError exception.
738
739 no_empty(0): if 1, remove keys with whitespace strings as a value.
740
741 unique([]): list of keys (or space separated string) which can't be
742 repeated. If one such key is found in the file, each new instance
743 overwrites the previous one. For keys not listed here, the behavior is
744 to make a list of all appearances.
745
746 Example:
747
748 If the input file test.ini contains (we put it in a string to keep the test
749 self-contained):
750
751 >>> test_ini = '''\
752 ... i 3
753 ... x 4.5
754 ... y 5.5
755 ... s hi ho'''
756
757 Then we can use it as follows:
758 >>> type_conv={int:'i',float:'x',None:'s'}
759
760 >>> d = read_dict(test_ini)
761
762 >>> sorted(d.items())
763 [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')]
764
765 >>> d = read_dict(test_ini,type_conv)
766
767 >>> sorted(d.items())
768 [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')]
769
770 >>> d = read_dict(test_ini,type_conv,purge=True)
771
772 >>> sorted(d.items())
773 [('i', 3), ('s', 'hi ho'), ('x', 4.5)]
774 """
775
776 # starting config
777 opt.setdefault('purge',0)
778 opt.setdefault('fs',None) # field sep defaults to any whitespace
779 opt.setdefault('strip',0)
780 opt.setdefault('warn',1)
781 opt.setdefault('no_empty',0)
782 opt.setdefault('unique','')
783 if type(opt['unique']) in StringTypes:
784 unique_keys = qw(opt['unique'])
785 elif type(opt['unique']) in (types.TupleType,types.ListType):
786 unique_keys = opt['unique']
787 else:
788 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
789
790 dict = {}
791
792 # first read in table of values as strings
793 if '\n' in filename:
794 lines = filename.splitlines()
795 file = None
796 else:
797 file = open(filename,'r')
798 lines = file.readlines()
799 for line in lines:
800 line = line.strip()
801 if len(line) and line[0]=='#': continue
802 if len(line)>0:
803 lsplit = line.split(opt['fs'],1)
804 try:
805 key,val = lsplit
806 except ValueError:
807 key,val = lsplit[0],''
808 key = key.strip()
809 if opt['strip']: val = val.strip()
810 if val == "''" or val == '""': val = ''
811 if opt['no_empty'] and (val=='' or val.isspace()):
812 continue
813 # if a key is found more than once in the file, build a list
814 # unless it's in the 'unique' list. In that case, last found in file
815 # takes precedence. User beware.
816 try:
817 if dict[key] and key in unique_keys:
818 dict[key] = val
819 elif type(dict[key]) is types.ListType:
820 dict[key].append(val)
821 else:
822 dict[key] = [dict[key],val]
823 except KeyError:
824 dict[key] = val
825 # purge if requested
826 if opt['purge']:
827 accepted_keys = qwflat(type_conv.values())
828 for key in dict.keys():
829 if key in accepted_keys: continue
830 del(dict[key])
831 # now convert if requested
832 if type_conv==None: return dict
833 conversions = type_conv.keys()
834 try: conversions.remove(None)
835 except: pass
836 for convert in conversions:
837 for val in qw(type_conv[convert]):
838 try:
839 dict[val] = convert(dict[val])
840 except KeyError,e:
841 if opt['warn'] == 0:
842 pass
843 elif opt['warn'] == 1:
844 print >>sys.stderr, 'Warning: key',val,\
845 'not found in file',filename
846 elif opt['warn'] == 2:
847 raise KeyError,e
848 else:
849 raise ValueError,'Warning level must be 0,1 or 2'
850
851 return dict
852
853 #----------------------------------------------------------------------------
854 636 def flag_calls(func):
855 637 """Wrap a function to detect and flag when it gets called.
856 638
@@ -1368,16 +1150,6 b' def ask_yes_no(prompt,default=None):'
1368 1150 return answers[ans]
1369 1151
1370 1152 #----------------------------------------------------------------------------
1371 def marquee(txt='',width=78,mark='*'):
1372 """Return the input string centered in a 'marquee'."""
1373 if not txt:
1374 return (mark*width)[:width]
1375 nmark = (width-len(txt)-2)/len(mark)/2
1376 if nmark < 0: nmark =0
1377 marks = mark*nmark
1378 return '%s %s %s' % (marks,txt,marks)
1379
1380 #----------------------------------------------------------------------------
1381 1153 class EvalDict:
1382 1154 """
1383 1155 Emulate a dict which evaluates its contents in the caller's frame.
@@ -1530,267 +1302,6 b' def native_line_ends(filename,backup=1):'
1530 1302 except:
1531 1303 pass
1532 1304
1533 #----------------------------------------------------------------------------
1534 def get_pager_cmd(pager_cmd = None):
1535 """Return a pager command.
1536
1537 Makes some attempts at finding an OS-correct one."""
1538
1539 if os.name == 'posix':
1540 default_pager_cmd = 'less -r' # -r for color control sequences
1541 elif os.name in ['nt','dos']:
1542 default_pager_cmd = 'type'
1543
1544 if pager_cmd is None:
1545 try:
1546 pager_cmd = os.environ['PAGER']
1547 except:
1548 pager_cmd = default_pager_cmd
1549 return pager_cmd
1550
1551 #-----------------------------------------------------------------------------
1552 def get_pager_start(pager,start):
1553 """Return the string for paging files with an offset.
1554
1555 This is the '+N' argument which less and more (under Unix) accept.
1556 """
1557
1558 if pager in ['less','more']:
1559 if start:
1560 start_string = '+' + str(start)
1561 else:
1562 start_string = ''
1563 else:
1564 start_string = ''
1565 return start_string
1566
1567 #----------------------------------------------------------------------------
1568 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1569 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1570 import msvcrt
1571 def page_more():
1572 """ Smart pausing between pages
1573
1574 @return: True if need print more lines, False if quit
1575 """
1576 Term.cout.write('---Return to continue, q to quit--- ')
1577 ans = msvcrt.getch()
1578 if ans in ("q", "Q"):
1579 result = False
1580 else:
1581 result = True
1582 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1583 return result
1584 else:
1585 def page_more():
1586 ans = raw_input('---Return to continue, q to quit--- ')
1587 if ans.lower().startswith('q'):
1588 return False
1589 else:
1590 return True
1591
1592 esc_re = re.compile(r"(\x1b[^m]+m)")
1593
1594 def page_dumb(strng,start=0,screen_lines=25):
1595 """Very dumb 'pager' in Python, for when nothing else works.
1596
1597 Only moves forward, same interface as page(), except for pager_cmd and
1598 mode."""
1599
1600 out_ln = strng.splitlines()[start:]
1601 screens = chop(out_ln,screen_lines-1)
1602 if len(screens) == 1:
1603 print >>Term.cout, os.linesep.join(screens[0])
1604 else:
1605 last_escape = ""
1606 for scr in screens[0:-1]:
1607 hunk = os.linesep.join(scr)
1608 print >>Term.cout, last_escape + hunk
1609 if not page_more():
1610 return
1611 esc_list = esc_re.findall(hunk)
1612 if len(esc_list) > 0:
1613 last_escape = esc_list[-1]
1614 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1615
1616 #----------------------------------------------------------------------------
1617 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1618 """Print a string, piping through a pager after a certain length.
1619
1620 The screen_lines parameter specifies the number of *usable* lines of your
1621 terminal screen (total lines minus lines you need to reserve to show other
1622 information).
1623
1624 If you set screen_lines to a number <=0, page() will try to auto-determine
1625 your screen size and will only use up to (screen_size+screen_lines) for
1626 printing, paging after that. That is, if you want auto-detection but need
1627 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1628 auto-detection without any lines reserved simply use screen_lines = 0.
1629
1630 If a string won't fit in the allowed lines, it is sent through the
1631 specified pager command. If none given, look for PAGER in the environment,
1632 and ultimately default to less.
1633
1634 If no system pager works, the string is sent through a 'dumb pager'
1635 written in python, very simplistic.
1636 """
1637
1638 # Some routines may auto-compute start offsets incorrectly and pass a
1639 # negative value. Offset to 0 for robustness.
1640 start = max(0,start)
1641
1642 # first, try the hook
1643 ip = ipapi.get()
1644 if ip:
1645 try:
1646 ip.IP.hooks.show_in_pager(strng)
1647 return
1648 except ipapi.TryNext:
1649 pass
1650
1651 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1652 TERM = os.environ.get('TERM','dumb')
1653 if TERM in ['dumb','emacs'] and os.name != 'nt':
1654 print strng
1655 return
1656 # chop off the topmost part of the string we don't want to see
1657 str_lines = strng.split(os.linesep)[start:]
1658 str_toprint = os.linesep.join(str_lines)
1659 num_newlines = len(str_lines)
1660 len_str = len(str_toprint)
1661
1662 # Dumb heuristics to guesstimate number of on-screen lines the string
1663 # takes. Very basic, but good enough for docstrings in reasonable
1664 # terminals. If someone later feels like refining it, it's not hard.
1665 numlines = max(num_newlines,int(len_str/80)+1)
1666
1667 if os.name == "nt":
1668 screen_lines_def = get_console_size(defaulty=25)[1]
1669 else:
1670 screen_lines_def = 25 # default value if we can't auto-determine
1671
1672 # auto-determine screen size
1673 if screen_lines <= 0:
1674 if TERM=='xterm':
1675 use_curses = USE_CURSES
1676 else:
1677 # curses causes problems on many terminals other than xterm.
1678 use_curses = False
1679 if use_curses:
1680 # There is a bug in curses, where *sometimes* it fails to properly
1681 # initialize, and then after the endwin() call is made, the
1682 # terminal is left in an unusable state. Rather than trying to
1683 # check everytime for this (by requesting and comparing termios
1684 # flags each time), we just save the initial terminal state and
1685 # unconditionally reset it every time. It's cheaper than making
1686 # the checks.
1687 term_flags = termios.tcgetattr(sys.stdout)
1688 scr = curses.initscr()
1689 screen_lines_real,screen_cols = scr.getmaxyx()
1690 curses.endwin()
1691 # Restore terminal state in case endwin() didn't.
1692 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
1693 # Now we have what we needed: the screen size in rows/columns
1694 screen_lines += screen_lines_real
1695 #print '***Screen size:',screen_lines_real,'lines x',\
1696 #screen_cols,'columns.' # dbg
1697 else:
1698 screen_lines += screen_lines_def
1699
1700 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1701 if numlines <= screen_lines :
1702 #print '*** normal print' # dbg
1703 print >>Term.cout, str_toprint
1704 else:
1705 # Try to open pager and default to internal one if that fails.
1706 # All failure modes are tagged as 'retval=1', to match the return
1707 # value of a failed system command. If any intermediate attempt
1708 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1709 pager_cmd = get_pager_cmd(pager_cmd)
1710 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1711 if os.name == 'nt':
1712 if pager_cmd.startswith('type'):
1713 # The default WinXP 'type' command is failing on complex strings.
1714 retval = 1
1715 else:
1716 tmpname = tempfile.mktemp('.txt')
1717 tmpfile = file(tmpname,'wt')
1718 tmpfile.write(strng)
1719 tmpfile.close()
1720 cmd = "%s < %s" % (pager_cmd,tmpname)
1721 if os.system(cmd):
1722 retval = 1
1723 else:
1724 retval = None
1725 os.remove(tmpname)
1726 else:
1727 try:
1728 retval = None
1729 # if I use popen4, things hang. No idea why.
1730 #pager,shell_out = os.popen4(pager_cmd)
1731 pager = os.popen(pager_cmd,'w')
1732 pager.write(strng)
1733 pager.close()
1734 retval = pager.close() # success returns None
1735 except IOError,msg: # broken pipe when user quits
1736 if msg.args == (32,'Broken pipe'):
1737 retval = None
1738 else:
1739 retval = 1
1740 except OSError:
1741 # Other strange problems, sometimes seen in Win2k/cygwin
1742 retval = 1
1743 if retval is not None:
1744 page_dumb(strng,screen_lines=screen_lines)
1745
1746 #----------------------------------------------------------------------------
1747 def page_file(fname,start = 0, pager_cmd = None):
1748 """Page a file, using an optional pager command and starting line.
1749 """
1750
1751 pager_cmd = get_pager_cmd(pager_cmd)
1752 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1753
1754 try:
1755 if os.environ['TERM'] in ['emacs','dumb']:
1756 raise EnvironmentError
1757 xsys(pager_cmd + ' ' + fname)
1758 except:
1759 try:
1760 if start > 0:
1761 start -= 1
1762 page(open(fname).read(),start)
1763 except:
1764 print 'Unable to show file',`fname`
1765
1766
1767 #----------------------------------------------------------------------------
1768 def snip_print(str,width = 75,print_full = 0,header = ''):
1769 """Print a string snipping the midsection to fit in width.
1770
1771 print_full: mode control:
1772 - 0: only snip long strings
1773 - 1: send to page() directly.
1774 - 2: snip long strings and ask for full length viewing with page()
1775 Return 1 if snipping was necessary, 0 otherwise."""
1776
1777 if print_full == 1:
1778 page(header+str)
1779 return 0
1780
1781 print header,
1782 if len(str) < width:
1783 print str
1784 snip = 0
1785 else:
1786 whalf = int((width -5)/2)
1787 print str[:whalf] + ' <...> ' + str[-whalf:]
1788 snip = 1
1789 if snip and print_full == 2:
1790 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1791 page(str)
1792 return snip
1793
1794 1305 #****************************************************************************
1795 1306 # lists, dicts and structures
1796 1307
@@ -2259,6 +1770,8 b' def list_strings(arg):'
2259 1770 if isinstance(arg,basestring): return [arg]
2260 1771 else: return arg
2261 1772
1773
1774 #----------------------------------------------------------------------------
2262 1775 def marquee(txt='',width=78,mark='*'):
2263 1776 """Return the input string centered in a 'marquee'.
2264 1777
@@ -54,7 +54,6 b' def toggle_set_term_title(val):'
54 54
55 55 def set_term_title(title):
56 56 """Set terminal title using the necessary platform-dependent calls."""
57
58 57 if _platutils.ignore_termtitle:
59 58 return
60 59 _platutils.set_term_title(title)
@@ -17,17 +17,18 b' import os'
17 17
18 18 ignore_termtitle = True
19 19
20
20 21 def _dummy_op(*a, **b):
21 22 """ A no-op function """
22 23
23 24
24 25 def _set_term_title_xterm(title):
25 26 """ Change virtual terminal title in xterm-workalikes """
26
27 27 sys.stdout.write('\033]0;%s\007' % title)
28 28
29 TERM = os.environ.get('TERM','')
29 30
30 if os.environ.get('TERM','') == 'xterm':
31 if (TERM == 'xterm') or (TERM == 'xterm-color'):
31 32 set_term_title = _set_term_title_xterm
32 33 else:
33 34 set_term_title = _dummy_op
@@ -26,6 +26,7 b' try:'
26 26 """Set terminal title using ctypes to access the Win32 APIs."""
27 27 SetConsoleTitleW(title)
28 28
29
29 30 except ImportError:
30 31 def set_term_title(title):
31 32 """Set terminal title using the 'title' command."""
@@ -52,10 +52,15 b' Authors:'
52 52 import inspect
53 53 import sys
54 54 import types
55 from types import InstanceType, ClassType, FunctionType
55 from types import (
56 InstanceType, ClassType, FunctionType,
57 ListType, TupleType
58 )
56 59
57 60 ClassTypes = (ClassType, type)
58 61
62 SequenceTypes = (ListType, TupleType)
63
59 64 #-----------------------------------------------------------------------------
60 65 # Basic classes
61 66 #-----------------------------------------------------------------------------
@@ -858,4 +863,63 b' class CBool(Bool):'
858 863 try:
859 864 return bool(value)
860 865 except:
861 self.error(obj, value) No newline at end of file
866 self.error(obj, value)
867
868
869 class Enum(TraitletType):
870 """An enum that whose value must be in a given sequence."""
871
872 def __init__(self, values, default_value=None, allow_none=True, **metadata):
873 self.values = values
874 self._allow_none = allow_none
875 super(Enum, self).__init__(default_value, **metadata)
876
877 def validate(self, obj, value):
878 if value is None:
879 if self._allow_none:
880 return value
881
882 if value in self.values:
883 return value
884 self.error(obj, value)
885
886 def info(self):
887 """ Returns a description of the trait."""
888 result = 'any of ' + repr(self.values)
889 if self._allow_none:
890 return result + ' or None'
891 return result
892
893 class CaselessStrEnum(Enum):
894 """An enum of strings that are caseless in validate."""
895
896 def validate(self, obj, value):
897 if value is None:
898 if self._allow_none:
899 return value
900
901 if not isinstance(value, str):
902 self.error(obj, value)
903
904 for v in self.values:
905 if v.lower() == value.lower():
906 return v
907 self.error(obj, value)
908
909
910 class List(Instance):
911 """An instance of a Python list."""
912
913 def __init__(self, default_value=None, allow_none=True, **metadata):
914 """Create a list traitlet type from a list or tuple.
915
916 The default value is created by doing ``list(default_value)``,
917 which creates a copy of the ``default_value``.
918 """
919 if default_value is None:
920 args = ((),)
921 elif isinstance(default_value, SequenceTypes):
922 args = (default_value,)
923
924 super(List,self).__init__(klass=list, args=args,
925 allow_none=allow_none, **metadata)
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (792 lines changed) Show them Hide them
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now