Show More
The requested changes are too big and content was truncated. Show full diff
@@ -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 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 | ||
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,29 +1,42 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A backwards compatibility layer for IPython.Shell. |
|
4 | A backwards compatibility layer for IPython.Shell. | |
5 |
|
5 | |||
6 | Previously, IPython had an IPython.Shell module. IPython.Shell has been moved |
|
6 | Previously, IPython had an IPython.Shell module. IPython.Shell has been moved | |
7 | to IPython.core.shell and is being refactored. This new module is provided |
|
7 | to IPython.core.shell and is being refactored. This new module is provided | |
8 | for backwards compatability. We strongly encourage everyone to start using |
|
8 | for backwards compatability. We strongly encourage everyone to start using | |
9 | the new code in IPython.core.shell. |
|
9 | the new code in IPython.core.shell. | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | from warnings import warn |
|
19 | from warnings import warn | |
20 |
|
20 | |||
21 | msg = """ |
|
21 | msg = """ | |
22 | This module (IPython.Shell) has been moved to a new location |
|
22 | This module (IPython.Shell) is deprecated. The classes that were in this | |
23 | (IPython.core.shell) and is being refactored. Please update your code |
|
23 | module have been replaced by: | |
24 | to use the new IPython.core.shell module""" |
|
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 | warn(msg, category=DeprecationWarning, stacklevel=1) |
|
31 | warn(msg, category=DeprecationWarning, stacklevel=1) | |
27 |
|
32 | |||
28 |
from IPython.core. |
|
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,87 +1,64 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 | IPython is a set of tools for interactive and exploratory computing in Python. | |
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. |
|
|||
29 | """ |
|
7 | """ | |
30 |
|
8 | |||
31 | #***************************************************************************** |
|
9 | #----------------------------------------------------------------------------- | |
32 |
# |
|
10 | # Copyright (C) 2008-2009 The IPython Development Team | |
33 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
|||
34 | # |
|
11 | # | |
35 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
36 | # the file COPYING, distributed as part of this software. |
|
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 | import sys |
|
21 | import sys | |
|
22 | from IPython.core import release | |||
|
23 | ||||
|
24 | #----------------------------------------------------------------------------- | |||
|
25 | # Setup everything | |||
|
26 | #----------------------------------------------------------------------------- | |||
|
27 | ||||
41 |
|
28 | |||
42 | if sys.version[0:3] < '2.4': |
|
29 | if sys.version[0:3] < '2.4': | |
43 | raise ImportError('Python Version 2.4 or above is required for IPython.') |
|
30 | raise ImportError('Python Version 2.4 or above is required for IPython.') | |
44 |
|
31 | |||
|
32 | ||||
45 | # Make it easy to import extensions - they are always directly on pythonpath. |
|
33 | # Make it easy to import extensions - they are always directly on pythonpath. | |
46 | # Therefore, non-IPython modules can be added to extensions directory |
|
34 | # Therefore, non-IPython modules can be added to extensions directory | |
47 | import os |
|
|||
48 | sys.path.append(os.path.join(os.path.dirname(__file__), "extensions")) |
|
35 | sys.path.append(os.path.join(os.path.dirname(__file__), "extensions")) | |
49 |
|
36 | |||
50 | # Define what gets imported with a 'from IPython import *' |
|
37 | #----------------------------------------------------------------------------- | |
51 | __all__ = ['IPython.core.ipapi','utils.generics','utils.ipstruct', |
|
38 | # Setup the top level names | |
52 | 'core.release','core.shell'] |
|
39 | #----------------------------------------------------------------------------- | |
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,[]) |
|
|||
60 |
|
40 | |||
61 | from IPython.core import shell |
|
41 | # In some cases, these are causing circular imports. | |
62 | Shell = shell |
|
42 | from IPython.core.iplib import InteractiveShell | |
63 |
from IPython.core import |
|
43 | from IPython.core.embed import embed | |
64 |
from IPython.core import |
|
44 | from IPython.core.error import TryNext | |
65 |
|
45 | |||
66 | from IPython.lib import ( |
|
46 | from IPython.lib import ( | |
67 | enable_wx, disable_wx, |
|
47 | enable_wx, disable_wx, | |
68 | enable_gtk, disable_gtk, |
|
48 | enable_gtk, disable_gtk, | |
69 | enable_qt4, disable_qt4, |
|
49 | enable_qt4, disable_qt4, | |
70 | enable_tk, disable_tk, |
|
50 | enable_tk, disable_tk, | |
71 | set_inputhook, clear_inputhook, |
|
51 | set_inputhook, clear_inputhook, | |
72 | current_gui, spin, |
|
52 | current_gui, spin, | |
73 | appstart_qt4, appstart_wx, |
|
53 | appstart_qt4, appstart_wx, | |
74 | appstart_gtk, appstart_tk |
|
54 | appstart_gtk, appstart_tk | |
75 | ) |
|
55 | ) | |
76 |
|
56 | |||
77 | # Release data |
|
57 | # Release data | |
78 | from IPython.core import release # do it explicitly so pydoc can see it - pydoc bug |
|
58 | __author__ = '' | |
79 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ |
|
59 | for author, email in release.authors.values(): | |
80 | ( release.authors['Fernando'] + release.authors['Janko'] + \ |
|
60 | __author__ += author + ' <' + email + '>\n' | |
81 | release.authors['Nathan'] ) |
|
|||
82 | __license__ = release.license |
|
61 | __license__ = release.license | |
83 | __version__ = release.version |
|
62 | __version__ = release.version | |
84 | __revision__ = release.revision |
|
63 | __revision__ = release.revision | |
85 |
|
64 | |||
86 | # Namespace cleanup |
|
|||
87 | del name,glob,loc |
|
@@ -1,200 +1,203 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """A factory for creating configuration objects. |
|
3 | """A factory for creating configuration objects. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
7 | # Copyright (C) 2008-2009 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | import os |
|
17 | import os | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | from IPython.external import argparse |
|
20 | from IPython.external import argparse | |
21 | from IPython.utils.ipstruct import Struct |
|
21 | from IPython.utils.ipstruct import Struct | |
22 | from IPython.utils.genutils import filefind |
|
22 | from IPython.utils.genutils import filefind | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Code |
|
25 | # Code | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | class ConfigLoaderError(Exception): |
|
29 | class ConfigLoaderError(Exception): | |
30 | pass |
|
30 | pass | |
31 |
|
31 | |||
32 |
|
32 | |||
33 | class ConfigLoader(object): |
|
33 | class ConfigLoader(object): | |
34 | """A object for loading configurations from just about anywhere. |
|
34 | """A object for loading configurations from just about anywhere. | |
35 |
|
35 | |||
36 | The resulting configuration is packaged as a :class:`Struct`. |
|
36 | The resulting configuration is packaged as a :class:`Struct`. | |
37 |
|
37 | |||
38 | Notes |
|
38 | Notes | |
39 | ----- |
|
39 | ----- | |
40 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
40 | A :class:`ConfigLoader` does one thing: load a config from a source | |
41 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
41 | (file, command line arguments) and returns the data as a :class:`Struct`. | |
42 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
42 | There are lots of things that :class:`ConfigLoader` does not do. It does | |
43 | not implement complex logic for finding config files. It does not handle |
|
43 | not implement complex logic for finding config files. It does not handle | |
44 | default values or merge multiple configs. These things need to be |
|
44 | default values or merge multiple configs. These things need to be | |
45 | handled elsewhere. |
|
45 | handled elsewhere. | |
46 | """ |
|
46 | """ | |
47 |
|
47 | |||
48 | def __init__(self): |
|
48 | def __init__(self): | |
49 | """A base class for config loaders. |
|
49 | """A base class for config loaders. | |
50 |
|
50 | |||
51 | Examples |
|
51 | Examples | |
52 | -------- |
|
52 | -------- | |
53 |
|
53 | |||
54 | >>> cl = ConfigLoader() |
|
54 | >>> cl = ConfigLoader() | |
55 | >>> config = cl.load_config() |
|
55 | >>> config = cl.load_config() | |
56 | >>> config |
|
56 | >>> config | |
57 | {} |
|
57 | {} | |
58 | """ |
|
58 | """ | |
59 | self.clear() |
|
59 | self.clear() | |
60 |
|
60 | |||
61 | def clear(self): |
|
61 | def clear(self): | |
62 | self.config = Struct() |
|
62 | self.config = Struct() | |
63 |
|
63 | |||
64 | def load_config(self): |
|
64 | def load_config(self): | |
65 | """Load a config from somewhere, return a Struct. |
|
65 | """Load a config from somewhere, return a Struct. | |
66 |
|
66 | |||
67 | Usually, this will cause self.config to be set and then returned. |
|
67 | Usually, this will cause self.config to be set and then returned. | |
68 | """ |
|
68 | """ | |
69 | return self.config |
|
69 | return self.config | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | class FileConfigLoader(ConfigLoader): |
|
72 | class FileConfigLoader(ConfigLoader): | |
73 | """A base class for file based configurations. |
|
73 | """A base class for file based configurations. | |
74 |
|
74 | |||
75 | As we add more file based config loaders, the common logic should go |
|
75 | As we add more file based config loaders, the common logic should go | |
76 | here. |
|
76 | here. | |
77 | """ |
|
77 | """ | |
78 | pass |
|
78 | pass | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | class PyFileConfigLoader(FileConfigLoader): |
|
81 | class PyFileConfigLoader(FileConfigLoader): | |
82 | """A config loader for pure python files. |
|
82 | """A config loader for pure python files. | |
83 |
|
83 | |||
84 | This calls execfile on a plain python file and looks for attributes |
|
84 | This calls execfile on a plain python file and looks for attributes | |
85 | that are all caps. These attribute are added to the config Struct. |
|
85 | that are all caps. These attribute are added to the config Struct. | |
86 | """ |
|
86 | """ | |
87 |
|
87 | |||
88 | def __init__(self, filename, path=None): |
|
88 | def __init__(self, filename, path=None): | |
89 | """Build a config loader for a filename and path. |
|
89 | """Build a config loader for a filename and path. | |
90 |
|
90 | |||
91 | Parameters |
|
91 | Parameters | |
92 | ---------- |
|
92 | ---------- | |
93 | filename : str |
|
93 | filename : str | |
94 | The file name of the config file. |
|
94 | The file name of the config file. | |
95 | path : str, list, tuple |
|
95 | path : str, list, tuple | |
96 | The path to search for the config file on, or a sequence of |
|
96 | The path to search for the config file on, or a sequence of | |
97 | paths to try in order. |
|
97 | paths to try in order. | |
98 | """ |
|
98 | """ | |
99 | super(PyFileConfigLoader, self).__init__() |
|
99 | super(PyFileConfigLoader, self).__init__() | |
100 | self.filename = filename |
|
100 | self.filename = filename | |
101 | self.path = path |
|
101 | self.path = path | |
102 | self.full_filename = '' |
|
102 | self.full_filename = '' | |
103 | self.data = None |
|
103 | self.data = None | |
104 |
|
104 | |||
105 | def load_config(self): |
|
105 | def load_config(self): | |
106 | """Load the config from a file and return it as a Struct.""" |
|
106 | """Load the config from a file and return it as a Struct.""" | |
107 | self._find_file() |
|
107 | self._find_file() | |
108 | self._read_file_as_dict() |
|
108 | self._read_file_as_dict() | |
109 | self._convert_to_struct() |
|
109 | self._convert_to_struct() | |
110 | return self.config |
|
110 | return self.config | |
111 |
|
111 | |||
112 | def _find_file(self): |
|
112 | def _find_file(self): | |
113 | """Try to find the file by searching the paths.""" |
|
113 | """Try to find the file by searching the paths.""" | |
114 | self.full_filename = filefind(self.filename, self.path) |
|
114 | self.full_filename = filefind(self.filename, self.path) | |
115 |
|
115 | |||
116 | def _read_file_as_dict(self): |
|
116 | def _read_file_as_dict(self): | |
117 | self.data = {} |
|
117 | self.data = {} | |
118 | execfile(self.full_filename, self.data) |
|
118 | execfile(self.full_filename, self.data) | |
119 |
|
119 | |||
120 | def _convert_to_struct(self): |
|
120 | def _convert_to_struct(self): | |
121 | if self.data is None: |
|
121 | if self.data is None: | |
122 | ConfigLoaderError('self.data does not exist') |
|
122 | ConfigLoaderError('self.data does not exist') | |
123 | for k, v in self.data.iteritems(): |
|
123 | for k, v in self.data.iteritems(): | |
124 | if k == k.upper(): |
|
124 | if k == k.upper(): | |
125 | self.config[k] = v |
|
125 | self.config[k] = v | |
126 |
|
126 | |||
127 |
|
127 | |||
128 | class CommandLineConfigLoader(ConfigLoader): |
|
128 | class CommandLineConfigLoader(ConfigLoader): | |
129 | """A config loader for command line arguments. |
|
129 | """A config loader for command line arguments. | |
130 |
|
130 | |||
131 | As we add more command line based loaders, the common logic should go |
|
131 | As we add more command line based loaders, the common logic should go | |
132 | here. |
|
132 | here. | |
133 | """ |
|
133 | """ | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | class NoDefault(object): pass |
|
136 | class NoDefault(object): pass | |
137 | NoDefault = NoDefault() |
|
137 | NoDefault = NoDefault() | |
138 |
|
138 | |||
139 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
139 | class ArgParseConfigLoader(CommandLineConfigLoader): | |
140 |
|
140 | |||
141 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] |
|
141 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] | |
142 | arguments = () |
|
142 | arguments = () | |
143 |
|
143 | |||
144 | def __init__(self, *args, **kw): |
|
144 | def __init__(self, *args, **kw): | |
145 | """Create a config loader for use with argparse. |
|
145 | """Create a config loader for use with argparse. | |
146 |
|
146 | |||
147 | The args and kwargs arguments here are passed onto the constructor |
|
147 | The args and kwargs arguments here are passed onto the constructor | |
148 | of :class:`argparse.ArgumentParser`. |
|
148 | of :class:`argparse.ArgumentParser`. | |
149 | """ |
|
149 | """ | |
150 | super(CommandLineConfigLoader, self).__init__() |
|
150 | super(CommandLineConfigLoader, self).__init__() | |
151 | self.args = args |
|
151 | self.args = args | |
152 | self.kw = kw |
|
152 | self.kw = kw | |
153 |
|
153 | |||
154 | def load_config(self, args=None): |
|
154 | def load_config(self, args=None): | |
155 | """Parse command line arguments and return as a Struct.""" |
|
155 | """Parse command line arguments and return as a Struct.""" | |
156 | self._create_parser() |
|
156 | self._create_parser() | |
157 | self._parse_args(args) |
|
157 | self._parse_args(args) | |
158 | self._convert_to_struct() |
|
158 | self._convert_to_struct() | |
159 | return self.config |
|
159 | return self.config | |
160 |
|
160 | |||
161 | def _create_parser(self): |
|
161 | def _create_parser(self): | |
162 | self.parser = argparse.ArgumentParser(*self.args, **self.kw) |
|
162 | self.parser = argparse.ArgumentParser(*self.args, **self.kw) | |
163 | self._add_arguments() |
|
163 | self._add_arguments() | |
164 | self._add_other_arguments() |
|
164 | self._add_other_arguments() | |
165 |
|
165 | |||
166 | def _add_other_arguments(): |
|
166 | def _add_other_arguments(self): | |
167 | pass |
|
167 | pass | |
168 |
|
168 | |||
169 | def _add_arguments(self): |
|
169 | def _add_arguments(self): | |
170 | for argument in self.arguments: |
|
170 | for argument in self.arguments: | |
171 | if not argument[1].has_key('default'): |
|
171 | if not argument[1].has_key('default'): | |
172 | argument[1]['default'] = NoDefault |
|
172 | argument[1]['default'] = NoDefault | |
173 | self.parser.add_argument(*argument[0],**argument[1]) |
|
173 | self.parser.add_argument(*argument[0],**argument[1]) | |
174 |
|
174 | |||
175 | def _parse_args(self, args=None): |
|
175 | def _parse_args(self, args=None): | |
176 | """self.parser->self.parsed_data""" |
|
176 | """self.parser->self.parsed_data""" | |
177 | if args is None: |
|
177 | if args is None: | |
178 | self.parsed_data = self.parser.parse_args() |
|
178 | self.parsed_data = self.parser.parse_args() | |
179 | else: |
|
179 | else: | |
180 | self.parsed_data = self.parser.parse_args(args) |
|
180 | self.parsed_data = self.parser.parse_args(args) | |
181 |
|
181 | |||
182 | def _convert_to_struct(self): |
|
182 | def _convert_to_struct(self): | |
183 | """self.parsed_data->self.config""" |
|
183 | """self.parsed_data->self.config""" | |
184 | self.config = Struct() |
|
184 | self.config = Struct() | |
185 | for k, v in vars(self.parsed_data).items(): |
|
185 | for k, v in vars(self.parsed_data).items(): | |
186 | if v is not NoDefault: |
|
186 | if v is not NoDefault: | |
187 | setattr(self.config, k, v) |
|
187 | setattr(self.config, k, v) | |
188 |
|
188 | |||
189 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): |
|
189 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): | |
190 |
|
190 | |||
191 | def _add_other_arguments(self): |
|
191 | def _add_other_arguments(self): | |
192 |
self.parser.add_argument(' |
|
192 | self.parser.add_argument('-ipythondir',dest='IPYTHONDIR',type=str, | |
193 |
help=' |
|
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 | default=NoDefault) |
|
200 | default=NoDefault) | |
195 |
self.parser.add_argument('- |
|
201 | self.parser.add_argument('-config_file',dest='CONFIG_FILE',type=str, | |
196 | help='the string name of the ipython profile to be used', |
|
202 | help='Set the config file name to override default.', | |
197 | default=None) |
|
|||
198 | self.parser.add_argument('--debug',dest="DEBUG",action='store_true', |
|
|||
199 | help='debug the application startup process', |
|
|||
200 | default=NoDefault) |
|
203 | default=NoDefault) |
@@ -1,10 +1,7 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 | def test_import_configloader(): |
|
|||
5 | from IPython.config import configloader |
|
|||
6 |
|
||||
7 | def test_import_userconfig(): |
|
4 | def test_import_userconfig(): | |
8 | from IPython.config import userconfig |
|
5 | from IPython.config import userconfig | |
9 |
|
6 | |||
10 |
|
7 |
@@ -1,233 +1,241 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | An application for IPython |
|
4 | An application for IPython | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 |
|
10 | |||
11 | Notes |
|
11 | Notes | |
12 | ----- |
|
12 | ----- | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
17 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
19 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | import os |
|
26 | import os | |
27 | import sys |
|
27 | import sys | |
28 | import traceback |
|
28 | import traceback | |
29 |
|
29 | |||
30 | from copy import deepcopy |
|
30 | from copy import deepcopy | |
31 | from IPython.utils.ipstruct import Struct |
|
31 | from IPython.utils.ipstruct import Struct | |
32 | from IPython.utils.genutils import get_ipython_dir, filefind |
|
32 | from IPython.utils.genutils import get_ipython_dir, filefind | |
33 | from IPython.config.loader import ( |
|
33 | from IPython.config.loader import ( | |
34 | IPythonArgParseConfigLoader, |
|
34 | IPythonArgParseConfigLoader, | |
35 | PyFileConfigLoader |
|
35 | PyFileConfigLoader | |
36 | ) |
|
36 | ) | |
37 |
|
37 | |||
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Classes and functions |
|
39 | # Classes and functions | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | class ApplicationError(Exception): |
|
43 | class ApplicationError(Exception): | |
44 | pass |
|
44 | pass | |
45 |
|
45 | |||
46 |
|
46 | |||
47 | class Application(object): |
|
47 | class Application(object): | |
48 | """Load a config, construct an app and run it. |
|
48 | """Load a config, construct an app and run it. | |
49 | """ |
|
49 | """ | |
50 |
|
50 | |||
51 | config_file_name = 'ipython_config.py' |
|
51 | config_file_name = 'ipython_config.py' | |
52 | name = 'ipython' |
|
52 | name = 'ipython' | |
53 | debug = False |
|
53 | debug = False | |
54 |
|
54 | |||
55 | def __init__(self): |
|
55 | def __init__(self): | |
56 | pass |
|
56 | pass | |
57 |
|
57 | |||
58 | def start(self): |
|
58 | def start(self): | |
59 | """Start the application.""" |
|
59 | """Start the application.""" | |
60 | self.attempt(self.create_default_config) |
|
60 | self.attempt(self.create_default_config) | |
61 | self.attempt(self.pre_load_command_line_config) |
|
61 | self.attempt(self.pre_load_command_line_config) | |
62 |
self.attempt(self.load_command_line_config, action=' |
|
62 | self.attempt(self.load_command_line_config, action='abort') | |
63 | self.attempt(self.post_load_command_line_config) |
|
63 | self.attempt(self.post_load_command_line_config) | |
64 | self.attempt(self.find_ipythondir) |
|
64 | self.attempt(self.find_ipythondir) | |
65 | self.attempt(self.find_config_file_name) |
|
65 | self.attempt(self.find_config_file_name) | |
66 | self.attempt(self.find_config_file_paths) |
|
66 | self.attempt(self.find_config_file_paths) | |
67 | self.attempt(self.pre_load_file_config) |
|
67 | self.attempt(self.pre_load_file_config) | |
68 | self.attempt(self.load_file_config) |
|
68 | self.attempt(self.load_file_config) | |
69 | self.attempt(self.post_load_file_config) |
|
69 | self.attempt(self.post_load_file_config) | |
70 | self.attempt(self.merge_configs) |
|
70 | self.attempt(self.merge_configs) | |
71 | self.attempt(self.pre_construct) |
|
71 | self.attempt(self.pre_construct) | |
72 | self.attempt(self.construct) |
|
72 | self.attempt(self.construct) | |
73 | self.attempt(self.post_construct) |
|
73 | self.attempt(self.post_construct) | |
74 | self.attempt(self.start_app) |
|
74 | self.attempt(self.start_app) | |
75 |
|
75 | |||
76 | #------------------------------------------------------------------------- |
|
76 | #------------------------------------------------------------------------- | |
77 | # Various stages of Application creation |
|
77 | # Various stages of Application creation | |
78 | #------------------------------------------------------------------------- |
|
78 | #------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | def create_default_config(self): |
|
80 | def create_default_config(self): | |
81 | """Create defaults that can't be set elsewhere.""" |
|
81 | """Create defaults that can't be set elsewhere.""" | |
82 | self.default_config = Struct() |
|
82 | self.default_config = Struct() | |
83 | self.default_config.IPYTHONDIR = get_ipython_dir() |
|
83 | self.default_config.IPYTHONDIR = get_ipython_dir() | |
84 |
|
84 | |||
85 | def create_command_line_config(self): |
|
85 | def create_command_line_config(self): | |
86 | """Create and return a command line config loader.""" |
|
86 | """Create and return a command line config loader.""" | |
87 | return IPythonArgParseConfigLoader(description=self.name) |
|
87 | return IPythonArgParseConfigLoader(description=self.name) | |
88 |
|
88 | |||
89 | def pre_load_command_line_config(self): |
|
89 | def pre_load_command_line_config(self): | |
90 | """Do actions just before loading the command line config.""" |
|
90 | """Do actions just before loading the command line config.""" | |
91 | pass |
|
91 | pass | |
92 |
|
92 | |||
93 | def load_command_line_config(self): |
|
93 | def load_command_line_config(self): | |
94 | """Load the command line config. |
|
94 | """Load the command line config. | |
95 |
|
95 | |||
96 | This method also sets ``self.debug``. |
|
96 | This method also sets ``self.debug``. | |
97 | """ |
|
97 | """ | |
98 |
|
98 | |||
99 | loader = self.create_command_line_config() |
|
99 | loader = self.create_command_line_config() | |
100 | self.command_line_config = loader.load_config() |
|
100 | self.command_line_config = loader.load_config() | |
101 | try: |
|
101 | try: | |
102 | self.debug = self.command_line_config.DEBUG |
|
102 | self.debug = self.command_line_config.DEBUG | |
103 | except AttributeError: |
|
103 | except AttributeError: | |
104 | pass # use class default |
|
104 | pass # use class default | |
105 | self.log("Default config loaded:", self.default_config) |
|
105 | self.log("Default config loaded:", self.default_config) | |
106 | self.log("Command line config loaded:", self.command_line_config) |
|
106 | self.log("Command line config loaded:", self.command_line_config) | |
107 |
|
107 | |||
108 | def post_load_command_line_config(self): |
|
108 | def post_load_command_line_config(self): | |
109 | """Do actions just after loading the command line config.""" |
|
109 | """Do actions just after loading the command line config.""" | |
110 | pass |
|
110 | pass | |
111 |
|
111 | |||
112 | def find_ipythondir(self): |
|
112 | def find_ipythondir(self): | |
113 | """Set the IPython directory. |
|
113 | """Set the IPython directory. | |
114 |
|
114 | |||
115 | This sets ``self.ipythondir``, but the actual value that is passed |
|
115 | This sets ``self.ipythondir``, but the actual value that is passed | |
116 | to the application is kept in either ``self.default_config`` or |
|
116 | to the application is kept in either ``self.default_config`` or | |
117 | ``self.command_line_config``. This also added ``self.ipythondir`` to |
|
117 | ``self.command_line_config``. This also added ``self.ipythondir`` to | |
118 | ``sys.path`` so config files there can be references by other config |
|
118 | ``sys.path`` so config files there can be references by other config | |
119 | files. |
|
119 | files. | |
120 | """ |
|
120 | """ | |
121 |
|
121 | |||
122 | try: |
|
122 | try: | |
123 | self.ipythondir = self.command_line_config.IPYTHONDIR |
|
123 | self.ipythondir = self.command_line_config.IPYTHONDIR | |
124 | except AttributeError: |
|
124 | except AttributeError: | |
125 | self.ipythondir = self.default_config.IPYTHONDIR |
|
125 | self.ipythondir = self.default_config.IPYTHONDIR | |
126 | sys.path.append(os.path.abspath(self.ipythondir)) |
|
126 | sys.path.append(os.path.abspath(self.ipythondir)) | |
127 | if not os.path.isdir(self.ipythondir): |
|
127 | if not os.path.isdir(self.ipythondir): | |
128 | os.makedirs(self.ipythondir, mode = 0777) |
|
128 | os.makedirs(self.ipythondir, mode = 0777) | |
129 | self.log("IPYTHONDIR set to: %s" % self.ipythondir) |
|
129 | self.log("IPYTHONDIR set to: %s" % self.ipythondir) | |
130 |
|
130 | |||
131 | def find_config_file_name(self): |
|
131 | def find_config_file_name(self): | |
132 | """Find the config file name for this application. |
|
132 | """Find the config file name for this application. | |
133 |
|
133 | |||
134 | If a profile has been set at the command line, this will resolve |
|
134 | If a profile has been set at the command line, this will resolve | |
135 | it. The search paths for the config file are set in |
|
135 | it. The search paths for the config file are set in | |
136 | :meth:`find_config_file_paths` and then passed to the config file |
|
136 | :meth:`find_config_file_paths` and then passed to the config file | |
137 | loader where they are resolved to an absolute path. |
|
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: |
|
140 | try: | |
141 |
self. |
|
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 | name_parts = self.config_file_name.split('.') |
|
147 | name_parts = self.config_file_name.split('.') | |
143 | name_parts.insert(1, '_' + self.profile_name + '.') |
|
148 | name_parts.insert(1, '_' + self.profile_name + '.') | |
144 | self.config_file_name = ''.join(name_parts) |
|
149 | self.config_file_name = ''.join(name_parts) | |
|
150 | except AttributeError: | |||
|
151 | pass | |||
145 |
|
152 | |||
146 | def find_config_file_paths(self): |
|
153 | def find_config_file_paths(self): | |
147 | """Set the search paths for resolving the config file.""" |
|
154 | """Set the search paths for resolving the config file.""" | |
148 | self.config_file_paths = (os.getcwd(), self.ipythondir) |
|
155 | self.config_file_paths = (os.getcwd(), self.ipythondir) | |
149 |
|
156 | |||
150 | def pre_load_file_config(self): |
|
157 | def pre_load_file_config(self): | |
151 | """Do actions before the config file is loaded.""" |
|
158 | """Do actions before the config file is loaded.""" | |
152 | pass |
|
159 | pass | |
153 |
|
160 | |||
154 | def load_file_config(self): |
|
161 | def load_file_config(self): | |
155 | """Load the config file. |
|
162 | """Load the config file. | |
156 |
|
163 | |||
157 | This tries to load the config file from disk. If successful, the |
|
164 | This tries to load the config file from disk. If successful, the | |
158 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
165 | ``CONFIG_FILE`` config variable is set to the resolved config file | |
159 | location. If not successful, an empty config is used. |
|
166 | location. If not successful, an empty config is used. | |
160 | """ |
|
167 | """ | |
161 | loader = PyFileConfigLoader(self.config_file_name, |
|
168 | loader = PyFileConfigLoader(self.config_file_name, | |
162 | self.config_file_paths) |
|
169 | self.config_file_paths) | |
163 | try: |
|
170 | try: | |
164 | self.file_config = loader.load_config() |
|
171 | self.file_config = loader.load_config() | |
165 | self.file_config.CONFIG_FILE = loader.full_filename |
|
172 | self.file_config.CONFIG_FILE = loader.full_filename | |
166 | except IOError: |
|
173 | except IOError: | |
167 | self.log("Config file not found, skipping: %s" % \ |
|
174 | self.log("Config file not found, skipping: %s" % \ | |
168 | self.config_file_name) |
|
175 | self.config_file_name) | |
169 | self.file_config = Struct() |
|
176 | self.file_config = Struct() | |
170 | else: |
|
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 | def post_load_file_config(self): |
|
181 | def post_load_file_config(self): | |
174 | """Do actions after the config file is loaded.""" |
|
182 | """Do actions after the config file is loaded.""" | |
175 | pass |
|
183 | pass | |
176 |
|
184 | |||
177 | def merge_configs(self): |
|
185 | def merge_configs(self): | |
178 | """Merge the default, command line and file config objects.""" |
|
186 | """Merge the default, command line and file config objects.""" | |
179 | config = Struct() |
|
187 | config = Struct() | |
180 | config.update(self.default_config) |
|
188 | config.update(self.default_config) | |
181 | config.update(self.command_line_config) |
|
|||
182 | config.update(self.file_config) |
|
189 | config.update(self.file_config) | |
|
190 | config.update(self.command_line_config) | |||
183 | self.master_config = config |
|
191 | self.master_config = config | |
184 | self.log("Master config created:", self.master_config) |
|
192 | self.log("Master config created:", self.master_config) | |
185 |
|
193 | |||
186 | def pre_construct(self): |
|
194 | def pre_construct(self): | |
187 | """Do actions after the config has been built, but before construct.""" |
|
195 | """Do actions after the config has been built, but before construct.""" | |
188 | pass |
|
196 | pass | |
189 |
|
197 | |||
190 | def construct(self): |
|
198 | def construct(self): | |
191 | """Construct the main components that make up this app.""" |
|
199 | """Construct the main components that make up this app.""" | |
192 | self.log("Constructing components for application...") |
|
200 | self.log("Constructing components for application...") | |
193 |
|
201 | |||
194 | def post_construct(self): |
|
202 | def post_construct(self): | |
195 | """Do actions after construct, but before starting the app.""" |
|
203 | """Do actions after construct, but before starting the app.""" | |
196 | pass |
|
204 | pass | |
197 |
|
205 | |||
198 | def start_app(self): |
|
206 | def start_app(self): | |
199 | """Actually start the app.""" |
|
207 | """Actually start the app.""" | |
200 | self.log("Starting application...") |
|
208 | self.log("Starting application...") | |
201 |
|
209 | |||
202 | #------------------------------------------------------------------------- |
|
210 | #------------------------------------------------------------------------- | |
203 | # Utility methods |
|
211 | # Utility methods | |
204 | #------------------------------------------------------------------------- |
|
212 | #------------------------------------------------------------------------- | |
205 |
|
213 | |||
206 | def abort(self): |
|
214 | def abort(self): | |
207 | """Abort the starting of the application.""" |
|
215 | """Abort the starting of the application.""" | |
208 | print "Aborting application: ", self.name |
|
216 | print "Aborting application: ", self.name | |
209 | sys.exit(1) |
|
217 | sys.exit(1) | |
210 |
|
218 | |||
211 | def exit(self): |
|
219 | def exit(self): | |
212 | print "Exiting application: ", self.name |
|
220 | print "Exiting application: ", self.name | |
213 | sys.exit(1) |
|
221 | sys.exit(1) | |
214 |
|
222 | |||
215 | def attempt(self, func, action='abort'): |
|
223 | def attempt(self, func, action='abort'): | |
216 | try: |
|
224 | try: | |
217 | func() |
|
225 | func() | |
218 | except: |
|
226 | except: | |
219 | if action == 'abort': |
|
227 | if action == 'abort': | |
220 | self.print_traceback() |
|
228 | self.print_traceback() | |
221 | self.abort() |
|
229 | self.abort() | |
222 | elif action == 'exit': |
|
230 | elif action == 'exit': | |
223 | self.exit() |
|
231 | self.exit() | |
224 |
|
232 | |||
225 | def print_traceback(self): |
|
233 | def print_traceback(self): | |
226 | print "Error in appliction startup: ", self.name |
|
234 | print "Error in appliction startup: ", self.name | |
227 |
|
235 | |||
228 | traceback.print_exc() |
|
236 | traceback.print_exc() | |
229 |
|
237 | |||
230 | def log(self, *args): |
|
238 | def log(self, *args): | |
231 | if self.debug: |
|
239 | if self.debug: | |
232 | for arg in args: |
|
240 | for arg in args: | |
233 | print "[%s] %s" % (self.name, arg) No newline at end of file |
|
241 | print "[%s] %s" % (self.name, arg) |
@@ -1,639 +1,640 b'' | |||||
1 | """Word completion for IPython. |
|
1 | """Word completion for IPython. | |
2 |
|
2 | |||
3 | This module is a fork of the rlcompleter module in the Python standard |
|
3 | This module is a fork of the rlcompleter module in the Python standard | |
4 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
5 | upstream and were accepted as of Python 2.3, but we need a lot more | |
6 | functionality specific to IPython, so this module will continue to live as an |
|
6 | functionality specific to IPython, so this module will continue to live as an | |
7 | IPython-specific utility. |
|
7 | IPython-specific utility. | |
8 |
|
8 | |||
9 | Original rlcompleter documentation: |
|
9 | Original rlcompleter documentation: | |
10 |
|
10 | |||
11 | This requires the latest extension to the readline module (the |
|
11 | This requires the latest extension to the readline module (the | |
12 | completes keywords, built-ins and globals in __main__; when completing |
|
12 | completes keywords, built-ins and globals in __main__; when completing | |
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |
14 | completes its attributes. |
|
14 | completes its attributes. | |
15 |
|
15 | |||
16 | It's very cool to do "import string" type "string.", hit the |
|
16 | It's very cool to do "import string" type "string.", hit the | |
17 | completion key (twice), and see the list of names defined by the |
|
17 | completion key (twice), and see the list of names defined by the | |
18 | string module! |
|
18 | string module! | |
19 |
|
19 | |||
20 | Tip: to use the tab key as the completion key, call |
|
20 | Tip: to use the tab key as the completion key, call | |
21 |
|
21 | |||
22 | readline.parse_and_bind("tab: complete") |
|
22 | readline.parse_and_bind("tab: complete") | |
23 |
|
23 | |||
24 | Notes: |
|
24 | Notes: | |
25 |
|
25 | |||
26 | - Exceptions raised by the completer function are *ignored* (and |
|
26 | - Exceptions raised by the completer function are *ignored* (and | |
27 | generally cause the completion to fail). This is a feature -- since |
|
27 | generally cause the completion to fail). This is a feature -- since | |
28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
28 | readline sets the tty device in raw (or cbreak) mode, printing a | |
29 | traceback wouldn't work well without some complicated hoopla to save, |
|
29 | traceback wouldn't work well without some complicated hoopla to save, | |
30 | reset and restore the tty state. |
|
30 | reset and restore the tty state. | |
31 |
|
31 | |||
32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
32 | - The evaluation of the NAME.NAME... form may cause arbitrary | |
33 | application defined code to be executed if an object with a |
|
33 | application defined code to be executed if an object with a | |
34 | __getattr__ hook is found. Since it is the responsibility of the |
|
34 | __getattr__ hook is found. Since it is the responsibility of the | |
35 | application (or the user) to enable this feature, I consider this an |
|
35 | application (or the user) to enable this feature, I consider this an | |
36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
36 | acceptable risk. More complicated expressions (e.g. function calls or | |
37 | indexing operations) are *not* evaluated. |
|
37 | indexing operations) are *not* evaluated. | |
38 |
|
38 | |||
39 | - GNU readline is also used by the built-in functions input() and |
|
39 | - GNU readline is also used by the built-in functions input() and | |
40 | raw_input(), and thus these also benefit/suffer from the completer |
|
40 | raw_input(), and thus these also benefit/suffer from the completer | |
41 | features. Clearly an interactive application can benefit by |
|
41 | features. Clearly an interactive application can benefit by | |
42 | specifying its own completer function and using raw_input() for all |
|
42 | specifying its own completer function and using raw_input() for all | |
43 | its input. |
|
43 | its input. | |
44 |
|
44 | |||
45 | - When the original stdin is not a tty device, GNU readline is never |
|
45 | - When the original stdin is not a tty device, GNU readline is never | |
46 | used, and this module (and the readline module) are silently inactive. |
|
46 | used, and this module (and the readline module) are silently inactive. | |
47 |
|
47 | |||
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | #***************************************************************************** |
|
50 | #***************************************************************************** | |
51 | # |
|
51 | # | |
52 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
52 | # Since this file is essentially a minimally modified copy of the rlcompleter | |
53 | # module which is part of the standard Python distribution, I assume that the |
|
53 | # module which is part of the standard Python distribution, I assume that the | |
54 | # proper procedure is to maintain its copyright as belonging to the Python |
|
54 | # proper procedure is to maintain its copyright as belonging to the Python | |
55 | # Software Foundation (in addition to my own, for all new code). |
|
55 | # Software Foundation (in addition to my own, for all new code). | |
56 | # |
|
56 | # | |
57 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
57 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
58 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
58 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
59 | # |
|
59 | # | |
60 | # Distributed under the terms of the BSD License. The full license is in |
|
60 | # Distributed under the terms of the BSD License. The full license is in | |
61 | # the file COPYING, distributed as part of this software. |
|
61 | # the file COPYING, distributed as part of this software. | |
62 | # |
|
62 | # | |
63 | #***************************************************************************** |
|
63 | #***************************************************************************** | |
64 |
|
64 | |||
65 | import __builtin__ |
|
65 | import __builtin__ | |
66 | import __main__ |
|
66 | import __main__ | |
67 | import glob |
|
67 | import glob | |
68 | import keyword |
|
68 | import keyword | |
69 | import os |
|
69 | import os | |
70 | import re |
|
70 | import re | |
71 | import shlex |
|
71 | import shlex | |
72 | import sys |
|
72 | import sys | |
73 | import IPython.utils.rlineimpl as readline |
|
|||
74 | import itertools |
|
73 | import itertools | |
|
74 | import types | |||
|
75 | ||||
|
76 | from IPython.core.error import TryNext | |||
|
77 | import IPython.utils.rlineimpl as readline | |||
75 | from IPython.utils.ipstruct import Struct |
|
78 | from IPython.utils.ipstruct import Struct | |
76 | from IPython.core import ipapi |
|
|||
77 | from IPython.utils import generics |
|
79 | from IPython.utils import generics | |
78 | import types |
|
|||
79 |
|
80 | |||
80 | # Python 2.4 offers sets as a builtin |
|
81 | # Python 2.4 offers sets as a builtin | |
81 | try: |
|
82 | try: | |
82 | set() |
|
83 | set() | |
83 | except NameError: |
|
84 | except NameError: | |
84 | from sets import Set as set |
|
85 | from sets import Set as set | |
85 |
|
86 | |||
86 | from IPython.utils.genutils import debugx, dir2 |
|
87 | from IPython.utils.genutils import debugx, dir2 | |
87 |
|
88 | |||
88 | __all__ = ['Completer','IPCompleter'] |
|
89 | __all__ = ['Completer','IPCompleter'] | |
89 |
|
90 | |||
90 | class Completer: |
|
91 | class Completer: | |
91 | def __init__(self,namespace=None,global_namespace=None): |
|
92 | def __init__(self,namespace=None,global_namespace=None): | |
92 | """Create a new completer for the command line. |
|
93 | """Create a new completer for the command line. | |
93 |
|
94 | |||
94 | Completer([namespace,global_namespace]) -> completer instance. |
|
95 | Completer([namespace,global_namespace]) -> completer instance. | |
95 |
|
96 | |||
96 | If unspecified, the default namespace where completions are performed |
|
97 | If unspecified, the default namespace where completions are performed | |
97 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
98 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
98 | given as dictionaries. |
|
99 | given as dictionaries. | |
99 |
|
100 | |||
100 | An optional second namespace can be given. This allows the completer |
|
101 | An optional second namespace can be given. This allows the completer | |
101 | to handle cases where both the local and global scopes need to be |
|
102 | to handle cases where both the local and global scopes need to be | |
102 | distinguished. |
|
103 | distinguished. | |
103 |
|
104 | |||
104 | Completer instances should be used as the completion mechanism of |
|
105 | Completer instances should be used as the completion mechanism of | |
105 | readline via the set_completer() call: |
|
106 | readline via the set_completer() call: | |
106 |
|
107 | |||
107 | readline.set_completer(Completer(my_namespace).complete) |
|
108 | readline.set_completer(Completer(my_namespace).complete) | |
108 | """ |
|
109 | """ | |
109 |
|
110 | |||
110 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
111 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
111 | # specific namespace or to use __main__.__dict__. This will allow us |
|
112 | # specific namespace or to use __main__.__dict__. This will allow us | |
112 | # to bind to __main__.__dict__ at completion time, not now. |
|
113 | # to bind to __main__.__dict__ at completion time, not now. | |
113 | if namespace is None: |
|
114 | if namespace is None: | |
114 | self.use_main_ns = 1 |
|
115 | self.use_main_ns = 1 | |
115 | else: |
|
116 | else: | |
116 | self.use_main_ns = 0 |
|
117 | self.use_main_ns = 0 | |
117 | self.namespace = namespace |
|
118 | self.namespace = namespace | |
118 |
|
119 | |||
119 | # The global namespace, if given, can be bound directly |
|
120 | # The global namespace, if given, can be bound directly | |
120 | if global_namespace is None: |
|
121 | if global_namespace is None: | |
121 | self.global_namespace = {} |
|
122 | self.global_namespace = {} | |
122 | else: |
|
123 | else: | |
123 | self.global_namespace = global_namespace |
|
124 | self.global_namespace = global_namespace | |
124 |
|
125 | |||
125 | def complete(self, text, state): |
|
126 | def complete(self, text, state): | |
126 | """Return the next possible completion for 'text'. |
|
127 | """Return the next possible completion for 'text'. | |
127 |
|
128 | |||
128 | This is called successively with state == 0, 1, 2, ... until it |
|
129 | This is called successively with state == 0, 1, 2, ... until it | |
129 | returns None. The completion should begin with 'text'. |
|
130 | returns None. The completion should begin with 'text'. | |
130 |
|
131 | |||
131 | """ |
|
132 | """ | |
132 | if self.use_main_ns: |
|
133 | if self.use_main_ns: | |
133 | self.namespace = __main__.__dict__ |
|
134 | self.namespace = __main__.__dict__ | |
134 |
|
135 | |||
135 | if state == 0: |
|
136 | if state == 0: | |
136 | if "." in text: |
|
137 | if "." in text: | |
137 | self.matches = self.attr_matches(text) |
|
138 | self.matches = self.attr_matches(text) | |
138 | else: |
|
139 | else: | |
139 | self.matches = self.global_matches(text) |
|
140 | self.matches = self.global_matches(text) | |
140 | try: |
|
141 | try: | |
141 | return self.matches[state] |
|
142 | return self.matches[state] | |
142 | except IndexError: |
|
143 | except IndexError: | |
143 | return None |
|
144 | return None | |
144 |
|
145 | |||
145 | def global_matches(self, text): |
|
146 | def global_matches(self, text): | |
146 | """Compute matches when text is a simple name. |
|
147 | """Compute matches when text is a simple name. | |
147 |
|
148 | |||
148 | Return a list of all keywords, built-in functions and names currently |
|
149 | Return a list of all keywords, built-in functions and names currently | |
149 | defined in self.namespace or self.global_namespace that match. |
|
150 | defined in self.namespace or self.global_namespace that match. | |
150 |
|
151 | |||
151 | """ |
|
152 | """ | |
152 | matches = [] |
|
153 | matches = [] | |
153 | match_append = matches.append |
|
154 | match_append = matches.append | |
154 | n = len(text) |
|
155 | n = len(text) | |
155 | for lst in [keyword.kwlist, |
|
156 | for lst in [keyword.kwlist, | |
156 | __builtin__.__dict__.keys(), |
|
157 | __builtin__.__dict__.keys(), | |
157 | self.namespace.keys(), |
|
158 | self.namespace.keys(), | |
158 | self.global_namespace.keys()]: |
|
159 | self.global_namespace.keys()]: | |
159 | for word in lst: |
|
160 | for word in lst: | |
160 | if word[:n] == text and word != "__builtins__": |
|
161 | if word[:n] == text and word != "__builtins__": | |
161 | match_append(word) |
|
162 | match_append(word) | |
162 | return matches |
|
163 | return matches | |
163 |
|
164 | |||
164 | def attr_matches(self, text): |
|
165 | def attr_matches(self, text): | |
165 | """Compute matches when text contains a dot. |
|
166 | """Compute matches when text contains a dot. | |
166 |
|
167 | |||
167 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
168 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
168 | evaluatable in self.namespace or self.global_namespace, it will be |
|
169 | evaluatable in self.namespace or self.global_namespace, it will be | |
169 | evaluated and its attributes (as revealed by dir()) are used as |
|
170 | evaluated and its attributes (as revealed by dir()) are used as | |
170 | possible completions. (For class instances, class members are are |
|
171 | possible completions. (For class instances, class members are are | |
171 | also considered.) |
|
172 | also considered.) | |
172 |
|
173 | |||
173 | WARNING: this can still invoke arbitrary C code, if an object |
|
174 | WARNING: this can still invoke arbitrary C code, if an object | |
174 | with a __getattr__ hook is evaluated. |
|
175 | with a __getattr__ hook is evaluated. | |
175 |
|
176 | |||
176 | """ |
|
177 | """ | |
177 | import re |
|
178 | import re | |
178 |
|
179 | |||
179 | # Another option, seems to work great. Catches things like ''.<tab> |
|
180 | # Another option, seems to work great. Catches things like ''.<tab> | |
180 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
181 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
181 |
|
182 | |||
182 | if not m: |
|
183 | if not m: | |
183 | return [] |
|
184 | return [] | |
184 |
|
185 | |||
185 | expr, attr = m.group(1, 3) |
|
186 | expr, attr = m.group(1, 3) | |
186 | try: |
|
187 | try: | |
187 | obj = eval(expr, self.namespace) |
|
188 | obj = eval(expr, self.namespace) | |
188 | except: |
|
189 | except: | |
189 | try: |
|
190 | try: | |
190 | obj = eval(expr, self.global_namespace) |
|
191 | obj = eval(expr, self.global_namespace) | |
191 | except: |
|
192 | except: | |
192 | return [] |
|
193 | return [] | |
193 |
|
194 | |||
194 | words = dir2(obj) |
|
195 | words = dir2(obj) | |
195 |
|
196 | |||
196 | try: |
|
197 | try: | |
197 | words = generics.complete_object(obj, words) |
|
198 | words = generics.complete_object(obj, words) | |
198 |
except |
|
199 | except TryNext: | |
199 | pass |
|
200 | pass | |
200 | # Build match list to return |
|
201 | # Build match list to return | |
201 | n = len(attr) |
|
202 | n = len(attr) | |
202 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
203 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
203 | return res |
|
204 | return res | |
204 |
|
205 | |||
205 | class IPCompleter(Completer): |
|
206 | class IPCompleter(Completer): | |
206 | """Extension of the completer class with IPython-specific features""" |
|
207 | """Extension of the completer class with IPython-specific features""" | |
207 |
|
208 | |||
208 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
209 | def __init__(self,shell,namespace=None,global_namespace=None, | |
209 | omit__names=0,alias_table=None): |
|
210 | omit__names=0,alias_table=None): | |
210 | """IPCompleter() -> completer |
|
211 | """IPCompleter() -> completer | |
211 |
|
212 | |||
212 | Return a completer object suitable for use by the readline library |
|
213 | Return a completer object suitable for use by the readline library | |
213 | via readline.set_completer(). |
|
214 | via readline.set_completer(). | |
214 |
|
215 | |||
215 | Inputs: |
|
216 | Inputs: | |
216 |
|
217 | |||
217 | - shell: a pointer to the ipython shell itself. This is needed |
|
218 | - shell: a pointer to the ipython shell itself. This is needed | |
218 | because this completer knows about magic functions, and those can |
|
219 | because this completer knows about magic functions, and those can | |
219 | only be accessed via the ipython instance. |
|
220 | only be accessed via the ipython instance. | |
220 |
|
221 | |||
221 | - namespace: an optional dict where completions are performed. |
|
222 | - namespace: an optional dict where completions are performed. | |
222 |
|
223 | |||
223 | - global_namespace: secondary optional dict for completions, to |
|
224 | - global_namespace: secondary optional dict for completions, to | |
224 | handle cases (such as IPython embedded inside functions) where |
|
225 | handle cases (such as IPython embedded inside functions) where | |
225 | both Python scopes are visible. |
|
226 | both Python scopes are visible. | |
226 |
|
227 | |||
227 | - The optional omit__names parameter sets the completer to omit the |
|
228 | - The optional omit__names parameter sets the completer to omit the | |
228 | 'magic' names (__magicname__) for python objects unless the text |
|
229 | 'magic' names (__magicname__) for python objects unless the text | |
229 | to be completed explicitly starts with one or more underscores. |
|
230 | to be completed explicitly starts with one or more underscores. | |
230 |
|
231 | |||
231 | - If alias_table is supplied, it should be a dictionary of aliases |
|
232 | - If alias_table is supplied, it should be a dictionary of aliases | |
232 | to complete. """ |
|
233 | to complete. """ | |
233 |
|
234 | |||
234 | Completer.__init__(self,namespace,global_namespace) |
|
235 | Completer.__init__(self,namespace,global_namespace) | |
235 | self.magic_prefix = shell.name+'.magic_' |
|
236 | self.magic_prefix = shell.name+'.magic_' | |
236 | self.magic_escape = shell.ESC_MAGIC |
|
237 | self.magic_escape = shell.ESC_MAGIC | |
237 | self.readline = readline |
|
238 | self.readline = readline | |
238 | delims = self.readline.get_completer_delims() |
|
239 | delims = self.readline.get_completer_delims() | |
239 | delims = delims.replace(self.magic_escape,'') |
|
240 | delims = delims.replace(self.magic_escape,'') | |
240 | self.readline.set_completer_delims(delims) |
|
241 | self.readline.set_completer_delims(delims) | |
241 | self.get_line_buffer = self.readline.get_line_buffer |
|
242 | self.get_line_buffer = self.readline.get_line_buffer | |
242 | self.get_endidx = self.readline.get_endidx |
|
243 | self.get_endidx = self.readline.get_endidx | |
243 | self.omit__names = omit__names |
|
244 | self.omit__names = omit__names | |
244 |
self.merge_completions = shell. |
|
245 | self.merge_completions = shell.readline_merge_completions | |
245 | if alias_table is None: |
|
246 | if alias_table is None: | |
246 | alias_table = {} |
|
247 | alias_table = {} | |
247 | self.alias_table = alias_table |
|
248 | self.alias_table = alias_table | |
248 | # Regexp to split filenames with spaces in them |
|
249 | # Regexp to split filenames with spaces in them | |
249 | self.space_name_re = re.compile(r'([^\\] )') |
|
250 | self.space_name_re = re.compile(r'([^\\] )') | |
250 | # Hold a local ref. to glob.glob for speed |
|
251 | # Hold a local ref. to glob.glob for speed | |
251 | self.glob = glob.glob |
|
252 | self.glob = glob.glob | |
252 |
|
253 | |||
253 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
254 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
254 | # buffers, to avoid completion problems. |
|
255 | # buffers, to avoid completion problems. | |
255 | term = os.environ.get('TERM','xterm') |
|
256 | term = os.environ.get('TERM','xterm') | |
256 | self.dumb_terminal = term in ['dumb','emacs'] |
|
257 | self.dumb_terminal = term in ['dumb','emacs'] | |
257 |
|
258 | |||
258 | # Special handling of backslashes needed in win32 platforms |
|
259 | # Special handling of backslashes needed in win32 platforms | |
259 | if sys.platform == "win32": |
|
260 | if sys.platform == "win32": | |
260 | self.clean_glob = self._clean_glob_win32 |
|
261 | self.clean_glob = self._clean_glob_win32 | |
261 | else: |
|
262 | else: | |
262 | self.clean_glob = self._clean_glob |
|
263 | self.clean_glob = self._clean_glob | |
263 | self.matchers = [self.python_matches, |
|
264 | self.matchers = [self.python_matches, | |
264 | self.file_matches, |
|
265 | self.file_matches, | |
265 | self.alias_matches, |
|
266 | self.alias_matches, | |
266 | self.python_func_kw_matches] |
|
267 | self.python_func_kw_matches] | |
267 |
|
268 | |||
268 |
|
269 | |||
269 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
270 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
270 | def all_completions(self, text): |
|
271 | def all_completions(self, text): | |
271 | """Return all possible completions for the benefit of emacs.""" |
|
272 | """Return all possible completions for the benefit of emacs.""" | |
272 |
|
273 | |||
273 | completions = [] |
|
274 | completions = [] | |
274 | comp_append = completions.append |
|
275 | comp_append = completions.append | |
275 | try: |
|
276 | try: | |
276 | for i in xrange(sys.maxint): |
|
277 | for i in xrange(sys.maxint): | |
277 | res = self.complete(text, i) |
|
278 | res = self.complete(text, i) | |
278 |
|
279 | |||
279 | if not res: break |
|
280 | if not res: break | |
280 |
|
281 | |||
281 | comp_append(res) |
|
282 | comp_append(res) | |
282 | #XXX workaround for ``notDefined.<tab>`` |
|
283 | #XXX workaround for ``notDefined.<tab>`` | |
283 | except NameError: |
|
284 | except NameError: | |
284 | pass |
|
285 | pass | |
285 | return completions |
|
286 | return completions | |
286 | # /end Alex Schmolck code. |
|
287 | # /end Alex Schmolck code. | |
287 |
|
288 | |||
288 | def _clean_glob(self,text): |
|
289 | def _clean_glob(self,text): | |
289 | return self.glob("%s*" % text) |
|
290 | return self.glob("%s*" % text) | |
290 |
|
291 | |||
291 | def _clean_glob_win32(self,text): |
|
292 | def _clean_glob_win32(self,text): | |
292 | return [f.replace("\\","/") |
|
293 | return [f.replace("\\","/") | |
293 | for f in self.glob("%s*" % text)] |
|
294 | for f in self.glob("%s*" % text)] | |
294 |
|
295 | |||
295 | def file_matches(self, text): |
|
296 | def file_matches(self, text): | |
296 | """Match filenames, expanding ~USER type strings. |
|
297 | """Match filenames, expanding ~USER type strings. | |
297 |
|
298 | |||
298 | Most of the seemingly convoluted logic in this completer is an |
|
299 | Most of the seemingly convoluted logic in this completer is an | |
299 | attempt to handle filenames with spaces in them. And yet it's not |
|
300 | attempt to handle filenames with spaces in them. And yet it's not | |
300 | quite perfect, because Python's readline doesn't expose all of the |
|
301 | quite perfect, because Python's readline doesn't expose all of the | |
301 | GNU readline details needed for this to be done correctly. |
|
302 | GNU readline details needed for this to be done correctly. | |
302 |
|
303 | |||
303 | For a filename with a space in it, the printed completions will be |
|
304 | For a filename with a space in it, the printed completions will be | |
304 | only the parts after what's already been typed (instead of the |
|
305 | only the parts after what's already been typed (instead of the | |
305 | full completions, as is normally done). I don't think with the |
|
306 | full completions, as is normally done). I don't think with the | |
306 | current (as of Python 2.3) Python readline it's possible to do |
|
307 | current (as of Python 2.3) Python readline it's possible to do | |
307 | better.""" |
|
308 | better.""" | |
308 |
|
309 | |||
309 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
310 | #print 'Completer->file_matches: <%s>' % text # dbg | |
310 |
|
311 | |||
311 | # chars that require escaping with backslash - i.e. chars |
|
312 | # chars that require escaping with backslash - i.e. chars | |
312 | # that readline treats incorrectly as delimiters, but we |
|
313 | # that readline treats incorrectly as delimiters, but we | |
313 | # don't want to treat as delimiters in filename matching |
|
314 | # don't want to treat as delimiters in filename matching | |
314 | # when escaped with backslash |
|
315 | # when escaped with backslash | |
315 |
|
316 | |||
316 | if sys.platform == 'win32': |
|
317 | if sys.platform == 'win32': | |
317 | protectables = ' ' |
|
318 | protectables = ' ' | |
318 | else: |
|
319 | else: | |
319 | protectables = ' ()' |
|
320 | protectables = ' ()' | |
320 |
|
321 | |||
321 | if text.startswith('!'): |
|
322 | if text.startswith('!'): | |
322 | text = text[1:] |
|
323 | text = text[1:] | |
323 | text_prefix = '!' |
|
324 | text_prefix = '!' | |
324 | else: |
|
325 | else: | |
325 | text_prefix = '' |
|
326 | text_prefix = '' | |
326 |
|
327 | |||
327 | def protect_filename(s): |
|
328 | def protect_filename(s): | |
328 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
329 | return "".join([(ch in protectables and '\\' + ch or ch) | |
329 | for ch in s]) |
|
330 | for ch in s]) | |
330 |
|
331 | |||
331 | def single_dir_expand(matches): |
|
332 | def single_dir_expand(matches): | |
332 | "Recursively expand match lists containing a single dir." |
|
333 | "Recursively expand match lists containing a single dir." | |
333 |
|
334 | |||
334 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
335 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
335 | # Takes care of links to directories also. Use '/' |
|
336 | # Takes care of links to directories also. Use '/' | |
336 | # explicitly, even under Windows, so that name completions |
|
337 | # explicitly, even under Windows, so that name completions | |
337 | # don't end up escaped. |
|
338 | # don't end up escaped. | |
338 | d = matches[0] |
|
339 | d = matches[0] | |
339 | if d[-1] in ['/','\\']: |
|
340 | if d[-1] in ['/','\\']: | |
340 | d = d[:-1] |
|
341 | d = d[:-1] | |
341 |
|
342 | |||
342 | subdirs = os.listdir(d) |
|
343 | subdirs = os.listdir(d) | |
343 | if subdirs: |
|
344 | if subdirs: | |
344 | matches = [ (d + '/' + p) for p in subdirs] |
|
345 | matches = [ (d + '/' + p) for p in subdirs] | |
345 | return single_dir_expand(matches) |
|
346 | return single_dir_expand(matches) | |
346 | else: |
|
347 | else: | |
347 | return matches |
|
348 | return matches | |
348 | else: |
|
349 | else: | |
349 | return matches |
|
350 | return matches | |
350 |
|
351 | |||
351 | lbuf = self.lbuf |
|
352 | lbuf = self.lbuf | |
352 | open_quotes = 0 # track strings with open quotes |
|
353 | open_quotes = 0 # track strings with open quotes | |
353 | try: |
|
354 | try: | |
354 | lsplit = shlex.split(lbuf)[-1] |
|
355 | lsplit = shlex.split(lbuf)[-1] | |
355 | except ValueError: |
|
356 | except ValueError: | |
356 | # typically an unmatched ", or backslash without escaped char. |
|
357 | # typically an unmatched ", or backslash without escaped char. | |
357 | if lbuf.count('"')==1: |
|
358 | if lbuf.count('"')==1: | |
358 | open_quotes = 1 |
|
359 | open_quotes = 1 | |
359 | lsplit = lbuf.split('"')[-1] |
|
360 | lsplit = lbuf.split('"')[-1] | |
360 | elif lbuf.count("'")==1: |
|
361 | elif lbuf.count("'")==1: | |
361 | open_quotes = 1 |
|
362 | open_quotes = 1 | |
362 | lsplit = lbuf.split("'")[-1] |
|
363 | lsplit = lbuf.split("'")[-1] | |
363 | else: |
|
364 | else: | |
364 | return [] |
|
365 | return [] | |
365 | except IndexError: |
|
366 | except IndexError: | |
366 | # tab pressed on empty line |
|
367 | # tab pressed on empty line | |
367 | lsplit = "" |
|
368 | lsplit = "" | |
368 |
|
369 | |||
369 | if lsplit != protect_filename(lsplit): |
|
370 | if lsplit != protect_filename(lsplit): | |
370 | # if protectables are found, do matching on the whole escaped |
|
371 | # if protectables are found, do matching on the whole escaped | |
371 | # name |
|
372 | # name | |
372 | has_protectables = 1 |
|
373 | has_protectables = 1 | |
373 | text0,text = text,lsplit |
|
374 | text0,text = text,lsplit | |
374 | else: |
|
375 | else: | |
375 | has_protectables = 0 |
|
376 | has_protectables = 0 | |
376 | text = os.path.expanduser(text) |
|
377 | text = os.path.expanduser(text) | |
377 |
|
378 | |||
378 | if text == "": |
|
379 | if text == "": | |
379 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
380 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
380 |
|
381 | |||
381 | m0 = self.clean_glob(text.replace('\\','')) |
|
382 | m0 = self.clean_glob(text.replace('\\','')) | |
382 | if has_protectables: |
|
383 | if has_protectables: | |
383 | # If we had protectables, we need to revert our changes to the |
|
384 | # If we had protectables, we need to revert our changes to the | |
384 | # beginning of filename so that we don't double-write the part |
|
385 | # beginning of filename so that we don't double-write the part | |
385 | # of the filename we have so far |
|
386 | # of the filename we have so far | |
386 | len_lsplit = len(lsplit) |
|
387 | len_lsplit = len(lsplit) | |
387 | matches = [text_prefix + text0 + |
|
388 | matches = [text_prefix + text0 + | |
388 | protect_filename(f[len_lsplit:]) for f in m0] |
|
389 | protect_filename(f[len_lsplit:]) for f in m0] | |
389 | else: |
|
390 | else: | |
390 | if open_quotes: |
|
391 | if open_quotes: | |
391 | # if we have a string with an open quote, we don't need to |
|
392 | # if we have a string with an open quote, we don't need to | |
392 | # protect the names at all (and we _shouldn't_, as it |
|
393 | # protect the names at all (and we _shouldn't_, as it | |
393 | # would cause bugs when the filesystem call is made). |
|
394 | # would cause bugs when the filesystem call is made). | |
394 | matches = m0 |
|
395 | matches = m0 | |
395 | else: |
|
396 | else: | |
396 | matches = [text_prefix + |
|
397 | matches = [text_prefix + | |
397 | protect_filename(f) for f in m0] |
|
398 | protect_filename(f) for f in m0] | |
398 |
|
399 | |||
399 | #print 'mm',matches # dbg |
|
400 | #print 'mm',matches # dbg | |
400 | return single_dir_expand(matches) |
|
401 | return single_dir_expand(matches) | |
401 |
|
402 | |||
402 | def alias_matches(self, text): |
|
403 | def alias_matches(self, text): | |
403 | """Match internal system aliases""" |
|
404 | """Match internal system aliases""" | |
404 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
405 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg | |
405 |
|
406 | |||
406 | # if we are not in the first 'item', alias matching |
|
407 | # if we are not in the first 'item', alias matching | |
407 | # doesn't make sense - unless we are starting with 'sudo' command. |
|
408 | # doesn't make sense - unless we are starting with 'sudo' command. | |
408 | if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'): |
|
409 | if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'): | |
409 | return [] |
|
410 | return [] | |
410 | text = os.path.expanduser(text) |
|
411 | text = os.path.expanduser(text) | |
411 | aliases = self.alias_table.keys() |
|
412 | aliases = self.alias_table.keys() | |
412 | if text == "": |
|
413 | if text == "": | |
413 | return aliases |
|
414 | return aliases | |
414 | else: |
|
415 | else: | |
415 | return [alias for alias in aliases if alias.startswith(text)] |
|
416 | return [alias for alias in aliases if alias.startswith(text)] | |
416 |
|
417 | |||
417 | def python_matches(self,text): |
|
418 | def python_matches(self,text): | |
418 | """Match attributes or global python names""" |
|
419 | """Match attributes or global python names""" | |
419 |
|
420 | |||
420 | #print 'Completer->python_matches, txt=<%s>' % text # dbg |
|
421 | #print 'Completer->python_matches, txt=<%s>' % text # dbg | |
421 | if "." in text: |
|
422 | if "." in text: | |
422 | try: |
|
423 | try: | |
423 | matches = self.attr_matches(text) |
|
424 | matches = self.attr_matches(text) | |
424 | if text.endswith('.') and self.omit__names: |
|
425 | if text.endswith('.') and self.omit__names: | |
425 | if self.omit__names == 1: |
|
426 | if self.omit__names == 1: | |
426 | # true if txt is _not_ a __ name, false otherwise: |
|
427 | # true if txt is _not_ a __ name, false otherwise: | |
427 | no__name = (lambda txt: |
|
428 | no__name = (lambda txt: | |
428 | re.match(r'.*\.__.*?__',txt) is None) |
|
429 | re.match(r'.*\.__.*?__',txt) is None) | |
429 | else: |
|
430 | else: | |
430 | # true if txt is _not_ a _ name, false otherwise: |
|
431 | # true if txt is _not_ a _ name, false otherwise: | |
431 | no__name = (lambda txt: |
|
432 | no__name = (lambda txt: | |
432 | re.match(r'.*\._.*?',txt) is None) |
|
433 | re.match(r'.*\._.*?',txt) is None) | |
433 | matches = filter(no__name, matches) |
|
434 | matches = filter(no__name, matches) | |
434 | except NameError: |
|
435 | except NameError: | |
435 | # catches <undefined attributes>.<tab> |
|
436 | # catches <undefined attributes>.<tab> | |
436 | matches = [] |
|
437 | matches = [] | |
437 | else: |
|
438 | else: | |
438 | matches = self.global_matches(text) |
|
439 | matches = self.global_matches(text) | |
439 | # this is so completion finds magics when automagic is on: |
|
440 | # this is so completion finds magics when automagic is on: | |
440 | if (matches == [] and |
|
441 | if (matches == [] and | |
441 | not text.startswith(os.sep) and |
|
442 | not text.startswith(os.sep) and | |
442 | not ' ' in self.lbuf): |
|
443 | not ' ' in self.lbuf): | |
443 | matches = self.attr_matches(self.magic_prefix+text) |
|
444 | matches = self.attr_matches(self.magic_prefix+text) | |
444 | return matches |
|
445 | return matches | |
445 |
|
446 | |||
446 | def _default_arguments(self, obj): |
|
447 | def _default_arguments(self, obj): | |
447 | """Return the list of default arguments of obj if it is callable, |
|
448 | """Return the list of default arguments of obj if it is callable, | |
448 | or empty list otherwise.""" |
|
449 | or empty list otherwise.""" | |
449 |
|
450 | |||
450 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
451 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
451 | # for classes, check for __init__,__new__ |
|
452 | # for classes, check for __init__,__new__ | |
452 | if inspect.isclass(obj): |
|
453 | if inspect.isclass(obj): | |
453 | obj = (getattr(obj,'__init__',None) or |
|
454 | obj = (getattr(obj,'__init__',None) or | |
454 | getattr(obj,'__new__',None)) |
|
455 | getattr(obj,'__new__',None)) | |
455 | # for all others, check if they are __call__able |
|
456 | # for all others, check if they are __call__able | |
456 | elif hasattr(obj, '__call__'): |
|
457 | elif hasattr(obj, '__call__'): | |
457 | obj = obj.__call__ |
|
458 | obj = obj.__call__ | |
458 | # XXX: is there a way to handle the builtins ? |
|
459 | # XXX: is there a way to handle the builtins ? | |
459 | try: |
|
460 | try: | |
460 | args,_,_1,defaults = inspect.getargspec(obj) |
|
461 | args,_,_1,defaults = inspect.getargspec(obj) | |
461 | if defaults: |
|
462 | if defaults: | |
462 | return args[-len(defaults):] |
|
463 | return args[-len(defaults):] | |
463 | except TypeError: pass |
|
464 | except TypeError: pass | |
464 | return [] |
|
465 | return [] | |
465 |
|
466 | |||
466 | def python_func_kw_matches(self,text): |
|
467 | def python_func_kw_matches(self,text): | |
467 | """Match named parameters (kwargs) of the last open function""" |
|
468 | """Match named parameters (kwargs) of the last open function""" | |
468 |
|
469 | |||
469 | if "." in text: # a parameter cannot be dotted |
|
470 | if "." in text: # a parameter cannot be dotted | |
470 | return [] |
|
471 | return [] | |
471 | try: regexp = self.__funcParamsRegex |
|
472 | try: regexp = self.__funcParamsRegex | |
472 | except AttributeError: |
|
473 | except AttributeError: | |
473 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
474 | regexp = self.__funcParamsRegex = re.compile(r''' | |
474 | '.*?' | # single quoted strings or |
|
475 | '.*?' | # single quoted strings or | |
475 | ".*?" | # double quoted strings or |
|
476 | ".*?" | # double quoted strings or | |
476 | \w+ | # identifier |
|
477 | \w+ | # identifier | |
477 | \S # other characters |
|
478 | \S # other characters | |
478 | ''', re.VERBOSE | re.DOTALL) |
|
479 | ''', re.VERBOSE | re.DOTALL) | |
479 | # 1. find the nearest identifier that comes before an unclosed |
|
480 | # 1. find the nearest identifier that comes before an unclosed | |
480 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
481 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
481 | tokens = regexp.findall(self.get_line_buffer()) |
|
482 | tokens = regexp.findall(self.get_line_buffer()) | |
482 | tokens.reverse() |
|
483 | tokens.reverse() | |
483 | iterTokens = iter(tokens); openPar = 0 |
|
484 | iterTokens = iter(tokens); openPar = 0 | |
484 | for token in iterTokens: |
|
485 | for token in iterTokens: | |
485 | if token == ')': |
|
486 | if token == ')': | |
486 | openPar -= 1 |
|
487 | openPar -= 1 | |
487 | elif token == '(': |
|
488 | elif token == '(': | |
488 | openPar += 1 |
|
489 | openPar += 1 | |
489 | if openPar > 0: |
|
490 | if openPar > 0: | |
490 | # found the last unclosed parenthesis |
|
491 | # found the last unclosed parenthesis | |
491 | break |
|
492 | break | |
492 | else: |
|
493 | else: | |
493 | return [] |
|
494 | return [] | |
494 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
495 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
495 | ids = [] |
|
496 | ids = [] | |
496 | isId = re.compile(r'\w+$').match |
|
497 | isId = re.compile(r'\w+$').match | |
497 | while True: |
|
498 | while True: | |
498 | try: |
|
499 | try: | |
499 | ids.append(iterTokens.next()) |
|
500 | ids.append(iterTokens.next()) | |
500 | if not isId(ids[-1]): |
|
501 | if not isId(ids[-1]): | |
501 | ids.pop(); break |
|
502 | ids.pop(); break | |
502 | if not iterTokens.next() == '.': |
|
503 | if not iterTokens.next() == '.': | |
503 | break |
|
504 | break | |
504 | except StopIteration: |
|
505 | except StopIteration: | |
505 | break |
|
506 | break | |
506 | # lookup the candidate callable matches either using global_matches |
|
507 | # lookup the candidate callable matches either using global_matches | |
507 | # or attr_matches for dotted names |
|
508 | # or attr_matches for dotted names | |
508 | if len(ids) == 1: |
|
509 | if len(ids) == 1: | |
509 | callableMatches = self.global_matches(ids[0]) |
|
510 | callableMatches = self.global_matches(ids[0]) | |
510 | else: |
|
511 | else: | |
511 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
512 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
512 | argMatches = [] |
|
513 | argMatches = [] | |
513 | for callableMatch in callableMatches: |
|
514 | for callableMatch in callableMatches: | |
514 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
515 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
515 | self.namespace)) |
|
516 | self.namespace)) | |
516 | except: continue |
|
517 | except: continue | |
517 | for namedArg in namedArgs: |
|
518 | for namedArg in namedArgs: | |
518 | if namedArg.startswith(text): |
|
519 | if namedArg.startswith(text): | |
519 | argMatches.append("%s=" %namedArg) |
|
520 | argMatches.append("%s=" %namedArg) | |
520 | return argMatches |
|
521 | return argMatches | |
521 |
|
522 | |||
522 | def dispatch_custom_completer(self,text): |
|
523 | def dispatch_custom_completer(self,text): | |
523 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
524 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg | |
524 | line = self.full_lbuf |
|
525 | line = self.full_lbuf | |
525 | if not line.strip(): |
|
526 | if not line.strip(): | |
526 | return None |
|
527 | return None | |
527 |
|
528 | |||
528 | event = Struct() |
|
529 | event = Struct() | |
529 | event.line = line |
|
530 | event.line = line | |
530 | event.symbol = text |
|
531 | event.symbol = text | |
531 | cmd = line.split(None,1)[0] |
|
532 | cmd = line.split(None,1)[0] | |
532 | event.command = cmd |
|
533 | event.command = cmd | |
533 | #print "\ncustom:{%s]\n" % event # dbg |
|
534 | #print "\ncustom:{%s]\n" % event # dbg | |
534 |
|
535 | |||
535 | # for foo etc, try also to find completer for %foo |
|
536 | # for foo etc, try also to find completer for %foo | |
536 | if not cmd.startswith(self.magic_escape): |
|
537 | if not cmd.startswith(self.magic_escape): | |
537 | try_magic = self.custom_completers.s_matches( |
|
538 | try_magic = self.custom_completers.s_matches( | |
538 | self.magic_escape + cmd) |
|
539 | self.magic_escape + cmd) | |
539 | else: |
|
540 | else: | |
540 | try_magic = [] |
|
541 | try_magic = [] | |
541 |
|
542 | |||
542 |
|
543 | |||
543 | for c in itertools.chain( |
|
544 | for c in itertools.chain( | |
544 | self.custom_completers.s_matches(cmd), |
|
545 | self.custom_completers.s_matches(cmd), | |
545 | try_magic, |
|
546 | try_magic, | |
546 | self.custom_completers.flat_matches(self.lbuf)): |
|
547 | self.custom_completers.flat_matches(self.lbuf)): | |
547 | #print "try",c # dbg |
|
548 | #print "try",c # dbg | |
548 | try: |
|
549 | try: | |
549 | res = c(event) |
|
550 | res = c(event) | |
550 | # first, try case sensitive match |
|
551 | # first, try case sensitive match | |
551 | withcase = [r for r in res if r.startswith(text)] |
|
552 | withcase = [r for r in res if r.startswith(text)] | |
552 | if withcase: |
|
553 | if withcase: | |
553 | return withcase |
|
554 | return withcase | |
554 | # if none, then case insensitive ones are ok too |
|
555 | # if none, then case insensitive ones are ok too | |
555 | return [r for r in res if r.lower().startswith(text.lower())] |
|
556 | return [r for r in res if r.lower().startswith(text.lower())] | |
556 |
except |
|
557 | except TryNext: | |
557 | pass |
|
558 | pass | |
558 |
|
559 | |||
559 | return None |
|
560 | return None | |
560 |
|
561 | |||
561 | def complete(self, text, state,line_buffer=None): |
|
562 | def complete(self, text, state,line_buffer=None): | |
562 | """Return the next possible completion for 'text'. |
|
563 | """Return the next possible completion for 'text'. | |
563 |
|
564 | |||
564 | This is called successively with state == 0, 1, 2, ... until it |
|
565 | This is called successively with state == 0, 1, 2, ... until it | |
565 | returns None. The completion should begin with 'text'. |
|
566 | returns None. The completion should begin with 'text'. | |
566 |
|
567 | |||
567 | :Keywords: |
|
568 | :Keywords: | |
568 | - line_buffer: string |
|
569 | - line_buffer: string | |
569 | If not given, the completer attempts to obtain the current line buffer |
|
570 | If not given, the completer attempts to obtain the current line buffer | |
570 | via readline. This keyword allows clients which are requesting for |
|
571 | via readline. This keyword allows clients which are requesting for | |
571 | text completions in non-readline contexts to inform the completer of |
|
572 | text completions in non-readline contexts to inform the completer of | |
572 | the entire text. |
|
573 | the entire text. | |
573 | """ |
|
574 | """ | |
574 |
|
575 | |||
575 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
576 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
576 |
|
577 | |||
577 | # if there is only a tab on a line with only whitespace, instead |
|
578 | # if there is only a tab on a line with only whitespace, instead | |
578 | # of the mostly useless 'do you want to see all million |
|
579 | # of the mostly useless 'do you want to see all million | |
579 | # completions' message, just do the right thing and give the user |
|
580 | # completions' message, just do the right thing and give the user | |
580 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
581 | # his tab! Incidentally, this enables pasting of tabbed text from | |
581 | # an editor (as long as autoindent is off). |
|
582 | # an editor (as long as autoindent is off). | |
582 |
|
583 | |||
583 | # It should be noted that at least pyreadline still shows |
|
584 | # It should be noted that at least pyreadline still shows | |
584 | # file completions - is there a way around it? |
|
585 | # file completions - is there a way around it? | |
585 |
|
586 | |||
586 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
587 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we | |
587 | # don't interfere with their own tab-completion mechanism. |
|
588 | # don't interfere with their own tab-completion mechanism. | |
588 | if line_buffer is None: |
|
589 | if line_buffer is None: | |
589 | self.full_lbuf = self.get_line_buffer() |
|
590 | self.full_lbuf = self.get_line_buffer() | |
590 | else: |
|
591 | else: | |
591 | self.full_lbuf = line_buffer |
|
592 | self.full_lbuf = line_buffer | |
592 |
|
593 | |||
593 | if not (self.dumb_terminal or self.full_lbuf.strip()): |
|
594 | if not (self.dumb_terminal or self.full_lbuf.strip()): | |
594 | self.readline.insert_text('\t') |
|
595 | self.readline.insert_text('\t') | |
595 | return None |
|
596 | return None | |
596 |
|
597 | |||
597 | magic_escape = self.magic_escape |
|
598 | magic_escape = self.magic_escape | |
598 | magic_prefix = self.magic_prefix |
|
599 | magic_prefix = self.magic_prefix | |
599 |
|
600 | |||
600 | self.lbuf = self.full_lbuf[:self.get_endidx()] |
|
601 | self.lbuf = self.full_lbuf[:self.get_endidx()] | |
601 |
|
602 | |||
602 | try: |
|
603 | try: | |
603 | if text.startswith(magic_escape): |
|
604 | if text.startswith(magic_escape): | |
604 | text = text.replace(magic_escape,magic_prefix) |
|
605 | text = text.replace(magic_escape,magic_prefix) | |
605 | elif text.startswith('~'): |
|
606 | elif text.startswith('~'): | |
606 | text = os.path.expanduser(text) |
|
607 | text = os.path.expanduser(text) | |
607 | if state == 0: |
|
608 | if state == 0: | |
608 | custom_res = self.dispatch_custom_completer(text) |
|
609 | custom_res = self.dispatch_custom_completer(text) | |
609 | if custom_res is not None: |
|
610 | if custom_res is not None: | |
610 | # did custom completers produce something? |
|
611 | # did custom completers produce something? | |
611 | self.matches = custom_res |
|
612 | self.matches = custom_res | |
612 | else: |
|
613 | else: | |
613 | # Extend the list of completions with the results of each |
|
614 | # Extend the list of completions with the results of each | |
614 | # matcher, so we return results to the user from all |
|
615 | # matcher, so we return results to the user from all | |
615 | # namespaces. |
|
616 | # namespaces. | |
616 | if self.merge_completions: |
|
617 | if self.merge_completions: | |
617 | self.matches = [] |
|
618 | self.matches = [] | |
618 | for matcher in self.matchers: |
|
619 | for matcher in self.matchers: | |
619 | self.matches.extend(matcher(text)) |
|
620 | self.matches.extend(matcher(text)) | |
620 | else: |
|
621 | else: | |
621 | for matcher in self.matchers: |
|
622 | for matcher in self.matchers: | |
622 | self.matches = matcher(text) |
|
623 | self.matches = matcher(text) | |
623 | if self.matches: |
|
624 | if self.matches: | |
624 | break |
|
625 | break | |
625 | def uniq(alist): |
|
626 | def uniq(alist): | |
626 | set = {} |
|
627 | set = {} | |
627 | return [set.setdefault(e,e) for e in alist if e not in set] |
|
628 | return [set.setdefault(e,e) for e in alist if e not in set] | |
628 | self.matches = uniq(self.matches) |
|
629 | self.matches = uniq(self.matches) | |
629 | try: |
|
630 | try: | |
630 | ret = self.matches[state].replace(magic_prefix,magic_escape) |
|
631 | ret = self.matches[state].replace(magic_prefix,magic_escape) | |
631 | return ret |
|
632 | return ret | |
632 | except IndexError: |
|
633 | except IndexError: | |
633 | return None |
|
634 | return None | |
634 | except: |
|
635 | except: | |
635 | #from IPython.core.ultratb import AutoFormattedTB; # dbg |
|
636 | #from IPython.core.ultratb import AutoFormattedTB; # dbg | |
636 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
637 | #tb=AutoFormattedTB('Verbose');tb() #dbg | |
637 |
|
638 | |||
638 | # If completion fails, don't annoy the user. |
|
639 | # If completion fails, don't annoy the user. | |
639 | return None |
|
640 | return None |
@@ -1,229 +1,242 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A lightweight component system for IPython. |
|
4 | A lightweight component system for IPython. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | from copy import deepcopy |
|
23 | from copy import deepcopy | |
|
24 | import datetime | |||
24 | from weakref import WeakValueDictionary |
|
25 | from weakref import WeakValueDictionary | |
25 |
|
26 | |||
26 | from IPython.utils.ipstruct import Struct |
|
27 | from IPython.utils.ipstruct import Struct | |
27 | from IPython.utils.traitlets import ( |
|
28 | from IPython.utils.traitlets import ( | |
28 | HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This |
|
29 | HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This | |
29 | ) |
|
30 | ) | |
30 |
|
31 | |||
31 |
|
32 | |||
32 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
33 | # Helper classes for Components |
|
34 | # Helper classes for Components | |
34 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
35 |
|
36 | |||
36 |
|
37 | |||
37 | class ComponentError(Exception): |
|
38 | class ComponentError(Exception): | |
38 | pass |
|
39 | pass | |
39 |
|
40 | |||
40 | class MetaComponentTracker(type): |
|
41 | class MetaComponentTracker(type): | |
41 | """A metaclass that tracks instances of Components and its subclasses.""" |
|
42 | """A metaclass that tracks instances of Components and its subclasses.""" | |
42 |
|
43 | |||
43 | def __init__(cls, name, bases, d): |
|
44 | def __init__(cls, name, bases, d): | |
44 | super(MetaComponentTracker, cls).__init__(name, bases, d) |
|
45 | super(MetaComponentTracker, cls).__init__(name, bases, d) | |
45 | cls.__instance_refs = WeakValueDictionary() |
|
46 | cls.__instance_refs = WeakValueDictionary() | |
46 | cls.__numcreated = 0 |
|
47 | cls.__numcreated = 0 | |
47 |
|
48 | |||
48 | def __call__(cls, *args, **kw): |
|
49 | def __call__(cls, *args, **kw): | |
49 | """Called when *class* is called (instantiated)!!! |
|
50 | """Called when *class* is called (instantiated)!!! | |
50 |
|
51 | |||
51 | When a Component or subclass is instantiated, this is called and |
|
52 | When a Component or subclass is instantiated, this is called and | |
52 | the instance is saved in a WeakValueDictionary for tracking. |
|
53 | the instance is saved in a WeakValueDictionary for tracking. | |
53 | """ |
|
54 | """ | |
54 |
|
55 | instance = cls.__new__(cls, *args, **kw) | ||
55 | instance = super(MetaComponentTracker, cls).__call__(*args, **kw) |
|
56 | # Do this before __init__ is called so get_instances works inside | |
|
57 | # __init__ methods! | |||
56 | for c in cls.__mro__: |
|
58 | for c in cls.__mro__: | |
57 | if issubclass(cls, c) and issubclass(c, Component): |
|
59 | if issubclass(cls, c) and issubclass(c, Component): | |
58 | c.__numcreated += 1 |
|
60 | c.__numcreated += 1 | |
59 | c.__instance_refs[c.__numcreated] = instance |
|
61 | c.__instance_refs[c.__numcreated] = instance | |
|
62 | if isinstance(instance, cls): | |||
|
63 | cls.__init__(instance, *args, **kw) | |||
|
64 | ||||
60 | return instance |
|
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 | """Get all instances of cls and its subclasses. |
|
68 | """Get all instances of cls and its subclasses. | |
64 |
|
69 | |||
65 | Parameters |
|
70 | Parameters | |
66 | ---------- |
|
71 | ---------- | |
67 | name : str |
|
72 | name : str | |
68 | Limit to components with this name. |
|
73 | Limit to components with this name. | |
69 | root : Component or subclass |
|
74 | root : Component or subclass | |
70 | Limit to components having this root. |
|
75 | Limit to components having this root. | |
|
76 | classname : str | |||
|
77 | The string name of a class to match exactly. | |||
71 | """ |
|
78 | """ | |
72 | instances = cls.__instance_refs.values() |
|
79 | instances = cls.__instance_refs.values() | |
73 | if name is not None: |
|
80 | if name is not None: | |
74 | instances = [i for i in instances if i.name == name] |
|
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 | if root is not None: |
|
84 | if root is not None: | |
76 | instances = [i for i in instances if i.root == root] |
|
85 | instances = [i for i in instances if i.root == root] | |
77 | return instances |
|
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 | """Get all instances of cls, i such that call(i)==True. |
|
90 | """Get all instances of cls, i such that call(i)==True. | |
81 |
|
91 | |||
82 |
This also takes the ``name`` and ``root`` a |
|
92 | This also takes the ``name`` and ``root`` and ``classname`` | |
83 | :meth:`get_instance` |
|
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 | class ComponentNameGenerator(object): |
|
98 | class ComponentNameGenerator(object): | |
89 | """A Singleton to generate unique component names.""" |
|
99 | """A Singleton to generate unique component names.""" | |
90 |
|
100 | |||
91 | def __init__(self, prefix): |
|
101 | def __init__(self, prefix): | |
92 | self.prefix = prefix |
|
102 | self.prefix = prefix | |
93 | self.i = 0 |
|
103 | self.i = 0 | |
94 |
|
104 | |||
95 | def __call__(self): |
|
105 | def __call__(self): | |
96 | count = self.i |
|
106 | count = self.i | |
97 | self.i += 1 |
|
107 | self.i += 1 | |
98 | return "%s%s" % (self.prefix, count) |
|
108 | return "%s%s" % (self.prefix, count) | |
99 |
|
109 | |||
100 |
|
110 | |||
101 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') |
|
111 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') | |
102 |
|
112 | |||
103 |
|
113 | |||
104 | class MetaComponent(MetaHasTraitlets, MetaComponentTracker): |
|
114 | class MetaComponent(MetaHasTraitlets, MetaComponentTracker): | |
105 | pass |
|
115 | pass | |
106 |
|
116 | |||
107 |
|
117 | |||
108 | #----------------------------------------------------------------------------- |
|
118 | #----------------------------------------------------------------------------- | |
109 | # Component implementation |
|
119 | # Component implementation | |
110 | #----------------------------------------------------------------------------- |
|
120 | #----------------------------------------------------------------------------- | |
111 |
|
121 | |||
112 |
|
122 | |||
113 | class Component(HasTraitlets): |
|
123 | class Component(HasTraitlets): | |
114 |
|
124 | |||
115 | __metaclass__ = MetaComponent |
|
125 | __metaclass__ = MetaComponent | |
116 |
|
126 | |||
117 | # Traitlets are fun! |
|
127 | # Traitlets are fun! | |
118 | config = Instance(Struct,(),{}) |
|
128 | config = Instance(Struct,(),{}) | |
119 | parent = This() |
|
129 | parent = This() | |
120 | root = This() |
|
130 | root = This() | |
|
131 | created = None | |||
121 |
|
132 | |||
122 | def __init__(self, parent, name=None, config=None): |
|
133 | def __init__(self, parent, name=None, config=None): | |
123 | """Create a component given a parent and possibly and name and config. |
|
134 | """Create a component given a parent and possibly and name and config. | |
124 |
|
135 | |||
125 | Parameters |
|
136 | Parameters | |
126 | ---------- |
|
137 | ---------- | |
127 | parent : Component subclass |
|
138 | parent : Component subclass | |
128 | The parent in the component graph. The parent is used |
|
139 | The parent in the component graph. The parent is used | |
129 | to get the root of the component graph. |
|
140 | to get the root of the component graph. | |
130 | name : str |
|
141 | name : str | |
131 | The unique name of the component. If empty, then a unique |
|
142 | The unique name of the component. If empty, then a unique | |
132 | one will be autogenerated. |
|
143 | one will be autogenerated. | |
133 | config : Struct |
|
144 | config : Struct | |
134 | If this is empty, self.config = parent.config, otherwise |
|
145 | If this is empty, self.config = parent.config, otherwise | |
135 | self.config = config and root.config is ignored. This argument |
|
146 | self.config = config and root.config is ignored. This argument | |
136 | should only be used to *override* the automatic inheritance of |
|
147 | should only be used to *override* the automatic inheritance of | |
137 | parent.config. If a caller wants to modify parent.config |
|
148 | parent.config. If a caller wants to modify parent.config | |
138 | (not override), the caller should make a copy and change |
|
149 | (not override), the caller should make a copy and change | |
139 | attributes and then pass the copy to this argument. |
|
150 | attributes and then pass the copy to this argument. | |
140 |
|
151 | |||
141 | Notes |
|
152 | Notes | |
142 | ----- |
|
153 | ----- | |
143 | Subclasses of Component must call the :meth:`__init__` method of |
|
154 | Subclasses of Component must call the :meth:`__init__` method of | |
144 | :class:`Component` *before* doing anything else and using |
|
155 | :class:`Component` *before* doing anything else and using | |
145 | :func:`super`:: |
|
156 | :func:`super`:: | |
146 |
|
157 | |||
147 | class MyComponent(Component): |
|
158 | class MyComponent(Component): | |
148 | def __init__(self, parent, name=None, config=None): |
|
159 | def __init__(self, parent, name=None, config=None): | |
149 | super(MyComponent, self).__init__(parent, name, config) |
|
160 | super(MyComponent, self).__init__(parent, name, config) | |
150 | # Then any other code you need to finish initialization. |
|
161 | # Then any other code you need to finish initialization. | |
151 |
|
162 | |||
152 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` |
|
163 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` | |
153 | attributes are handled properly. |
|
164 | attributes are handled properly. | |
154 | """ |
|
165 | """ | |
155 | super(Component, self).__init__() |
|
166 | super(Component, self).__init__() | |
156 | self._children = [] |
|
167 | self._children = [] | |
157 | if name is None: |
|
168 | if name is None: | |
158 | self.name = ComponentNameGenerator() |
|
169 | self.name = ComponentNameGenerator() | |
159 | else: |
|
170 | else: | |
160 | self.name = name |
|
171 | self.name = name | |
161 | self.root = self # This is the default, it is set when parent is set |
|
172 | self.root = self # This is the default, it is set when parent is set | |
162 | self.parent = parent |
|
173 | self.parent = parent | |
163 | if config is not None: |
|
174 | if config is not None: | |
164 | self.config = deepcopy(config) |
|
175 | self.config = deepcopy(config) | |
165 | else: |
|
176 | else: | |
166 | if self.parent is not None: |
|
177 | if self.parent is not None: | |
167 | self.config = deepcopy(self.parent.config) |
|
178 | self.config = deepcopy(self.parent.config) | |
168 |
|
179 | |||
|
180 | self.created = datetime.datetime.now() | |||
|
181 | ||||
169 | #------------------------------------------------------------------------- |
|
182 | #------------------------------------------------------------------------- | |
170 | # Static traitlet notifiations |
|
183 | # Static traitlet notifiations | |
171 | #------------------------------------------------------------------------- |
|
184 | #------------------------------------------------------------------------- | |
172 |
|
185 | |||
173 | def _parent_changed(self, name, old, new): |
|
186 | def _parent_changed(self, name, old, new): | |
174 | if old is not None: |
|
187 | if old is not None: | |
175 | old._remove_child(self) |
|
188 | old._remove_child(self) | |
176 | if new is not None: |
|
189 | if new is not None: | |
177 | new._add_child(self) |
|
190 | new._add_child(self) | |
178 |
|
191 | |||
179 | if new is None: |
|
192 | if new is None: | |
180 | self.root = self |
|
193 | self.root = self | |
181 | else: |
|
194 | else: | |
182 | self.root = new.root |
|
195 | self.root = new.root | |
183 |
|
196 | |||
184 | def _root_changed(self, name, old, new): |
|
197 | def _root_changed(self, name, old, new): | |
185 | if self.parent is None: |
|
198 | if self.parent is None: | |
186 | if not (new is self): |
|
199 | if not (new is self): | |
187 | raise ComponentError("Root not self, but parent is None.") |
|
200 | raise ComponentError("Root not self, but parent is None.") | |
188 | else: |
|
201 | else: | |
189 | if not self.parent.root is new: |
|
202 | if not self.parent.root is new: | |
190 | raise ComponentError("Error in setting the root attribute: " |
|
203 | raise ComponentError("Error in setting the root attribute: " | |
191 | "root != parent.root") |
|
204 | "root != parent.root") | |
192 |
|
205 | |||
193 | def _config_changed(self, name, old, new): |
|
206 | def _config_changed(self, name, old, new): | |
194 | """Update all the class traits having a config_key with the config. |
|
207 | """Update all the class traits having a config_key with the config. | |
195 |
|
208 | |||
196 | For any class traitlet with a ``config_key`` metadata attribute, we |
|
209 | For any class traitlet with a ``config_key`` metadata attribute, we | |
197 | update the traitlet with the value of the corresponding config entry. |
|
210 | update the traitlet with the value of the corresponding config entry. | |
198 |
|
211 | |||
199 | In the future, we might want to do a pop here so stale config info |
|
212 | In the future, we might want to do a pop here so stale config info | |
200 | is not passed onto children. |
|
213 | is not passed onto children. | |
201 | """ |
|
214 | """ | |
202 | # Get all traitlets with a config_key metadata entry |
|
215 | # Get all traitlets with a config_key metadata entry | |
203 | traitlets = self.traitlets('config_key') |
|
216 | traitlets = self.traitlets('config_key') | |
204 | for k, v in traitlets.items(): |
|
217 | for k, v in traitlets.items(): | |
205 | try: |
|
218 | try: | |
206 | config_value = new[v.get_metadata('config_key')] |
|
219 | config_value = new[v.get_metadata('config_key')] | |
207 | except KeyError: |
|
220 | except KeyError: | |
208 | pass |
|
221 | pass | |
209 | else: |
|
222 | else: | |
210 | setattr(self, k, config_value) |
|
223 | setattr(self, k, config_value) | |
211 |
|
224 | |||
212 | @property |
|
225 | @property | |
213 | def children(self): |
|
226 | def children(self): | |
214 | """A list of all my child components.""" |
|
227 | """A list of all my child components.""" | |
215 | return self._children |
|
228 | return self._children | |
216 |
|
229 | |||
217 | def _remove_child(self, child): |
|
230 | def _remove_child(self, child): | |
218 | """A private method for removing children components.""" |
|
231 | """A private method for removing children components.""" | |
219 | if child in self._children: |
|
232 | if child in self._children: | |
220 | index = self._children.index(child) |
|
233 | index = self._children.index(child) | |
221 | del self._children[index] |
|
234 | del self._children[index] | |
222 |
|
235 | |||
223 | def _add_child(self, child): |
|
236 | def _add_child(self, child): | |
224 | """A private method for adding children components.""" |
|
237 | """A private method for adding children components.""" | |
225 | if child not in self._children: |
|
238 | if child not in self._children: | |
226 | self._children.append(child) |
|
239 | self._children.append(child) | |
227 |
|
240 | |||
228 | def __repr__(self): |
|
241 | def __repr__(self): | |
229 | return "<Component('%s')>" % self.name |
|
242 | return "<Component('%s')>" % self.name |
@@ -1,229 +1,229 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. |
|
2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | Authors |
|
5 | Authors | |
6 | ------- |
|
6 | ------- | |
7 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
7 | - Fernando Perez <Fernando.Perez@berkeley.edu> | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
11 | # Copyright (C) 2008-2009 The IPython Development Team | |
12 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #***************************************************************************** |
|
16 | #***************************************************************************** | |
17 |
|
17 | |||
18 | #**************************************************************************** |
|
18 | #**************************************************************************** | |
19 | # Required modules |
|
19 | # Required modules | |
20 |
|
20 | |||
21 | # From the standard library |
|
21 | # From the standard library | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | from pprint import pformat |
|
24 | from pprint import pformat | |
25 |
|
25 | |||
26 | # Our own |
|
26 | # Our own | |
27 | from IPython.core import release |
|
27 | from IPython.core import release | |
28 | from IPython.core import ultratb |
|
28 | from IPython.core import ultratb | |
29 | from IPython.external.Itpl import itpl |
|
29 | from IPython.external.Itpl import itpl | |
30 |
|
30 | |||
31 | from IPython.utils.genutils import * |
|
31 | from IPython.utils.genutils import * | |
32 |
|
32 | |||
33 | #**************************************************************************** |
|
33 | #**************************************************************************** | |
34 | class CrashHandler: |
|
34 | class CrashHandler: | |
35 | """Customizable crash handlers for IPython-based systems. |
|
35 | """Customizable crash handlers for IPython-based systems. | |
36 |
|
36 | |||
37 | Instances of this class provide a __call__ method which can be used as a |
|
37 | Instances of this class provide a __call__ method which can be used as a | |
38 | sys.excepthook, i.e., the __call__ signature is: |
|
38 | sys.excepthook, i.e., the __call__ signature is: | |
39 |
|
39 | |||
40 | def __call__(self,etype, evalue, etb) |
|
40 | def __call__(self,etype, evalue, etb) | |
41 |
|
41 | |||
42 | """ |
|
42 | """ | |
43 |
|
43 | |||
44 | def __init__(self,IP,app_name,contact_name,contact_email, |
|
44 | def __init__(self,IP,app_name,contact_name,contact_email, | |
45 | bug_tracker,crash_report_fname, |
|
45 | bug_tracker,crash_report_fname, | |
46 | show_crash_traceback=True): |
|
46 | show_crash_traceback=True): | |
47 | """New crash handler. |
|
47 | """New crash handler. | |
48 |
|
48 | |||
49 | Inputs: |
|
49 | Inputs: | |
50 |
|
50 | |||
51 | - IP: a running IPython instance, which will be queried at crash time |
|
51 | - IP: a running IPython instance, which will be queried at crash time | |
52 | for internal information. |
|
52 | for internal information. | |
53 |
|
53 | |||
54 | - app_name: a string containing the name of your application. |
|
54 | - app_name: a string containing the name of your application. | |
55 |
|
55 | |||
56 | - contact_name: a string with the name of the person to contact. |
|
56 | - contact_name: a string with the name of the person to contact. | |
57 |
|
57 | |||
58 | - contact_email: a string with the email address of the contact. |
|
58 | - contact_email: a string with the email address of the contact. | |
59 |
|
59 | |||
60 | - bug_tracker: a string with the URL for your project's bug tracker. |
|
60 | - bug_tracker: a string with the URL for your project's bug tracker. | |
61 |
|
61 | |||
62 | - crash_report_fname: a string with the filename for the crash report |
|
62 | - crash_report_fname: a string with the filename for the crash report | |
63 | to be saved in. These reports are left in the ipython user directory |
|
63 | to be saved in. These reports are left in the ipython user directory | |
64 | as determined by the running IPython instance. |
|
64 | as determined by the running IPython instance. | |
65 |
|
65 | |||
66 | Optional inputs: |
|
66 | Optional inputs: | |
67 |
|
67 | |||
68 | - show_crash_traceback(True): if false, don't print the crash |
|
68 | - show_crash_traceback(True): if false, don't print the crash | |
69 | traceback on stderr, only generate the on-disk report |
|
69 | traceback on stderr, only generate the on-disk report | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | Non-argument instance attributes: |
|
72 | Non-argument instance attributes: | |
73 |
|
73 | |||
74 | These instances contain some non-argument attributes which allow for |
|
74 | These instances contain some non-argument attributes which allow for | |
75 | further customization of the crash handler's behavior. Please see the |
|
75 | further customization of the crash handler's behavior. Please see the | |
76 | source for further details. |
|
76 | source for further details. | |
77 | """ |
|
77 | """ | |
78 |
|
78 | |||
79 | # apply args into instance |
|
79 | # apply args into instance | |
80 | self.IP = IP # IPython instance |
|
80 | self.IP = IP # IPython instance | |
81 | self.app_name = app_name |
|
81 | self.app_name = app_name | |
82 | self.contact_name = contact_name |
|
82 | self.contact_name = contact_name | |
83 | self.contact_email = contact_email |
|
83 | self.contact_email = contact_email | |
84 | self.bug_tracker = bug_tracker |
|
84 | self.bug_tracker = bug_tracker | |
85 | self.crash_report_fname = crash_report_fname |
|
85 | self.crash_report_fname = crash_report_fname | |
86 | self.show_crash_traceback = show_crash_traceback |
|
86 | self.show_crash_traceback = show_crash_traceback | |
87 |
|
87 | |||
88 | # Hardcoded defaults, which can be overridden either by subclasses or |
|
88 | # Hardcoded defaults, which can be overridden either by subclasses or | |
89 | # at runtime for the instance. |
|
89 | # at runtime for the instance. | |
90 |
|
90 | |||
91 | # Template for the user message. Subclasses which completely override |
|
91 | # Template for the user message. Subclasses which completely override | |
92 | # this, or user apps, can modify it to suit their tastes. It gets |
|
92 | # this, or user apps, can modify it to suit their tastes. It gets | |
93 | # expanded using itpl, so calls of the kind $self.foo are valid. |
|
93 | # expanded using itpl, so calls of the kind $self.foo are valid. | |
94 | self.user_message_template = """ |
|
94 | self.user_message_template = """ | |
95 | Oops, $self.app_name crashed. We do our best to make it stable, but... |
|
95 | Oops, $self.app_name crashed. We do our best to make it stable, but... | |
96 |
|
96 | |||
97 | A crash report was automatically generated with the following information: |
|
97 | A crash report was automatically generated with the following information: | |
98 | - A verbatim copy of the crash traceback. |
|
98 | - A verbatim copy of the crash traceback. | |
99 | - A copy of your input history during this session. |
|
99 | - A copy of your input history during this session. | |
100 | - Data on your current $self.app_name configuration. |
|
100 | - Data on your current $self.app_name configuration. | |
101 |
|
101 | |||
102 | It was left in the file named: |
|
102 | It was left in the file named: | |
103 | \t'$self.crash_report_fname' |
|
103 | \t'$self.crash_report_fname' | |
104 | If you can email this file to the developers, the information in it will help |
|
104 | If you can email this file to the developers, the information in it will help | |
105 | them in understanding and correcting the problem. |
|
105 | them in understanding and correcting the problem. | |
106 |
|
106 | |||
107 | You can mail it to: $self.contact_name at $self.contact_email |
|
107 | You can mail it to: $self.contact_name at $self.contact_email | |
108 | with the subject '$self.app_name Crash Report'. |
|
108 | with the subject '$self.app_name Crash Report'. | |
109 |
|
109 | |||
110 | If you want to do it now, the following command will work (under Unix): |
|
110 | If you want to do it now, the following command will work (under Unix): | |
111 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname |
|
111 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname | |
112 |
|
112 | |||
113 | To ensure accurate tracking of this issue, please file a report about it at: |
|
113 | To ensure accurate tracking of this issue, please file a report about it at: | |
114 | $self.bug_tracker |
|
114 | $self.bug_tracker | |
115 | """ |
|
115 | """ | |
116 |
|
116 | |||
117 | def __call__(self,etype, evalue, etb): |
|
117 | def __call__(self,etype, evalue, etb): | |
118 | """Handle an exception, call for compatible with sys.excepthook""" |
|
118 | """Handle an exception, call for compatible with sys.excepthook""" | |
119 |
|
119 | |||
120 | # Report tracebacks shouldn't use color in general (safer for users) |
|
120 | # Report tracebacks shouldn't use color in general (safer for users) | |
121 | color_scheme = 'NoColor' |
|
121 | color_scheme = 'NoColor' | |
122 |
|
122 | |||
123 | # Use this ONLY for developer debugging (keep commented out for release) |
|
123 | # Use this ONLY for developer debugging (keep commented out for release) | |
124 | #color_scheme = 'Linux' # dbg |
|
124 | #color_scheme = 'Linux' # dbg | |
125 |
|
125 | |||
126 | try: |
|
126 | try: | |
127 |
rptdir = self.IP. |
|
127 | rptdir = self.IP.config.IPYTHONDIR | |
128 | except: |
|
128 | except: | |
129 | rptdir = os.getcwd() |
|
129 | rptdir = os.getcwd() | |
130 | if not os.path.isdir(rptdir): |
|
130 | if not os.path.isdir(rptdir): | |
131 | rptdir = os.getcwd() |
|
131 | rptdir = os.getcwd() | |
132 | report_name = os.path.join(rptdir,self.crash_report_fname) |
|
132 | report_name = os.path.join(rptdir,self.crash_report_fname) | |
133 | # write the report filename into the instance dict so it can get |
|
133 | # write the report filename into the instance dict so it can get | |
134 | # properly expanded out in the user message template |
|
134 | # properly expanded out in the user message template | |
135 | self.crash_report_fname = report_name |
|
135 | self.crash_report_fname = report_name | |
136 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, |
|
136 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, | |
137 | long_header=1) |
|
137 | long_header=1) | |
138 | traceback = TBhandler.text(etype,evalue,etb,context=31) |
|
138 | traceback = TBhandler.text(etype,evalue,etb,context=31) | |
139 |
|
139 | |||
140 | # print traceback to screen |
|
140 | # print traceback to screen | |
141 | if self.show_crash_traceback: |
|
141 | if self.show_crash_traceback: | |
142 | print >> sys.stderr, traceback |
|
142 | print >> sys.stderr, traceback | |
143 |
|
143 | |||
144 | # and generate a complete report on disk |
|
144 | # and generate a complete report on disk | |
145 | try: |
|
145 | try: | |
146 | report = open(report_name,'w') |
|
146 | report = open(report_name,'w') | |
147 | except: |
|
147 | except: | |
148 | print >> sys.stderr, 'Could not create crash report on disk.' |
|
148 | print >> sys.stderr, 'Could not create crash report on disk.' | |
149 | return |
|
149 | return | |
150 |
|
150 | |||
151 | # Inform user on stderr of what happened |
|
151 | # Inform user on stderr of what happened | |
152 | msg = itpl('\n'+'*'*70+'\n'+self.user_message_template) |
|
152 | msg = itpl('\n'+'*'*70+'\n'+self.user_message_template) | |
153 | print >> sys.stderr, msg |
|
153 | print >> sys.stderr, msg | |
154 |
|
154 | |||
155 | # Construct report on disk |
|
155 | # Construct report on disk | |
156 | report.write(self.make_report(traceback)) |
|
156 | report.write(self.make_report(traceback)) | |
157 | report.close() |
|
157 | report.close() | |
158 | raw_input("Press enter to exit:") |
|
158 | raw_input("Press enter to exit:") | |
159 |
|
159 | |||
160 | def make_report(self,traceback): |
|
160 | def make_report(self,traceback): | |
161 | """Return a string containing a crash report.""" |
|
161 | """Return a string containing a crash report.""" | |
162 |
|
162 | |||
163 | sec_sep = '\n\n'+'*'*75+'\n\n' |
|
163 | sec_sep = '\n\n'+'*'*75+'\n\n' | |
164 |
|
164 | |||
165 | report = [] |
|
165 | report = [] | |
166 | rpt_add = report.append |
|
166 | rpt_add = report.append | |
167 |
|
167 | |||
168 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
168 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') | |
169 | rpt_add('IPython version: %s \n\n' % release.version) |
|
169 | rpt_add('IPython version: %s \n\n' % release.version) | |
170 | rpt_add('BZR revision : %s \n\n' % release.revision) |
|
170 | rpt_add('BZR revision : %s \n\n' % release.revision) | |
171 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
171 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % | |
172 | (os.name,sys.platform) ) |
|
172 | (os.name,sys.platform) ) | |
173 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
173 | rpt_add(sec_sep+'Current user configuration structure:\n\n') | |
174 |
rpt_add(pformat(self.IP. |
|
174 | rpt_add(pformat(self.IP.dict())) | |
175 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
175 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) | |
176 | try: |
|
176 | try: | |
177 | rpt_add(sec_sep+"History of session input:") |
|
177 | rpt_add(sec_sep+"History of session input:") | |
178 | for line in self.IP.user_ns['_ih']: |
|
178 | for line in self.IP.user_ns['_ih']: | |
179 | rpt_add(line) |
|
179 | rpt_add(line) | |
180 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
180 | rpt_add('\n*** Last line of input (may not be in above history):\n') | |
181 | rpt_add(self.IP._last_input_line+'\n') |
|
181 | rpt_add(self.IP._last_input_line+'\n') | |
182 | except: |
|
182 | except: | |
183 | pass |
|
183 | pass | |
184 |
|
184 | |||
185 | return ''.join(report) |
|
185 | return ''.join(report) | |
186 |
|
186 | |||
187 | class IPythonCrashHandler(CrashHandler): |
|
187 | class IPythonCrashHandler(CrashHandler): | |
188 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
188 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" | |
189 |
|
189 | |||
190 | def __init__(self,IP): |
|
190 | def __init__(self,IP): | |
191 |
|
191 | |||
192 | # Set here which of the IPython authors should be listed as contact |
|
192 | # Set here which of the IPython authors should be listed as contact | |
193 | AUTHOR_CONTACT = 'Fernando' |
|
193 | AUTHOR_CONTACT = 'Fernando' | |
194 |
|
194 | |||
195 | # Set argument defaults |
|
195 | # Set argument defaults | |
196 | app_name = 'IPython' |
|
196 | app_name = 'IPython' | |
197 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' |
|
197 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' | |
198 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] |
|
198 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] | |
199 | crash_report_fname = 'IPython_crash_report.txt' |
|
199 | crash_report_fname = 'IPython_crash_report.txt' | |
200 | # Call parent constructor |
|
200 | # Call parent constructor | |
201 | CrashHandler.__init__(self,IP,app_name,contact_name,contact_email, |
|
201 | CrashHandler.__init__(self,IP,app_name,contact_name,contact_email, | |
202 | bug_tracker,crash_report_fname) |
|
202 | bug_tracker,crash_report_fname) | |
203 |
|
203 | |||
204 | def make_report(self,traceback): |
|
204 | def make_report(self,traceback): | |
205 | """Return a string containing a crash report.""" |
|
205 | """Return a string containing a crash report.""" | |
206 |
|
206 | |||
207 | sec_sep = '\n\n'+'*'*75+'\n\n' |
|
207 | sec_sep = '\n\n'+'*'*75+'\n\n' | |
208 |
|
208 | |||
209 | report = [] |
|
209 | report = [] | |
210 | rpt_add = report.append |
|
210 | rpt_add = report.append | |
211 |
|
211 | |||
212 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
212 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') | |
213 | rpt_add('IPython version: %s \n\n' % release.version) |
|
213 | rpt_add('IPython version: %s \n\n' % release.version) | |
214 | rpt_add('BZR revision : %s \n\n' % release.revision) |
|
214 | rpt_add('BZR revision : %s \n\n' % release.revision) | |
215 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
215 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % | |
216 | (os.name,sys.platform) ) |
|
216 | (os.name,sys.platform) ) | |
217 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
217 | rpt_add(sec_sep+'Current user configuration structure:\n\n') | |
218 |
rpt_add(pformat(self.IP |
|
218 | # rpt_add(pformat(self.IP.dict())) | |
219 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
219 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) | |
220 | try: |
|
220 | try: | |
221 | rpt_add(sec_sep+"History of session input:") |
|
221 | rpt_add(sec_sep+"History of session input:") | |
222 | for line in self.IP.user_ns['_ih']: |
|
222 | for line in self.IP.user_ns['_ih']: | |
223 | rpt_add(line) |
|
223 | rpt_add(line) | |
224 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
224 | rpt_add('\n*** Last line of input (may not be in above history):\n') | |
225 | rpt_add(self.IP._last_input_line+'\n') |
|
225 | rpt_add(self.IP._last_input_line+'\n') | |
226 | except: |
|
226 | except: | |
227 | pass |
|
227 | pass | |
228 |
|
228 | |||
229 | return ''.join(report) |
|
229 | return ''.join(report) |
@@ -1,524 +1,524 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Pdb debugger class. |
|
3 | Pdb debugger class. | |
4 |
|
4 | |||
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that | |
6 | the command line completion of other programs which include this isn't |
|
6 | the command line completion of other programs which include this isn't | |
7 | damaged. |
|
7 | damaged. | |
8 |
|
8 | |||
9 | In the future, this class will be expanded with improvements over the standard |
|
9 | In the future, this class will be expanded with improvements over the standard | |
10 | pdb. |
|
10 | pdb. | |
11 |
|
11 | |||
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor | |
13 | changes. Licensing should therefore be under the standard Python terms. For |
|
13 | changes. Licensing should therefore be under the standard Python terms. For | |
14 | details on the PSF (Python Software Foundation) standard license, see: |
|
14 | details on the PSF (Python Software Foundation) standard license, see: | |
15 |
|
15 | |||
16 | http://www.python.org/2.2.3/license.html""" |
|
16 | http://www.python.org/2.2.3/license.html""" | |
17 |
|
17 | |||
18 | #***************************************************************************** |
|
18 | #***************************************************************************** | |
19 | # |
|
19 | # | |
20 | # This file is licensed under the PSF license. |
|
20 | # This file is licensed under the PSF license. | |
21 | # |
|
21 | # | |
22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
22 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> | |
24 | # |
|
24 | # | |
25 | # |
|
25 | # | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 |
|
27 | |||
28 | import bdb |
|
28 | import bdb | |
29 | import cmd |
|
29 | import cmd | |
30 | import linecache |
|
30 | import linecache | |
31 | import os |
|
31 | import os | |
32 | import sys |
|
32 | import sys | |
33 |
|
33 | |||
34 | from IPython.utils import PyColorize |
|
34 | from IPython.utils import PyColorize | |
35 | from IPython.core import ipapi |
|
35 | from IPython.core import ipapi | |
36 | from IPython.utils import coloransi |
|
36 | from IPython.utils import coloransi | |
37 | from IPython.utils.genutils import Term |
|
37 | from IPython.utils.genutils import Term | |
38 | from IPython.core.excolors import exception_colors |
|
38 | from IPython.core.excolors import exception_colors | |
39 |
|
39 | |||
40 | # See if we can use pydb. |
|
40 | # See if we can use pydb. | |
41 | has_pydb = False |
|
41 | has_pydb = False | |
42 | prompt = 'ipdb> ' |
|
42 | prompt = 'ipdb> ' | |
43 | #We have to check this directly from sys.argv, config struct not yet available |
|
43 | #We have to check this directly from sys.argv, config struct not yet available | |
44 | if '-pydb' in sys.argv: |
|
44 | if '-pydb' in sys.argv: | |
45 | try: |
|
45 | try: | |
46 | import pydb |
|
46 | import pydb | |
47 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': |
|
47 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': | |
48 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we |
|
48 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we | |
49 | # better protect against it. |
|
49 | # better protect against it. | |
50 | has_pydb = True |
|
50 | has_pydb = True | |
51 | except ImportError: |
|
51 | except ImportError: | |
52 | print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" |
|
52 | print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" | |
53 |
|
53 | |||
54 | if has_pydb: |
|
54 | if has_pydb: | |
55 | from pydb import Pdb as OldPdb |
|
55 | from pydb import Pdb as OldPdb | |
56 | #print "Using pydb for %run -d and post-mortem" #dbg |
|
56 | #print "Using pydb for %run -d and post-mortem" #dbg | |
57 | prompt = 'ipydb> ' |
|
57 | prompt = 'ipydb> ' | |
58 | else: |
|
58 | else: | |
59 | from pdb import Pdb as OldPdb |
|
59 | from pdb import Pdb as OldPdb | |
60 |
|
60 | |||
61 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
61 | # Allow the set_trace code to operate outside of an ipython instance, even if | |
62 | # it does so with some limitations. The rest of this support is implemented in |
|
62 | # it does so with some limitations. The rest of this support is implemented in | |
63 | # the Tracer constructor. |
|
63 | # the Tracer constructor. | |
64 | def BdbQuit_excepthook(et,ev,tb): |
|
64 | def BdbQuit_excepthook(et,ev,tb): | |
65 | if et==bdb.BdbQuit: |
|
65 | if et==bdb.BdbQuit: | |
66 | print 'Exiting Debugger.' |
|
66 | print 'Exiting Debugger.' | |
67 | else: |
|
67 | else: | |
68 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
68 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) | |
69 |
|
69 | |||
70 | def BdbQuit_IPython_excepthook(self,et,ev,tb): |
|
70 | def BdbQuit_IPython_excepthook(self,et,ev,tb): | |
71 | print 'Exiting Debugger.' |
|
71 | print 'Exiting Debugger.' | |
72 |
|
72 | |||
73 | class Tracer(object): |
|
73 | class Tracer(object): | |
74 | """Class for local debugging, similar to pdb.set_trace. |
|
74 | """Class for local debugging, similar to pdb.set_trace. | |
75 |
|
75 | |||
76 | Instances of this class, when called, behave like pdb.set_trace, but |
|
76 | Instances of this class, when called, behave like pdb.set_trace, but | |
77 | providing IPython's enhanced capabilities. |
|
77 | providing IPython's enhanced capabilities. | |
78 |
|
78 | |||
79 | This is implemented as a class which must be initialized in your own code |
|
79 | This is implemented as a class which must be initialized in your own code | |
80 | and not as a standalone function because we need to detect at runtime |
|
80 | and not as a standalone function because we need to detect at runtime | |
81 | whether IPython is already active or not. That detection is done in the |
|
81 | whether IPython is already active or not. That detection is done in the | |
82 | constructor, ensuring that this code plays nicely with a running IPython, |
|
82 | constructor, ensuring that this code plays nicely with a running IPython, | |
83 | while functioning acceptably (though with limitations) if outside of it. |
|
83 | while functioning acceptably (though with limitations) if outside of it. | |
84 | """ |
|
84 | """ | |
85 |
|
85 | |||
86 | def __init__(self,colors=None): |
|
86 | def __init__(self,colors=None): | |
87 | """Create a local debugger instance. |
|
87 | """Create a local debugger instance. | |
88 |
|
88 | |||
89 | :Parameters: |
|
89 | :Parameters: | |
90 |
|
90 | |||
91 | - `colors` (None): a string containing the name of the color scheme to |
|
91 | - `colors` (None): a string containing the name of the color scheme to | |
92 | use, it must be one of IPython's valid color schemes. If not given, the |
|
92 | use, it must be one of IPython's valid color schemes. If not given, the | |
93 | function will default to the current IPython scheme when running inside |
|
93 | function will default to the current IPython scheme when running inside | |
94 | IPython, and to 'NoColor' otherwise. |
|
94 | IPython, and to 'NoColor' otherwise. | |
95 |
|
95 | |||
96 | Usage example: |
|
96 | Usage example: | |
97 |
|
97 | |||
98 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
98 | from IPython.core.debugger import Tracer; debug_here = Tracer() | |
99 |
|
99 | |||
100 | ... later in your code |
|
100 | ... later in your code | |
101 | debug_here() # -> will open up the debugger at that point. |
|
101 | debug_here() # -> will open up the debugger at that point. | |
102 |
|
102 | |||
103 | Once the debugger activates, you can use all of its regular commands to |
|
103 | Once the debugger activates, you can use all of its regular commands to | |
104 | step through code, set breakpoints, etc. See the pdb documentation |
|
104 | step through code, set breakpoints, etc. See the pdb documentation | |
105 | from the Python standard library for usage details. |
|
105 | from the Python standard library for usage details. | |
106 | """ |
|
106 | """ | |
107 |
|
107 | |||
108 | global __IPYTHON__ |
|
108 | global __IPYTHON__ | |
109 | try: |
|
109 | try: | |
110 | __IPYTHON__ |
|
110 | __IPYTHON__ | |
111 | except NameError: |
|
111 | except NameError: | |
112 | # Outside of ipython, we set our own exception hook manually |
|
112 | # Outside of ipython, we set our own exception hook manually | |
113 |
__IPYTHON__ = ipapi.get( |
|
113 | __IPYTHON__ = ipapi.get() | |
114 | BdbQuit_excepthook.excepthook_ori = sys.excepthook |
|
114 | BdbQuit_excepthook.excepthook_ori = sys.excepthook | |
115 | sys.excepthook = BdbQuit_excepthook |
|
115 | sys.excepthook = BdbQuit_excepthook | |
116 | def_colors = 'NoColor' |
|
116 | def_colors = 'NoColor' | |
117 | try: |
|
117 | try: | |
118 | # Limited tab completion support |
|
118 | # Limited tab completion support | |
119 | import readline |
|
119 | import readline | |
120 | readline.parse_and_bind('tab: complete') |
|
120 | readline.parse_and_bind('tab: complete') | |
121 | except ImportError: |
|
121 | except ImportError: | |
122 | pass |
|
122 | pass | |
123 | else: |
|
123 | else: | |
124 | # In ipython, we use its custom exception handler mechanism |
|
124 | # In ipython, we use its custom exception handler mechanism | |
125 | ip = ipapi.get() |
|
125 | ip = ipapi.get() | |
126 |
def_colors = ip. |
|
126 | def_colors = ip.colors | |
127 | ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook) |
|
127 | ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook) | |
128 |
|
128 | |||
129 | if colors is None: |
|
129 | if colors is None: | |
130 | colors = def_colors |
|
130 | colors = def_colors | |
131 | self.debugger = Pdb(colors) |
|
131 | self.debugger = Pdb(colors) | |
132 |
|
132 | |||
133 | def __call__(self): |
|
133 | def __call__(self): | |
134 | """Starts an interactive debugger at the point where called. |
|
134 | """Starts an interactive debugger at the point where called. | |
135 |
|
135 | |||
136 | This is similar to the pdb.set_trace() function from the std lib, but |
|
136 | This is similar to the pdb.set_trace() function from the std lib, but | |
137 | using IPython's enhanced debugger.""" |
|
137 | using IPython's enhanced debugger.""" | |
138 |
|
138 | |||
139 | self.debugger.set_trace(sys._getframe().f_back) |
|
139 | self.debugger.set_trace(sys._getframe().f_back) | |
140 |
|
140 | |||
141 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
141 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): | |
142 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
142 | """Make new_fn have old_fn's doc string. This is particularly useful | |
143 | for the do_... commands that hook into the help system. |
|
143 | for the do_... commands that hook into the help system. | |
144 | Adapted from from a comp.lang.python posting |
|
144 | Adapted from from a comp.lang.python posting | |
145 | by Duncan Booth.""" |
|
145 | by Duncan Booth.""" | |
146 | def wrapper(*args, **kw): |
|
146 | def wrapper(*args, **kw): | |
147 | return new_fn(*args, **kw) |
|
147 | return new_fn(*args, **kw) | |
148 | if old_fn.__doc__: |
|
148 | if old_fn.__doc__: | |
149 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
149 | wrapper.__doc__ = old_fn.__doc__ + additional_text | |
150 | return wrapper |
|
150 | return wrapper | |
151 |
|
151 | |||
152 | def _file_lines(fname): |
|
152 | def _file_lines(fname): | |
153 | """Return the contents of a named file as a list of lines. |
|
153 | """Return the contents of a named file as a list of lines. | |
154 |
|
154 | |||
155 | This function never raises an IOError exception: if the file can't be |
|
155 | This function never raises an IOError exception: if the file can't be | |
156 | read, it simply returns an empty list.""" |
|
156 | read, it simply returns an empty list.""" | |
157 |
|
157 | |||
158 | try: |
|
158 | try: | |
159 | outfile = open(fname) |
|
159 | outfile = open(fname) | |
160 | except IOError: |
|
160 | except IOError: | |
161 | return [] |
|
161 | return [] | |
162 | else: |
|
162 | else: | |
163 | out = outfile.readlines() |
|
163 | out = outfile.readlines() | |
164 | outfile.close() |
|
164 | outfile.close() | |
165 | return out |
|
165 | return out | |
166 |
|
166 | |||
167 | class Pdb(OldPdb): |
|
167 | class Pdb(OldPdb): | |
168 | """Modified Pdb class, does not load readline.""" |
|
168 | """Modified Pdb class, does not load readline.""" | |
169 |
|
169 | |||
170 | if sys.version[:3] >= '2.5' or has_pydb: |
|
170 | if sys.version[:3] >= '2.5' or has_pydb: | |
171 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
171 | def __init__(self,color_scheme='NoColor',completekey=None, | |
172 | stdin=None, stdout=None): |
|
172 | stdin=None, stdout=None): | |
173 |
|
173 | |||
174 | # Parent constructor: |
|
174 | # Parent constructor: | |
175 | if has_pydb and completekey is None: |
|
175 | if has_pydb and completekey is None: | |
176 | OldPdb.__init__(self,stdin=stdin,stdout=Term.cout) |
|
176 | OldPdb.__init__(self,stdin=stdin,stdout=Term.cout) | |
177 | else: |
|
177 | else: | |
178 | OldPdb.__init__(self,completekey,stdin,stdout) |
|
178 | OldPdb.__init__(self,completekey,stdin,stdout) | |
179 |
|
179 | |||
180 | self.prompt = prompt # The default prompt is '(Pdb)' |
|
180 | self.prompt = prompt # The default prompt is '(Pdb)' | |
181 |
|
181 | |||
182 | # IPython changes... |
|
182 | # IPython changes... | |
183 | self.is_pydb = has_pydb |
|
183 | self.is_pydb = has_pydb | |
184 |
|
184 | |||
185 | if self.is_pydb: |
|
185 | if self.is_pydb: | |
186 |
|
186 | |||
187 | # iplib.py's ipalias seems to want pdb's checkline |
|
187 | # iplib.py's ipalias seems to want pdb's checkline | |
188 | # which located in pydb.fn |
|
188 | # which located in pydb.fn | |
189 | import pydb.fns |
|
189 | import pydb.fns | |
190 | self.checkline = lambda filename, lineno: \ |
|
190 | self.checkline = lambda filename, lineno: \ | |
191 | pydb.fns.checkline(self, filename, lineno) |
|
191 | pydb.fns.checkline(self, filename, lineno) | |
192 |
|
192 | |||
193 | self.curframe = None |
|
193 | self.curframe = None | |
194 | self.do_restart = self.new_do_restart |
|
194 | self.do_restart = self.new_do_restart | |
195 |
|
195 | |||
196 | self.old_all_completions = __IPYTHON__.Completer.all_completions |
|
196 | self.old_all_completions = __IPYTHON__.Completer.all_completions | |
197 | __IPYTHON__.Completer.all_completions=self.all_completions |
|
197 | __IPYTHON__.Completer.all_completions=self.all_completions | |
198 |
|
198 | |||
199 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, |
|
199 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, | |
200 | OldPdb.do_list) |
|
200 | OldPdb.do_list) | |
201 | self.do_l = self.do_list |
|
201 | self.do_l = self.do_list | |
202 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, |
|
202 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, | |
203 | OldPdb.do_frame) |
|
203 | OldPdb.do_frame) | |
204 |
|
204 | |||
205 | self.aliases = {} |
|
205 | self.aliases = {} | |
206 |
|
206 | |||
207 | # Create color table: we copy the default one from the traceback |
|
207 | # Create color table: we copy the default one from the traceback | |
208 | # module and add a few attributes needed for debugging |
|
208 | # module and add a few attributes needed for debugging | |
209 | self.color_scheme_table = exception_colors() |
|
209 | self.color_scheme_table = exception_colors() | |
210 |
|
210 | |||
211 | # shorthands |
|
211 | # shorthands | |
212 | C = coloransi.TermColors |
|
212 | C = coloransi.TermColors | |
213 | cst = self.color_scheme_table |
|
213 | cst = self.color_scheme_table | |
214 |
|
214 | |||
215 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
215 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
216 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
216 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
217 |
|
217 | |||
218 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
218 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
219 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
219 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
220 |
|
220 | |||
221 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
221 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
222 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
222 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
223 |
|
223 | |||
224 | self.set_colors(color_scheme) |
|
224 | self.set_colors(color_scheme) | |
225 |
|
225 | |||
226 | # Add a python parser so we can syntax highlight source while |
|
226 | # Add a python parser so we can syntax highlight source while | |
227 | # debugging. |
|
227 | # debugging. | |
228 | self.parser = PyColorize.Parser() |
|
228 | self.parser = PyColorize.Parser() | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | else: |
|
231 | else: | |
232 | # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor, |
|
232 | # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor, | |
233 | # because it binds readline and breaks tab-completion. This means we |
|
233 | # because it binds readline and breaks tab-completion. This means we | |
234 | # have to COPY the constructor here. |
|
234 | # have to COPY the constructor here. | |
235 | def __init__(self,color_scheme='NoColor'): |
|
235 | def __init__(self,color_scheme='NoColor'): | |
236 | bdb.Bdb.__init__(self) |
|
236 | bdb.Bdb.__init__(self) | |
237 | cmd.Cmd.__init__(self,completekey=None) # don't load readline |
|
237 | cmd.Cmd.__init__(self,completekey=None) # don't load readline | |
238 | self.prompt = 'ipdb> ' # The default prompt is '(Pdb)' |
|
238 | self.prompt = 'ipdb> ' # The default prompt is '(Pdb)' | |
239 | self.aliases = {} |
|
239 | self.aliases = {} | |
240 |
|
240 | |||
241 | # These two lines are part of the py2.4 constructor, let's put them |
|
241 | # These two lines are part of the py2.4 constructor, let's put them | |
242 | # unconditionally here as they won't cause any problems in 2.3. |
|
242 | # unconditionally here as they won't cause any problems in 2.3. | |
243 | self.mainpyfile = '' |
|
243 | self.mainpyfile = '' | |
244 | self._wait_for_mainpyfile = 0 |
|
244 | self._wait_for_mainpyfile = 0 | |
245 |
|
245 | |||
246 | # Read $HOME/.pdbrc and ./.pdbrc |
|
246 | # Read $HOME/.pdbrc and ./.pdbrc | |
247 | try: |
|
247 | try: | |
248 | self.rcLines = _file_lines(os.path.join(os.environ['HOME'], |
|
248 | self.rcLines = _file_lines(os.path.join(os.environ['HOME'], | |
249 | ".pdbrc")) |
|
249 | ".pdbrc")) | |
250 | except KeyError: |
|
250 | except KeyError: | |
251 | self.rcLines = [] |
|
251 | self.rcLines = [] | |
252 | self.rcLines.extend(_file_lines(".pdbrc")) |
|
252 | self.rcLines.extend(_file_lines(".pdbrc")) | |
253 |
|
253 | |||
254 | # Create color table: we copy the default one from the traceback |
|
254 | # Create color table: we copy the default one from the traceback | |
255 | # module and add a few attributes needed for debugging |
|
255 | # module and add a few attributes needed for debugging | |
256 | self.color_scheme_table = exception_colors() |
|
256 | self.color_scheme_table = exception_colors() | |
257 |
|
257 | |||
258 | # shorthands |
|
258 | # shorthands | |
259 | C = coloransi.TermColors |
|
259 | C = coloransi.TermColors | |
260 | cst = self.color_scheme_table |
|
260 | cst = self.color_scheme_table | |
261 |
|
261 | |||
262 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
262 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
263 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
263 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
264 |
|
264 | |||
265 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
265 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
266 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
266 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
267 |
|
267 | |||
268 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
268 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
269 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
269 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
270 |
|
270 | |||
271 | self.set_colors(color_scheme) |
|
271 | self.set_colors(color_scheme) | |
272 |
|
272 | |||
273 | # Add a python parser so we can syntax highlight source while |
|
273 | # Add a python parser so we can syntax highlight source while | |
274 | # debugging. |
|
274 | # debugging. | |
275 | self.parser = PyColorize.Parser() |
|
275 | self.parser = PyColorize.Parser() | |
276 |
|
276 | |||
277 | def set_colors(self, scheme): |
|
277 | def set_colors(self, scheme): | |
278 | """Shorthand access to the color table scheme selector method.""" |
|
278 | """Shorthand access to the color table scheme selector method.""" | |
279 | self.color_scheme_table.set_active_scheme(scheme) |
|
279 | self.color_scheme_table.set_active_scheme(scheme) | |
280 |
|
280 | |||
281 | def interaction(self, frame, traceback): |
|
281 | def interaction(self, frame, traceback): | |
282 | __IPYTHON__.set_completer_frame(frame) |
|
282 | __IPYTHON__.set_completer_frame(frame) | |
283 | OldPdb.interaction(self, frame, traceback) |
|
283 | OldPdb.interaction(self, frame, traceback) | |
284 |
|
284 | |||
285 | def new_do_up(self, arg): |
|
285 | def new_do_up(self, arg): | |
286 | OldPdb.do_up(self, arg) |
|
286 | OldPdb.do_up(self, arg) | |
287 | __IPYTHON__.set_completer_frame(self.curframe) |
|
287 | __IPYTHON__.set_completer_frame(self.curframe) | |
288 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
288 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) | |
289 |
|
289 | |||
290 | def new_do_down(self, arg): |
|
290 | def new_do_down(self, arg): | |
291 | OldPdb.do_down(self, arg) |
|
291 | OldPdb.do_down(self, arg) | |
292 | __IPYTHON__.set_completer_frame(self.curframe) |
|
292 | __IPYTHON__.set_completer_frame(self.curframe) | |
293 |
|
293 | |||
294 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
294 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) | |
295 |
|
295 | |||
296 | def new_do_frame(self, arg): |
|
296 | def new_do_frame(self, arg): | |
297 | OldPdb.do_frame(self, arg) |
|
297 | OldPdb.do_frame(self, arg) | |
298 | __IPYTHON__.set_completer_frame(self.curframe) |
|
298 | __IPYTHON__.set_completer_frame(self.curframe) | |
299 |
|
299 | |||
300 | def new_do_quit(self, arg): |
|
300 | def new_do_quit(self, arg): | |
301 |
|
301 | |||
302 | if hasattr(self, 'old_all_completions'): |
|
302 | if hasattr(self, 'old_all_completions'): | |
303 | __IPYTHON__.Completer.all_completions=self.old_all_completions |
|
303 | __IPYTHON__.Completer.all_completions=self.old_all_completions | |
304 |
|
304 | |||
305 |
|
305 | |||
306 | return OldPdb.do_quit(self, arg) |
|
306 | return OldPdb.do_quit(self, arg) | |
307 |
|
307 | |||
308 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
308 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) | |
309 |
|
309 | |||
310 | def new_do_restart(self, arg): |
|
310 | def new_do_restart(self, arg): | |
311 | """Restart command. In the context of ipython this is exactly the same |
|
311 | """Restart command. In the context of ipython this is exactly the same | |
312 | thing as 'quit'.""" |
|
312 | thing as 'quit'.""" | |
313 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
313 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") | |
314 | return self.do_quit(arg) |
|
314 | return self.do_quit(arg) | |
315 |
|
315 | |||
316 | def postloop(self): |
|
316 | def postloop(self): | |
317 | __IPYTHON__.set_completer_frame(None) |
|
317 | __IPYTHON__.set_completer_frame(None) | |
318 |
|
318 | |||
319 | def print_stack_trace(self): |
|
319 | def print_stack_trace(self): | |
320 | try: |
|
320 | try: | |
321 | for frame_lineno in self.stack: |
|
321 | for frame_lineno in self.stack: | |
322 | self.print_stack_entry(frame_lineno, context = 5) |
|
322 | self.print_stack_entry(frame_lineno, context = 5) | |
323 | except KeyboardInterrupt: |
|
323 | except KeyboardInterrupt: | |
324 | pass |
|
324 | pass | |
325 |
|
325 | |||
326 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
326 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', | |
327 | context = 3): |
|
327 | context = 3): | |
328 | #frame, lineno = frame_lineno |
|
328 | #frame, lineno = frame_lineno | |
329 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) |
|
329 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) | |
330 |
|
330 | |||
331 | # vds: >> |
|
331 | # vds: >> | |
332 | frame, lineno = frame_lineno |
|
332 | frame, lineno = frame_lineno | |
333 | filename = frame.f_code.co_filename |
|
333 | filename = frame.f_code.co_filename | |
334 | __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0) |
|
334 | __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0) | |
335 | # vds: << |
|
335 | # vds: << | |
336 |
|
336 | |||
337 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
337 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): | |
338 | import linecache, repr |
|
338 | import linecache, repr | |
339 |
|
339 | |||
340 | ret = [] |
|
340 | ret = [] | |
341 |
|
341 | |||
342 | Colors = self.color_scheme_table.active_colors |
|
342 | Colors = self.color_scheme_table.active_colors | |
343 | ColorsNormal = Colors.Normal |
|
343 | ColorsNormal = Colors.Normal | |
344 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
344 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) | |
345 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
345 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) | |
346 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
346 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
347 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
347 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, | |
348 | ColorsNormal) |
|
348 | ColorsNormal) | |
349 |
|
349 | |||
350 | frame, lineno = frame_lineno |
|
350 | frame, lineno = frame_lineno | |
351 |
|
351 | |||
352 | return_value = '' |
|
352 | return_value = '' | |
353 | if '__return__' in frame.f_locals: |
|
353 | if '__return__' in frame.f_locals: | |
354 | rv = frame.f_locals['__return__'] |
|
354 | rv = frame.f_locals['__return__'] | |
355 | #return_value += '->' |
|
355 | #return_value += '->' | |
356 | return_value += repr.repr(rv) + '\n' |
|
356 | return_value += repr.repr(rv) + '\n' | |
357 | ret.append(return_value) |
|
357 | ret.append(return_value) | |
358 |
|
358 | |||
359 | #s = filename + '(' + `lineno` + ')' |
|
359 | #s = filename + '(' + `lineno` + ')' | |
360 | filename = self.canonic(frame.f_code.co_filename) |
|
360 | filename = self.canonic(frame.f_code.co_filename) | |
361 | link = tpl_link % filename |
|
361 | link = tpl_link % filename | |
362 |
|
362 | |||
363 | if frame.f_code.co_name: |
|
363 | if frame.f_code.co_name: | |
364 | func = frame.f_code.co_name |
|
364 | func = frame.f_code.co_name | |
365 | else: |
|
365 | else: | |
366 | func = "<lambda>" |
|
366 | func = "<lambda>" | |
367 |
|
367 | |||
368 | call = '' |
|
368 | call = '' | |
369 | if func != '?': |
|
369 | if func != '?': | |
370 | if '__args__' in frame.f_locals: |
|
370 | if '__args__' in frame.f_locals: | |
371 | args = repr.repr(frame.f_locals['__args__']) |
|
371 | args = repr.repr(frame.f_locals['__args__']) | |
372 | else: |
|
372 | else: | |
373 | args = '()' |
|
373 | args = '()' | |
374 | call = tpl_call % (func, args) |
|
374 | call = tpl_call % (func, args) | |
375 |
|
375 | |||
376 | # The level info should be generated in the same format pdb uses, to |
|
376 | # The level info should be generated in the same format pdb uses, to | |
377 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
377 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. | |
378 | if frame is self.curframe: |
|
378 | if frame is self.curframe: | |
379 | ret.append('> ') |
|
379 | ret.append('> ') | |
380 | else: |
|
380 | else: | |
381 | ret.append(' ') |
|
381 | ret.append(' ') | |
382 | ret.append('%s(%s)%s\n' % (link,lineno,call)) |
|
382 | ret.append('%s(%s)%s\n' % (link,lineno,call)) | |
383 |
|
383 | |||
384 | start = lineno - 1 - context//2 |
|
384 | start = lineno - 1 - context//2 | |
385 | lines = linecache.getlines(filename) |
|
385 | lines = linecache.getlines(filename) | |
386 | start = max(start, 0) |
|
386 | start = max(start, 0) | |
387 | start = min(start, len(lines) - context) |
|
387 | start = min(start, len(lines) - context) | |
388 | lines = lines[start : start + context] |
|
388 | lines = lines[start : start + context] | |
389 |
|
389 | |||
390 | for i,line in enumerate(lines): |
|
390 | for i,line in enumerate(lines): | |
391 | show_arrow = (start + 1 + i == lineno) |
|
391 | show_arrow = (start + 1 + i == lineno) | |
392 | linetpl = (frame is self.curframe or show_arrow) \ |
|
392 | linetpl = (frame is self.curframe or show_arrow) \ | |
393 | and tpl_line_em \ |
|
393 | and tpl_line_em \ | |
394 | or tpl_line |
|
394 | or tpl_line | |
395 | ret.append(self.__format_line(linetpl, filename, |
|
395 | ret.append(self.__format_line(linetpl, filename, | |
396 | start + 1 + i, line, |
|
396 | start + 1 + i, line, | |
397 | arrow = show_arrow) ) |
|
397 | arrow = show_arrow) ) | |
398 |
|
398 | |||
399 | return ''.join(ret) |
|
399 | return ''.join(ret) | |
400 |
|
400 | |||
401 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
401 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): | |
402 | bp_mark = "" |
|
402 | bp_mark = "" | |
403 | bp_mark_color = "" |
|
403 | bp_mark_color = "" | |
404 |
|
404 | |||
405 | scheme = self.color_scheme_table.active_scheme_name |
|
405 | scheme = self.color_scheme_table.active_scheme_name | |
406 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
406 | new_line, err = self.parser.format2(line, 'str', scheme) | |
407 | if not err: line = new_line |
|
407 | if not err: line = new_line | |
408 |
|
408 | |||
409 | bp = None |
|
409 | bp = None | |
410 | if lineno in self.get_file_breaks(filename): |
|
410 | if lineno in self.get_file_breaks(filename): | |
411 | bps = self.get_breaks(filename, lineno) |
|
411 | bps = self.get_breaks(filename, lineno) | |
412 | bp = bps[-1] |
|
412 | bp = bps[-1] | |
413 |
|
413 | |||
414 | if bp: |
|
414 | if bp: | |
415 | Colors = self.color_scheme_table.active_colors |
|
415 | Colors = self.color_scheme_table.active_colors | |
416 | bp_mark = str(bp.number) |
|
416 | bp_mark = str(bp.number) | |
417 | bp_mark_color = Colors.breakpoint_enabled |
|
417 | bp_mark_color = Colors.breakpoint_enabled | |
418 | if not bp.enabled: |
|
418 | if not bp.enabled: | |
419 | bp_mark_color = Colors.breakpoint_disabled |
|
419 | bp_mark_color = Colors.breakpoint_disabled | |
420 |
|
420 | |||
421 | numbers_width = 7 |
|
421 | numbers_width = 7 | |
422 | if arrow: |
|
422 | if arrow: | |
423 | # This is the line with the error |
|
423 | # This is the line with the error | |
424 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
424 | pad = numbers_width - len(str(lineno)) - len(bp_mark) | |
425 | if pad >= 3: |
|
425 | if pad >= 3: | |
426 | marker = '-'*(pad-3) + '-> ' |
|
426 | marker = '-'*(pad-3) + '-> ' | |
427 | elif pad == 2: |
|
427 | elif pad == 2: | |
428 | marker = '> ' |
|
428 | marker = '> ' | |
429 | elif pad == 1: |
|
429 | elif pad == 1: | |
430 | marker = '>' |
|
430 | marker = '>' | |
431 | else: |
|
431 | else: | |
432 | marker = '' |
|
432 | marker = '' | |
433 | num = '%s%s' % (marker, str(lineno)) |
|
433 | num = '%s%s' % (marker, str(lineno)) | |
434 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
434 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
435 | else: |
|
435 | else: | |
436 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
436 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) | |
437 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
437 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
438 |
|
438 | |||
439 | return line |
|
439 | return line | |
440 |
|
440 | |||
441 | def list_command_pydb(self, arg): |
|
441 | def list_command_pydb(self, arg): | |
442 | """List command to use if we have a newer pydb installed""" |
|
442 | """List command to use if we have a newer pydb installed""" | |
443 | filename, first, last = OldPdb.parse_list_cmd(self, arg) |
|
443 | filename, first, last = OldPdb.parse_list_cmd(self, arg) | |
444 | if filename is not None: |
|
444 | if filename is not None: | |
445 | self.print_list_lines(filename, first, last) |
|
445 | self.print_list_lines(filename, first, last) | |
446 |
|
446 | |||
447 | def print_list_lines(self, filename, first, last): |
|
447 | def print_list_lines(self, filename, first, last): | |
448 | """The printing (as opposed to the parsing part of a 'list' |
|
448 | """The printing (as opposed to the parsing part of a 'list' | |
449 | command.""" |
|
449 | command.""" | |
450 | try: |
|
450 | try: | |
451 | Colors = self.color_scheme_table.active_colors |
|
451 | Colors = self.color_scheme_table.active_colors | |
452 | ColorsNormal = Colors.Normal |
|
452 | ColorsNormal = Colors.Normal | |
453 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
453 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
454 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
454 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) | |
455 | src = [] |
|
455 | src = [] | |
456 | for lineno in range(first, last+1): |
|
456 | for lineno in range(first, last+1): | |
457 | line = linecache.getline(filename, lineno) |
|
457 | line = linecache.getline(filename, lineno) | |
458 | if not line: |
|
458 | if not line: | |
459 | break |
|
459 | break | |
460 |
|
460 | |||
461 | if lineno == self.curframe.f_lineno: |
|
461 | if lineno == self.curframe.f_lineno: | |
462 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
462 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) | |
463 | else: |
|
463 | else: | |
464 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
464 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) | |
465 |
|
465 | |||
466 | src.append(line) |
|
466 | src.append(line) | |
467 | self.lineno = lineno |
|
467 | self.lineno = lineno | |
468 |
|
468 | |||
469 | print >>Term.cout, ''.join(src) |
|
469 | print >>Term.cout, ''.join(src) | |
470 |
|
470 | |||
471 | except KeyboardInterrupt: |
|
471 | except KeyboardInterrupt: | |
472 | pass |
|
472 | pass | |
473 |
|
473 | |||
474 | def do_list(self, arg): |
|
474 | def do_list(self, arg): | |
475 | self.lastcmd = 'list' |
|
475 | self.lastcmd = 'list' | |
476 | last = None |
|
476 | last = None | |
477 | if arg: |
|
477 | if arg: | |
478 | try: |
|
478 | try: | |
479 | x = eval(arg, {}, {}) |
|
479 | x = eval(arg, {}, {}) | |
480 | if type(x) == type(()): |
|
480 | if type(x) == type(()): | |
481 | first, last = x |
|
481 | first, last = x | |
482 | first = int(first) |
|
482 | first = int(first) | |
483 | last = int(last) |
|
483 | last = int(last) | |
484 | if last < first: |
|
484 | if last < first: | |
485 | # Assume it's a count |
|
485 | # Assume it's a count | |
486 | last = first + last |
|
486 | last = first + last | |
487 | else: |
|
487 | else: | |
488 | first = max(1, int(x) - 5) |
|
488 | first = max(1, int(x) - 5) | |
489 | except: |
|
489 | except: | |
490 | print '*** Error in argument:', `arg` |
|
490 | print '*** Error in argument:', `arg` | |
491 | return |
|
491 | return | |
492 | elif self.lineno is None: |
|
492 | elif self.lineno is None: | |
493 | first = max(1, self.curframe.f_lineno - 5) |
|
493 | first = max(1, self.curframe.f_lineno - 5) | |
494 | else: |
|
494 | else: | |
495 | first = self.lineno + 1 |
|
495 | first = self.lineno + 1 | |
496 | if last is None: |
|
496 | if last is None: | |
497 | last = first + 10 |
|
497 | last = first + 10 | |
498 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
498 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) | |
499 |
|
499 | |||
500 | # vds: >> |
|
500 | # vds: >> | |
501 | lineno = first |
|
501 | lineno = first | |
502 | filename = self.curframe.f_code.co_filename |
|
502 | filename = self.curframe.f_code.co_filename | |
503 | __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0) |
|
503 | __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0) | |
504 | # vds: << |
|
504 | # vds: << | |
505 |
|
505 | |||
506 | do_l = do_list |
|
506 | do_l = do_list | |
507 |
|
507 | |||
508 | def do_pdef(self, arg): |
|
508 | def do_pdef(self, arg): | |
509 | """The debugger interface to magic_pdef""" |
|
509 | """The debugger interface to magic_pdef""" | |
510 | namespaces = [('Locals', self.curframe.f_locals), |
|
510 | namespaces = [('Locals', self.curframe.f_locals), | |
511 | ('Globals', self.curframe.f_globals)] |
|
511 | ('Globals', self.curframe.f_globals)] | |
512 | __IPYTHON__.magic_pdef(arg, namespaces=namespaces) |
|
512 | __IPYTHON__.magic_pdef(arg, namespaces=namespaces) | |
513 |
|
513 | |||
514 | def do_pdoc(self, arg): |
|
514 | def do_pdoc(self, arg): | |
515 | """The debugger interface to magic_pdoc""" |
|
515 | """The debugger interface to magic_pdoc""" | |
516 | namespaces = [('Locals', self.curframe.f_locals), |
|
516 | namespaces = [('Locals', self.curframe.f_locals), | |
517 | ('Globals', self.curframe.f_globals)] |
|
517 | ('Globals', self.curframe.f_globals)] | |
518 | __IPYTHON__.magic_pdoc(arg, namespaces=namespaces) |
|
518 | __IPYTHON__.magic_pdoc(arg, namespaces=namespaces) | |
519 |
|
519 | |||
520 | def do_pinfo(self, arg): |
|
520 | def do_pinfo(self, arg): | |
521 | """The debugger equivalant of ?obj""" |
|
521 | """The debugger equivalant of ?obj""" | |
522 | namespaces = [('Locals', self.curframe.f_locals), |
|
522 | namespaces = [('Locals', self.curframe.f_locals), | |
523 | ('Globals', self.curframe.f_globals)] |
|
523 | ('Globals', self.curframe.f_globals)] | |
524 | __IPYTHON__.magic_pinfo("pinfo %s" % arg, namespaces=namespaces) |
|
524 | __IPYTHON__.magic_pinfo("pinfo %s" % arg, namespaces=namespaces) |
@@ -1,257 +1,254 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ History related magics and functionality """ |
|
2 | """ History related magics and functionality """ | |
3 |
|
3 | |||
4 | # Stdlib imports |
|
4 | # Stdlib imports | |
5 | import fnmatch |
|
5 | import fnmatch | |
6 | import os |
|
6 | import os | |
7 |
|
7 | |||
8 | from IPython.utils.genutils import Term, ask_yes_no, warn |
|
8 | from IPython.utils.genutils import Term, ask_yes_no, warn | |
9 | from IPython.core import ipapi |
|
9 | from IPython.core import ipapi | |
10 |
|
10 | |||
11 | def magic_history(self, parameter_s = ''): |
|
11 | def magic_history(self, parameter_s = ''): | |
12 | """Print input history (_i<n> variables), with most recent last. |
|
12 | """Print input history (_i<n> variables), with most recent last. | |
13 |
|
13 | |||
14 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
14 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
15 | %history n -> print at most n inputs\\ |
|
15 | %history n -> print at most n inputs\\ | |
16 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
16 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
17 |
|
17 | |||
18 | Each input's number <n> is shown, and is accessible as the |
|
18 | Each input's number <n> is shown, and is accessible as the | |
19 | automatically generated variable _i<n>. Multi-line statements are |
|
19 | automatically generated variable _i<n>. Multi-line statements are | |
20 | printed starting at a new line for easy copy/paste. |
|
20 | printed starting at a new line for easy copy/paste. | |
21 |
|
21 | |||
22 |
|
22 | |||
23 | Options: |
|
23 | Options: | |
24 |
|
24 | |||
25 | -n: do NOT print line numbers. This is useful if you want to get a |
|
25 | -n: do NOT print line numbers. This is useful if you want to get a | |
26 | printout of many lines which can be directly pasted into a text |
|
26 | printout of many lines which can be directly pasted into a text | |
27 | editor. |
|
27 | editor. | |
28 |
|
28 | |||
29 | This feature is only available if numbered prompts are in use. |
|
29 | This feature is only available if numbered prompts are in use. | |
30 |
|
30 | |||
31 | -t: (default) print the 'translated' history, as IPython understands it. |
|
31 | -t: (default) print the 'translated' history, as IPython understands it. | |
32 | IPython filters your input and converts it all into valid Python source |
|
32 | IPython filters your input and converts it all into valid Python source | |
33 | before executing it (things like magics or aliases are turned into |
|
33 | before executing it (things like magics or aliases are turned into | |
34 | function calls, for example). With this option, you'll see the native |
|
34 | function calls, for example). With this option, you'll see the native | |
35 | history instead of the user-entered version: '%cd /' will be seen as |
|
35 | history instead of the user-entered version: '%cd /' will be seen as | |
36 | '_ip.magic("%cd /")' instead of '%cd /'. |
|
36 | '_ip.magic("%cd /")' instead of '%cd /'. | |
37 |
|
37 | |||
38 | -r: print the 'raw' history, i.e. the actual commands you typed. |
|
38 | -r: print the 'raw' history, i.e. the actual commands you typed. | |
39 |
|
39 | |||
40 | -g: treat the arg as a pattern to grep for in (full) history. |
|
40 | -g: treat the arg as a pattern to grep for in (full) history. | |
41 | This includes the "shadow history" (almost all commands ever written). |
|
41 | This includes the "shadow history" (almost all commands ever written). | |
42 | Use '%hist -g' to show full shadow history (may be very long). |
|
42 | Use '%hist -g' to show full shadow history (may be very long). | |
43 | In shadow history, every index nuwber starts with 0. |
|
43 | In shadow history, every index nuwber starts with 0. | |
44 |
|
44 | |||
45 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
45 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
46 | the given file. The file is always overwritten, though IPython asks for |
|
46 | the given file. The file is always overwritten, though IPython asks for | |
47 | confirmation first if it already exists. |
|
47 | confirmation first if it already exists. | |
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | ip = self.api |
|
50 | if not self.outputcache.do_full_cache: | |
51 | shell = self.shell |
|
|||
52 | if not shell.outputcache.do_full_cache: |
|
|||
53 | print 'This feature is only available if numbered prompts are in use.' |
|
51 | print 'This feature is only available if numbered prompts are in use.' | |
54 | return |
|
52 | return | |
55 | opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list') |
|
53 | opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list') | |
56 |
|
54 | |||
57 | # Check if output to specific file was requested. |
|
55 | # Check if output to specific file was requested. | |
58 | try: |
|
56 | try: | |
59 | outfname = opts['f'] |
|
57 | outfname = opts['f'] | |
60 | except KeyError: |
|
58 | except KeyError: | |
61 | outfile = Term.cout # default |
|
59 | outfile = Term.cout # default | |
62 | # We don't want to close stdout at the end! |
|
60 | # We don't want to close stdout at the end! | |
63 | close_at_end = False |
|
61 | close_at_end = False | |
64 | else: |
|
62 | else: | |
65 | if os.path.exists(outfname): |
|
63 | if os.path.exists(outfname): | |
66 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
64 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
67 | print 'Aborting.' |
|
65 | print 'Aborting.' | |
68 | return |
|
66 | return | |
69 |
|
67 | |||
70 | outfile = open(outfname,'w') |
|
68 | outfile = open(outfname,'w') | |
71 | close_at_end = True |
|
69 | close_at_end = True | |
72 |
|
70 | |||
73 | if 't' in opts: |
|
71 | if 't' in opts: | |
74 |
input_hist = s |
|
72 | input_hist = self.input_hist | |
75 | elif 'r' in opts: |
|
73 | elif 'r' in opts: | |
76 |
input_hist = s |
|
74 | input_hist = self.input_hist_raw | |
77 | else: |
|
75 | else: | |
78 |
input_hist = s |
|
76 | input_hist = self.input_hist | |
79 |
|
77 | |||
80 | default_length = 40 |
|
78 | default_length = 40 | |
81 | pattern = None |
|
79 | pattern = None | |
82 | if 'g' in opts: |
|
80 | if 'g' in opts: | |
83 | init = 1 |
|
81 | init = 1 | |
84 | final = len(input_hist) |
|
82 | final = len(input_hist) | |
85 | parts = parameter_s.split(None,1) |
|
83 | parts = parameter_s.split(None,1) | |
86 | if len(parts) == 1: |
|
84 | if len(parts) == 1: | |
87 | parts += '*' |
|
85 | parts += '*' | |
88 | head, pattern = parts |
|
86 | head, pattern = parts | |
89 | pattern = "*" + pattern + "*" |
|
87 | pattern = "*" + pattern + "*" | |
90 | elif len(args) == 0: |
|
88 | elif len(args) == 0: | |
91 | final = len(input_hist) |
|
89 | final = len(input_hist) | |
92 | init = max(1,final-default_length) |
|
90 | init = max(1,final-default_length) | |
93 | elif len(args) == 1: |
|
91 | elif len(args) == 1: | |
94 | final = len(input_hist) |
|
92 | final = len(input_hist) | |
95 | init = max(1,final-int(args[0])) |
|
93 | init = max(1,final-int(args[0])) | |
96 | elif len(args) == 2: |
|
94 | elif len(args) == 2: | |
97 | init,final = map(int,args) |
|
95 | init,final = map(int,args) | |
98 | else: |
|
96 | else: | |
99 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
97 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
100 | print self.magic_hist.__doc__ |
|
98 | print self.magic_hist.__doc__ | |
101 | return |
|
99 | return | |
102 | width = len(str(final)) |
|
100 | width = len(str(final)) | |
103 | line_sep = ['','\n'] |
|
101 | line_sep = ['','\n'] | |
104 | print_nums = not opts.has_key('n') |
|
102 | print_nums = not opts.has_key('n') | |
105 |
|
103 | |||
106 | found = False |
|
104 | found = False | |
107 | if pattern is not None: |
|
105 | if pattern is not None: | |
108 |
sh = |
|
106 | sh = self.shadowhist.all() | |
109 | for idx, s in sh: |
|
107 | for idx, s in sh: | |
110 | if fnmatch.fnmatch(s, pattern): |
|
108 | if fnmatch.fnmatch(s, pattern): | |
111 | print "0%d: %s" %(idx, s) |
|
109 | print "0%d: %s" %(idx, s) | |
112 | found = True |
|
110 | found = True | |
113 |
|
111 | |||
114 | if found: |
|
112 | if found: | |
115 | print "===" |
|
113 | print "===" | |
116 | print "shadow history ends, fetch by %rep <number> (must start with 0)" |
|
114 | print "shadow history ends, fetch by %rep <number> (must start with 0)" | |
117 | print "=== start of normal history ===" |
|
115 | print "=== start of normal history ===" | |
118 |
|
116 | |||
119 | for in_num in range(init,final): |
|
117 | for in_num in range(init,final): | |
120 | inline = input_hist[in_num] |
|
118 | inline = input_hist[in_num] | |
121 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
119 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | |
122 | continue |
|
120 | continue | |
123 |
|
121 | |||
124 | multiline = int(inline.count('\n') > 1) |
|
122 | multiline = int(inline.count('\n') > 1) | |
125 | if print_nums: |
|
123 | if print_nums: | |
126 | print >> outfile, \ |
|
124 | print >> outfile, \ | |
127 | '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), |
|
125 | '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), | |
128 | print >> outfile, inline, |
|
126 | print >> outfile, inline, | |
129 |
|
127 | |||
130 | if close_at_end: |
|
128 | if close_at_end: | |
131 | outfile.close() |
|
129 | outfile.close() | |
132 |
|
130 | |||
133 |
|
131 | |||
134 | def magic_hist(self, parameter_s=''): |
|
132 | def magic_hist(self, parameter_s=''): | |
135 | """Alternate name for %history.""" |
|
133 | """Alternate name for %history.""" | |
136 | return self.magic_history(parameter_s) |
|
134 | return self.magic_history(parameter_s) | |
137 |
|
135 | |||
138 |
|
136 | |||
139 | def rep_f(self, arg): |
|
137 | def rep_f(self, arg): | |
140 | r""" Repeat a command, or get command to input line for editing |
|
138 | r""" Repeat a command, or get command to input line for editing | |
141 |
|
139 | |||
142 | - %rep (no arguments): |
|
140 | - %rep (no arguments): | |
143 |
|
141 | |||
144 | Place a string version of last computation result (stored in the special '_' |
|
142 | Place a string version of last computation result (stored in the special '_' | |
145 | variable) to the next input prompt. Allows you to create elaborate command |
|
143 | variable) to the next input prompt. Allows you to create elaborate command | |
146 | lines without using copy-paste:: |
|
144 | lines without using copy-paste:: | |
147 |
|
145 | |||
148 | $ l = ["hei", "vaan"] |
|
146 | $ l = ["hei", "vaan"] | |
149 | $ "".join(l) |
|
147 | $ "".join(l) | |
150 | ==> heivaan |
|
148 | ==> heivaan | |
151 | $ %rep |
|
149 | $ %rep | |
152 | $ heivaan_ <== cursor blinking |
|
150 | $ heivaan_ <== cursor blinking | |
153 |
|
151 | |||
154 | %rep 45 |
|
152 | %rep 45 | |
155 |
|
153 | |||
156 | Place history line 45 to next input prompt. Use %hist to find out the |
|
154 | Place history line 45 to next input prompt. Use %hist to find out the | |
157 | number. |
|
155 | number. | |
158 |
|
156 | |||
159 | %rep 1-4 6-7 3 |
|
157 | %rep 1-4 6-7 3 | |
160 |
|
158 | |||
161 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
159 | Repeat the specified lines immediately. Input slice syntax is the same as | |
162 | in %macro and %save. |
|
160 | in %macro and %save. | |
163 |
|
161 | |||
164 | %rep foo |
|
162 | %rep foo | |
165 |
|
163 | |||
166 | Place the most recent line that has the substring "foo" to next input. |
|
164 | Place the most recent line that has the substring "foo" to next input. | |
167 | (e.g. 'svn ci -m foobar'). |
|
165 | (e.g. 'svn ci -m foobar'). | |
168 | """ |
|
166 | """ | |
169 |
|
167 | |||
170 | opts,args = self.parse_options(arg,'',mode='list') |
|
168 | opts,args = self.parse_options(arg,'',mode='list') | |
171 | ip = self.api |
|
|||
172 | if not args: |
|
169 | if not args: | |
173 |
|
|
170 | self.set_next_input(str(self.user_ns["_"])) | |
174 | return |
|
171 | return | |
175 |
|
172 | |||
176 | if len(args) == 1 and not '-' in args[0]: |
|
173 | if len(args) == 1 and not '-' in args[0]: | |
177 | arg = args[0] |
|
174 | arg = args[0] | |
178 | if len(arg) > 1 and arg.startswith('0'): |
|
175 | if len(arg) > 1 and arg.startswith('0'): | |
179 | # get from shadow hist |
|
176 | # get from shadow hist | |
180 | num = int(arg[1:]) |
|
177 | num = int(arg[1:]) | |
181 | line = self.shadowhist.get(num) |
|
178 | line = self.shadowhist.get(num) | |
182 |
|
|
179 | self.set_next_input(str(line)) | |
183 | return |
|
180 | return | |
184 | try: |
|
181 | try: | |
185 | num = int(args[0]) |
|
182 | num = int(args[0]) | |
186 |
|
|
183 | self.set_next_input(str(self.input_hist_raw[num]).rstrip()) | |
187 | return |
|
184 | return | |
188 | except ValueError: |
|
185 | except ValueError: | |
189 | pass |
|
186 | pass | |
190 |
|
187 | |||
191 |
for h in reversed(self. |
|
188 | for h in reversed(self.input_hist_raw): | |
192 | if 'rep' in h: |
|
189 | if 'rep' in h: | |
193 | continue |
|
190 | continue | |
194 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
191 | if fnmatch.fnmatch(h,'*' + arg + '*'): | |
195 |
|
|
192 | self.set_next_input(str(h).rstrip()) | |
196 | return |
|
193 | return | |
197 |
|
194 | |||
198 | try: |
|
195 | try: | |
199 | lines = self.extract_input_slices(args, True) |
|
196 | lines = self.extract_input_slices(args, True) | |
200 | print "lines",lines |
|
197 | print "lines",lines | |
201 |
|
|
198 | self.runlines(lines) | |
202 | except ValueError: |
|
199 | except ValueError: | |
203 | print "Not found in recent history:", args |
|
200 | print "Not found in recent history:", args | |
204 |
|
201 | |||
205 |
|
202 | |||
206 | _sentinel = object() |
|
203 | _sentinel = object() | |
207 |
|
204 | |||
208 | class ShadowHist: |
|
205 | class ShadowHist(object): | |
209 | def __init__(self,db): |
|
206 | def __init__(self,db): | |
210 | # cmd => idx mapping |
|
207 | # cmd => idx mapping | |
211 | self.curidx = 0 |
|
208 | self.curidx = 0 | |
212 | self.db = db |
|
209 | self.db = db | |
213 | self.disabled = False |
|
210 | self.disabled = False | |
214 |
|
211 | |||
215 | def inc_idx(self): |
|
212 | def inc_idx(self): | |
216 | idx = self.db.get('shadowhist_idx', 1) |
|
213 | idx = self.db.get('shadowhist_idx', 1) | |
217 | self.db['shadowhist_idx'] = idx + 1 |
|
214 | self.db['shadowhist_idx'] = idx + 1 | |
218 | return idx |
|
215 | return idx | |
219 |
|
216 | |||
220 | def add(self, ent): |
|
217 | def add(self, ent): | |
221 | if self.disabled: |
|
218 | if self.disabled: | |
222 | return |
|
219 | return | |
223 | try: |
|
220 | try: | |
224 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
221 | old = self.db.hget('shadowhist', ent, _sentinel) | |
225 | if old is not _sentinel: |
|
222 | if old is not _sentinel: | |
226 | return |
|
223 | return | |
227 | newidx = self.inc_idx() |
|
224 | newidx = self.inc_idx() | |
228 | #print "new",newidx # dbg |
|
225 | #print "new",newidx # dbg | |
229 | self.db.hset('shadowhist',ent, newidx) |
|
226 | self.db.hset('shadowhist',ent, newidx) | |
230 | except: |
|
227 | except: | |
231 |
ipapi.get(). |
|
228 | ipapi.get().showtraceback() | |
232 | print "WARNING: disabling shadow history" |
|
229 | print "WARNING: disabling shadow history" | |
233 | self.disabled = True |
|
230 | self.disabled = True | |
234 |
|
231 | |||
235 | def all(self): |
|
232 | def all(self): | |
236 | d = self.db.hdict('shadowhist') |
|
233 | d = self.db.hdict('shadowhist') | |
237 | items = [(i,s) for (s,i) in d.items()] |
|
234 | items = [(i,s) for (s,i) in d.items()] | |
238 | items.sort() |
|
235 | items.sort() | |
239 | return items |
|
236 | return items | |
240 |
|
237 | |||
241 | def get(self, idx): |
|
238 | def get(self, idx): | |
242 | all = self.all() |
|
239 | all = self.all() | |
243 |
|
240 | |||
244 | for k, v in all: |
|
241 | for k, v in all: | |
245 | #print k,v |
|
242 | #print k,v | |
246 | if k == idx: |
|
243 | if k == idx: | |
247 | return v |
|
244 | return v | |
248 |
|
245 | |||
249 |
|
246 | |||
250 | def init_ipython(ip): |
|
247 | def init_ipython(ip): | |
251 | import ipy_completers |
|
248 | import ipy_completers | |
252 |
|
249 | |||
253 |
ip. |
|
250 | ip.define_magic("rep",rep_f) | |
254 |
ip. |
|
251 | ip.define_magic("hist",magic_hist) | |
255 |
ip. |
|
252 | ip.define_magic("history",magic_history) | |
256 |
|
253 | |||
257 | ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
254 | ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,266 +1,274 b'' | |||||
1 | """hooks for IPython. |
|
1 | """hooks for IPython. | |
2 |
|
2 | |||
3 | In Python, it is possible to overwrite any method of any object if you really |
|
3 | In Python, it is possible to overwrite any method of any object if you really | |
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to | |
5 | be overwritten by users for customization purposes. This module defines the |
|
5 | be overwritten by users for customization purposes. This module defines the | |
6 | default versions of all such hooks, which get used by IPython if not |
|
6 | default versions of all such hooks, which get used by IPython if not | |
7 | overridden by the user. |
|
7 | overridden by the user. | |
8 |
|
8 | |||
9 | hooks are simple functions, but they should be declared with 'self' as their |
|
9 | hooks are simple functions, but they should be declared with 'self' as their | |
10 | first argument, because when activated they are registered into IPython as |
|
10 | first argument, because when activated they are registered into IPython as | |
11 | instance methods. The self argument will be the IPython running instance |
|
11 | instance methods. The self argument will be the IPython running instance | |
12 | itself, so hooks have full access to the entire IPython object. |
|
12 | itself, so hooks have full access to the entire IPython object. | |
13 |
|
13 | |||
14 | If you wish to define a new hook and activate it, you need to put the |
|
14 | If you wish to define a new hook and activate it, you need to put the | |
15 | necessary code into a python file which can be either imported or execfile()'d |
|
15 | necessary code into a python file which can be either imported or execfile()'d | |
16 | from within your ipythonrc configuration. |
|
16 | from within your ipythonrc configuration. | |
17 |
|
17 | |||
18 | For example, suppose that you have a module called 'myiphooks' in your |
|
18 | For example, suppose that you have a module called 'myiphooks' in your | |
19 | PYTHONPATH, which contains the following definition: |
|
19 | PYTHONPATH, which contains the following definition: | |
20 |
|
20 | |||
21 | import os |
|
21 | import os | |
22 | from IPython.core import ipapi |
|
22 | from IPython.core import ipapi | |
23 | ip = ipapi.get() |
|
23 | ip = ipapi.get() | |
24 |
|
24 | |||
25 | def calljed(self,filename, linenum): |
|
25 | def calljed(self,filename, linenum): | |
26 | "My editor hook calls the jed editor directly." |
|
26 | "My editor hook calls the jed editor directly." | |
27 | print "Calling my own editor, jed ..." |
|
27 | print "Calling my own editor, jed ..." | |
28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: |
|
28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: | |
29 |
raise |
|
29 | raise TryNext() | |
30 |
|
30 | |||
31 | ip.set_hook('editor', calljed) |
|
31 | ip.set_hook('editor', calljed) | |
32 |
|
32 | |||
33 | You can then enable the functionality by doing 'import myiphooks' |
|
33 | You can then enable the functionality by doing 'import myiphooks' | |
34 | somewhere in your configuration files or ipython command line. |
|
34 | somewhere in your configuration files or ipython command line. | |
35 | """ |
|
35 | """ | |
36 |
|
36 | |||
37 | #***************************************************************************** |
|
37 | #***************************************************************************** | |
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> | |
39 | # |
|
39 | # | |
40 | # Distributed under the terms of the BSD License. The full license is in |
|
40 | # Distributed under the terms of the BSD License. The full license is in | |
41 | # the file COPYING, distributed as part of this software. |
|
41 | # the file COPYING, distributed as part of this software. | |
42 | #***************************************************************************** |
|
42 | #***************************************************************************** | |
43 |
|
43 | |||
44 | from IPython.core import ipapi |
|
|||
45 |
|
||||
46 | import os, bisect |
|
44 | import os, bisect | |
47 | import sys |
|
45 | import sys | |
48 | from IPython.utils.genutils import Term, shell |
|
46 | from IPython.utils.genutils import Term, shell | |
49 | from pprint import PrettyPrinter |
|
47 | from pprint import PrettyPrinter | |
50 |
|
48 | |||
|
49 | from IPython.core.error import TryNext | |||
|
50 | ||||
51 | # List here all the default hooks. For now it's just the editor functions |
|
51 | # List here all the default hooks. For now it's just the editor functions | |
52 | # but over time we'll move here all the public API for user-accessible things. |
|
52 | # but over time we'll move here all the public API for user-accessible things. | |
53 | # vds: >> |
|
53 | ||
54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', |
|
54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', | |
55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', | |
56 | 'generate_prompt', 'generate_output_prompt','shell_hook', |
|
56 | 'generate_prompt', 'generate_output_prompt','shell_hook', | |
57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', |
|
57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', | |
58 | 'clipboard_get'] |
|
58 | 'clipboard_get'] | |
59 | # vds: << |
|
|||
60 |
|
59 | |||
61 | pformat = PrettyPrinter().pformat |
|
60 | pformat = PrettyPrinter().pformat | |
62 |
|
61 | |||
63 | def editor(self,filename, linenum=None): |
|
62 | def editor(self,filename, linenum=None): | |
64 | """Open the default editor at the given filename and linenumber. |
|
63 | """Open the default editor at the given filename and linenumber. | |
65 |
|
64 | |||
66 | This is IPython's default editor hook, you can use it as an example to |
|
65 | This is IPython's default editor hook, you can use it as an example to | |
67 | write your own modified one. To set your own editor function as the |
|
66 | write your own modified one. To set your own editor function as the | |
68 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
67 | new editor hook, call ip.set_hook('editor',yourfunc).""" | |
69 |
|
68 | |||
70 | # IPython configures a default editor at startup by reading $EDITOR from |
|
69 | # IPython configures a default editor at startup by reading $EDITOR from | |
71 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
70 | # the environment, and falling back on vi (unix) or notepad (win32). | |
72 |
editor = self. |
|
71 | editor = self.editor | |
73 |
|
72 | |||
74 | # marker for at which line to open the file (for existing objects) |
|
73 | # marker for at which line to open the file (for existing objects) | |
75 | if linenum is None or editor=='notepad': |
|
74 | if linenum is None or editor=='notepad': | |
76 | linemark = '' |
|
75 | linemark = '' | |
77 | else: |
|
76 | else: | |
78 | linemark = '+%d' % int(linenum) |
|
77 | linemark = '+%d' % int(linenum) | |
79 |
|
78 | |||
80 | # Enclose in quotes if necessary and legal |
|
79 | # Enclose in quotes if necessary and legal | |
81 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
80 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': | |
82 | editor = '"%s"' % editor |
|
81 | editor = '"%s"' % editor | |
83 |
|
82 | |||
84 | # Call the actual editor |
|
83 | # Call the actual editor | |
85 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
84 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: | |
86 |
raise |
|
85 | raise TryNext() | |
87 |
|
86 | |||
88 | import tempfile |
|
87 | import tempfile | |
89 | def fix_error_editor(self,filename,linenum,column,msg): |
|
88 | def fix_error_editor(self,filename,linenum,column,msg): | |
90 | """Open the editor at the given filename, linenumber, column and |
|
89 | """Open the editor at the given filename, linenumber, column and | |
91 | show an error message. This is used for correcting syntax errors. |
|
90 | show an error message. This is used for correcting syntax errors. | |
92 | The current implementation only has special support for the VIM editor, |
|
91 | The current implementation only has special support for the VIM editor, | |
93 | and falls back on the 'editor' hook if VIM is not used. |
|
92 | and falls back on the 'editor' hook if VIM is not used. | |
94 |
|
93 | |||
95 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
94 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, | |
96 | """ |
|
95 | """ | |
97 | def vim_quickfix_file(): |
|
96 | def vim_quickfix_file(): | |
98 | t = tempfile.NamedTemporaryFile() |
|
97 | t = tempfile.NamedTemporaryFile() | |
99 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
98 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) | |
100 | t.flush() |
|
99 | t.flush() | |
101 | return t |
|
100 | return t | |
102 |
if os.path.basename(self. |
|
101 | if os.path.basename(self.editor) != 'vim': | |
103 | self.hooks.editor(filename,linenum) |
|
102 | self.hooks.editor(filename,linenum) | |
104 | return |
|
103 | return | |
105 | t = vim_quickfix_file() |
|
104 | t = vim_quickfix_file() | |
106 | try: |
|
105 | try: | |
107 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
106 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): | |
108 |
raise |
|
107 | raise TryNext() | |
109 | finally: |
|
108 | finally: | |
110 | t.close() |
|
109 | t.close() | |
111 |
|
110 | |||
112 | # vds: >> |
|
111 | ||
113 | def synchronize_with_editor(self, filename, linenum, column): |
|
112 | def synchronize_with_editor(self, filename, linenum, column): | |
114 | pass |
|
113 | pass | |
115 | # vds: << |
|
114 | ||
116 |
|
115 | |||
117 | class CommandChainDispatcher: |
|
116 | class CommandChainDispatcher: | |
118 | """ Dispatch calls to a chain of commands until some func can handle it |
|
117 | """ Dispatch calls to a chain of commands until some func can handle it | |
119 |
|
118 | |||
120 | Usage: instantiate, execute "add" to add commands (with optional |
|
119 | Usage: instantiate, execute "add" to add commands (with optional | |
121 | priority), execute normally via f() calling mechanism. |
|
120 | priority), execute normally via f() calling mechanism. | |
122 |
|
121 | |||
123 | """ |
|
122 | """ | |
124 | def __init__(self,commands=None): |
|
123 | def __init__(self,commands=None): | |
125 | if commands is None: |
|
124 | if commands is None: | |
126 | self.chain = [] |
|
125 | self.chain = [] | |
127 | else: |
|
126 | else: | |
128 | self.chain = commands |
|
127 | self.chain = commands | |
129 |
|
128 | |||
130 |
|
129 | |||
131 | def __call__(self,*args, **kw): |
|
130 | def __call__(self,*args, **kw): | |
132 | """ Command chain is called just like normal func. |
|
131 | """ Command chain is called just like normal func. | |
133 |
|
132 | |||
134 | This will call all funcs in chain with the same args as were given to this |
|
133 | This will call all funcs in chain with the same args as were given to this | |
135 | function, and return the result of first func that didn't raise |
|
134 | function, and return the result of first func that didn't raise | |
136 | TryNext """ |
|
135 | TryNext """ | |
137 |
|
136 | |||
138 | for prio,cmd in self.chain: |
|
137 | for prio,cmd in self.chain: | |
139 | #print "prio",prio,"cmd",cmd #dbg |
|
138 | #print "prio",prio,"cmd",cmd #dbg | |
140 | try: |
|
139 | try: | |
141 | ret = cmd(*args, **kw) |
|
140 | ret = cmd(*args, **kw) | |
142 | return ret |
|
141 | return ret | |
143 |
except |
|
142 | except TryNext, exc: | |
144 | if exc.args or exc.kwargs: |
|
143 | if exc.args or exc.kwargs: | |
145 | args = exc.args |
|
144 | args = exc.args | |
146 | kw = exc.kwargs |
|
145 | kw = exc.kwargs | |
147 | # if no function will accept it, raise TryNext up to the caller |
|
146 | # if no function will accept it, raise TryNext up to the caller | |
148 |
raise |
|
147 | raise TryNext | |
149 |
|
148 | |||
150 | def __str__(self): |
|
149 | def __str__(self): | |
151 | return str(self.chain) |
|
150 | return str(self.chain) | |
152 |
|
151 | |||
153 | def add(self, func, priority=0): |
|
152 | def add(self, func, priority=0): | |
154 | """ Add a func to the cmd chain with given priority """ |
|
153 | """ Add a func to the cmd chain with given priority """ | |
155 | bisect.insort(self.chain,(priority,func)) |
|
154 | bisect.insort(self.chain,(priority,func)) | |
156 |
|
155 | |||
157 | def __iter__(self): |
|
156 | def __iter__(self): | |
158 | """ Return all objects in chain. |
|
157 | """ Return all objects in chain. | |
159 |
|
158 | |||
160 | Handy if the objects are not callable. |
|
159 | Handy if the objects are not callable. | |
161 | """ |
|
160 | """ | |
162 | return iter(self.chain) |
|
161 | return iter(self.chain) | |
163 |
|
162 | |||
|
163 | ||||
164 | def result_display(self,arg): |
|
164 | def result_display(self,arg): | |
165 | """ Default display hook. |
|
165 | """ Default display hook. | |
166 |
|
166 | |||
167 | Called for displaying the result to the user. |
|
167 | Called for displaying the result to the user. | |
168 | """ |
|
168 | """ | |
169 |
|
169 | |||
170 |
if self. |
|
170 | if self.pprint: | |
171 | out = pformat(arg) |
|
171 | out = pformat(arg) | |
172 | if '\n' in out: |
|
172 | if '\n' in out: | |
173 | # So that multi-line strings line up with the left column of |
|
173 | # So that multi-line strings line up with the left column of | |
174 | # the screen, instead of having the output prompt mess up |
|
174 | # the screen, instead of having the output prompt mess up | |
175 | # their first line. |
|
175 | # their first line. | |
176 | Term.cout.write('\n') |
|
176 | Term.cout.write('\n') | |
177 | print >>Term.cout, out |
|
177 | print >>Term.cout, out | |
178 | else: |
|
178 | else: | |
179 | # By default, the interactive prompt uses repr() to display results, |
|
179 | # By default, the interactive prompt uses repr() to display results, | |
180 | # so we should honor this. Users who'd rather use a different |
|
180 | # so we should honor this. Users who'd rather use a different | |
181 | # mechanism can easily override this hook. |
|
181 | # mechanism can easily override this hook. | |
182 | print >>Term.cout, repr(arg) |
|
182 | print >>Term.cout, repr(arg) | |
183 | # the default display hook doesn't manipulate the value to put in history |
|
183 | # the default display hook doesn't manipulate the value to put in history | |
184 | return None |
|
184 | return None | |
185 |
|
185 | |||
|
186 | ||||
186 | def input_prefilter(self,line): |
|
187 | def input_prefilter(self,line): | |
187 | """ Default input prefilter |
|
188 | """ Default input prefilter | |
188 |
|
189 | |||
189 | This returns the line as unchanged, so that the interpreter |
|
190 | This returns the line as unchanged, so that the interpreter | |
190 | knows that nothing was done and proceeds with "classic" prefiltering |
|
191 | knows that nothing was done and proceeds with "classic" prefiltering | |
191 | (%magics, !shell commands etc.). |
|
192 | (%magics, !shell commands etc.). | |
192 |
|
193 | |||
193 | Note that leading whitespace is not passed to this hook. Prefilter |
|
194 | Note that leading whitespace is not passed to this hook. Prefilter | |
194 | can't alter indentation. |
|
195 | can't alter indentation. | |
195 |
|
196 | |||
196 | """ |
|
197 | """ | |
197 | #print "attempt to rewrite",line #dbg |
|
198 | #print "attempt to rewrite",line #dbg | |
198 | return line |
|
199 | return line | |
199 |
|
200 | |||
|
201 | ||||
200 | def shutdown_hook(self): |
|
202 | def shutdown_hook(self): | |
201 | """ default shutdown hook |
|
203 | """ default shutdown hook | |
202 |
|
204 | |||
203 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
205 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done | |
204 | """ |
|
206 | """ | |
205 |
|
207 | |||
206 | #print "default shutdown hook ok" # dbg |
|
208 | #print "default shutdown hook ok" # dbg | |
207 | return |
|
209 | return | |
208 |
|
210 | |||
|
211 | ||||
209 | def late_startup_hook(self): |
|
212 | def late_startup_hook(self): | |
210 | """ Executed after ipython has been constructed and configured |
|
213 | """ Executed after ipython has been constructed and configured | |
211 |
|
214 | |||
212 | """ |
|
215 | """ | |
213 | #print "default startup hook ok" # dbg |
|
216 | #print "default startup hook ok" # dbg | |
214 |
|
217 | |||
|
218 | ||||
215 | def generate_prompt(self, is_continuation): |
|
219 | def generate_prompt(self, is_continuation): | |
216 | """ calculate and return a string with the prompt to display """ |
|
220 | """ calculate and return a string with the prompt to display """ | |
217 | ip = self.api |
|
|||
218 | if is_continuation: |
|
221 | if is_continuation: | |
219 |
return str( |
|
222 | return str(self.outputcache.prompt2) | |
220 |
return str( |
|
223 | return str(self.outputcache.prompt1) | |
|
224 | ||||
221 |
|
225 | |||
222 | def generate_output_prompt(self): |
|
226 | def generate_output_prompt(self): | |
223 | ip = self.api |
|
227 | return str(self.outputcache.prompt_out) | |
224 | return str(ip.IP.outputcache.prompt_out) |
|
228 | ||
225 |
|
229 | |||
226 | def shell_hook(self,cmd): |
|
230 | def shell_hook(self,cmd): | |
227 | """ Run system/shell command a'la os.system() """ |
|
231 | """ Run system/shell command a'la os.system() """ | |
228 |
|
232 | |||
229 |
shell(cmd, header=self. |
|
233 | shell(cmd, header=self.system_header, verbose=self.system_verbose) | |
|
234 | ||||
230 |
|
235 | |||
231 | def show_in_pager(self,s): |
|
236 | def show_in_pager(self,s): | |
232 | """ Run a string through pager """ |
|
237 | """ Run a string through pager """ | |
233 | # raising TryNext here will use the default paging functionality |
|
238 | # raising TryNext here will use the default paging functionality | |
234 |
raise |
|
239 | raise TryNext | |
|
240 | ||||
235 |
|
241 | |||
236 | def pre_prompt_hook(self): |
|
242 | def pre_prompt_hook(self): | |
237 | """ Run before displaying the next prompt |
|
243 | """ Run before displaying the next prompt | |
238 |
|
244 | |||
239 | Use this e.g. to display output from asynchronous operations (in order |
|
245 | Use this e.g. to display output from asynchronous operations (in order | |
240 | to not mess up text entry) |
|
246 | to not mess up text entry) | |
241 | """ |
|
247 | """ | |
242 |
|
248 | |||
243 | return None |
|
249 | return None | |
244 |
|
250 | |||
|
251 | ||||
245 | def pre_runcode_hook(self): |
|
252 | def pre_runcode_hook(self): | |
246 | """ Executed before running the (prefiltered) code in IPython """ |
|
253 | """ Executed before running the (prefiltered) code in IPython """ | |
247 | return None |
|
254 | return None | |
248 |
|
255 | |||
|
256 | ||||
249 | def clipboard_get(self): |
|
257 | def clipboard_get(self): | |
250 | """ Get text from the clipboard. |
|
258 | """ Get text from the clipboard. | |
251 | """ |
|
259 | """ | |
252 | from IPython.lib.clipboard import ( |
|
260 | from IPython.lib.clipboard import ( | |
253 | osx_clipboard_get, tkinter_clipboard_get, |
|
261 | osx_clipboard_get, tkinter_clipboard_get, | |
254 | win32_clipboard_get |
|
262 | win32_clipboard_get | |
255 | ) |
|
263 | ) | |
256 | if sys.platform == 'win32': |
|
264 | if sys.platform == 'win32': | |
257 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
265 | chain = [win32_clipboard_get, tkinter_clipboard_get] | |
258 | elif sys.platform == 'darwin': |
|
266 | elif sys.platform == 'darwin': | |
259 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
267 | chain = [osx_clipboard_get, tkinter_clipboard_get] | |
260 | else: |
|
268 | else: | |
261 | chain = [tkinter_clipboard_get] |
|
269 | chain = [tkinter_clipboard_get] | |
262 | dispatcher = CommandChainDispatcher() |
|
270 | dispatcher = CommandChainDispatcher() | |
263 | for func in chain: |
|
271 | for func in chain: | |
264 | dispatcher.add(func) |
|
272 | dispatcher.add(func) | |
265 | text = dispatcher() |
|
273 | text = dispatcher() | |
266 | return text |
|
274 | return text |
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 |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | # encoding: utf-8 | ||
3 | Your one-stop module for configuring & extending ipython |
|
3 | """ | |
4 |
|
4 | Oh my @#*%, where did ipapi go? | ||
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)') |
|
|||
46 |
|
5 | |||
47 | def jed_editor(self,filename, linenum=None): |
|
6 | Originally, this module was designed to be a public api for IPython. It is | |
48 | print 'Calling my own editor, jed ... via hook!' |
|
7 | now deprecated and replaced by :class:`IPython.core.Interactive` shell. | |
49 | import os |
|
8 | Almost all of the methods that were here are now there, but possibly renamed. | |
50 | if linenum is None: linenum = 0 |
|
|||
51 | os.system('jed +%d %s' % (linenum, filename)) |
|
|||
52 | print 'exiting jed' |
|
|||
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 |
|
14 | Authors: | |
57 | o.autocall = 2 # FULL autocall mode |
|
|||
58 |
|
15 | |||
59 | print 'done!' |
|
16 | * Brian Granger | |
60 | """ |
|
17 | """ | |
61 |
|
18 | |||
62 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
63 | # Modules and globals |
|
20 | # Copyright (C) 2008-2009 The IPython Development Team | |
64 |
|
21 | # | ||
65 | # stdlib imports |
|
22 | # Distributed under the terms of the BSD License. The full license is in | |
66 | import __builtin__ |
|
23 | # the file COPYING, distributed as part of this software. | |
67 | import sys |
|
|||
68 |
|
||||
69 | # contains the most recently instantiated IPApi |
|
|||
70 | _RECENT_IP = None |
|
|||
71 |
|
||||
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): |
|
26 | #----------------------------------------------------------------------------- | |
216 | """All configurable variables.""" |
|
27 | # Imports | |
217 |
|
28 | #----------------------------------------------------------------------------- | ||
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. |
|
|||
614 |
|
29 | |||
615 | This builds a dict with the minimal information needed to operate as a |
|
30 | from IPython.core.error import TryNext, UsageError | |
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. |
|
|||
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: |
|
36 | def get(): | |
628 | user_ns : dict-like, optional |
|
37 | """Get the most recently created InteractiveShell instance.""" | |
629 | The current user namespace. The items in this namespace should be |
|
38 | from IPython.core.iplib import InteractiveShell | |
630 | included in the output. If None, an appropriate blank namespace |
|
39 | insts = InteractiveShell.get_instances() | |
631 | should be created. |
|
40 | most_recent = insts[0] | |
632 | user_global_ns : dict, optional |
|
41 | for inst in insts[1:]: | |
633 | The current user global namespace. The items in this namespace |
|
42 | if inst.created > most_recent.created: | |
634 | should be included in the output. If None, an appropriate blank |
|
43 | most_recent = inst | |
635 | namespace should be created. |
|
44 | return most_recent | |
636 |
|
45 | |||
637 | :Returns: |
|
46 | def launch_new_instance(): | |
638 | A tuple pair of dictionary-like object to be used as the local namespace |
|
47 | """Create a run a full blown IPython instance""" | |
639 | of the interpreter and a dict to be used as the global namespace. |
|
48 | from IPython.core.ipapp import IPythonApp | |
640 | """ |
|
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,2865 +1,2962 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | Main IPython Component | |
4 |
|
||||
5 | Requires Python 2.4 or newer. |
|
|||
6 |
|
||||
7 | This file contains all the classes and helper functions specific to IPython. |
|
|||
8 | """ |
|
4 | """ | |
9 |
|
5 | |||
10 | #***************************************************************************** |
|
6 | #----------------------------------------------------------------------------- | |
11 |
# |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
12 |
# |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |||
13 | # |
|
10 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
16 | # |
|
13 | #----------------------------------------------------------------------------- | |
17 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
14 | ||
18 | # Python standard library. Over time, all of that class has been copied |
|
15 | #----------------------------------------------------------------------------- | |
19 | # verbatim here for modifications which could not be accomplished by |
|
16 | # Imports | |
20 | # subclassing. At this point, there are no dependencies at all on the code |
|
17 | #----------------------------------------------------------------------------- | |
21 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
18 | ||
22 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
19 | from __future__ import with_statement | |
23 | # due. |
|
20 | ||
24 | #***************************************************************************** |
|
|||
25 |
|
||||
26 | #**************************************************************************** |
|
|||
27 | # Modules and globals |
|
|||
28 |
|
||||
29 | # Python standard modules |
|
|||
30 | import __main__ |
|
21 | import __main__ | |
31 | import __builtin__ |
|
22 | import __builtin__ | |
32 | import StringIO |
|
23 | import StringIO | |
33 | import bdb |
|
24 | import bdb | |
34 | import codeop |
|
25 | import codeop | |
35 | import exceptions |
|
26 | import exceptions | |
36 | import glob |
|
27 | import glob | |
37 | import keyword |
|
28 | import keyword | |
38 | import new |
|
29 | import new | |
39 | import os |
|
30 | import os | |
40 | import re |
|
31 | import re | |
41 | import shutil |
|
32 | import shutil | |
42 | import string |
|
33 | import string | |
43 | import sys |
|
34 | import sys | |
44 | import tempfile |
|
35 | import tempfile | |
45 |
|
36 | |||
46 | # IPython's own modules |
|
|||
47 | #import IPython |
|
|||
48 | from IPython.core import ultratb |
|
37 | from IPython.core import ultratb | |
49 | from IPython.utils import PyColorize |
|
|||
50 | from IPython.core import debugger, oinspect |
|
38 | from IPython.core import debugger, oinspect | |
51 |
from IPython. |
|
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 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
44 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
53 | from IPython.external.Itpl import ItplNS |
|
|||
54 | from IPython.core.logger import Logger |
|
45 | from IPython.core.logger import Logger | |
55 | from IPython.core.magic import Magic |
|
46 | from IPython.core.magic import Magic | |
56 | from IPython.core.prompts import CachedOutput |
|
47 | from IPython.core.prompts import CachedOutput | |
57 |
from IPython. |
|
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 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
56 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
|
57 | from IPython.utils.ipstruct import Struct | |||
|
58 | from IPython.utils import PyColorize | |||
59 | from IPython.utils.genutils import * |
|
59 | from IPython.utils.genutils import * | |
60 | from IPython.utils.strdispatch import StrDispatch |
|
60 | from IPython.utils.strdispatch import StrDispatch | |
61 | from IPython.core import ipapi |
|
61 | from IPython.utils.platutils import toggle_set_term_title, set_term_title | |
62 | import IPython.core.history |
|
62 | ||
63 | import IPython.core.prefilter as prefilter |
|
63 | from IPython.utils.traitlets import ( | |
64 | from IPython.core import shadowns |
|
64 | Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode | |
|
65 | ) | |||
|
66 | ||||
|
67 | #----------------------------------------------------------------------------- | |||
65 | # Globals |
|
68 | # Globals | |
|
69 | #----------------------------------------------------------------------------- | |||
|
70 | ||||
66 |
|
71 | |||
67 | # store the builtin raw_input globally, and use this always, in case user code |
|
72 | # store the builtin raw_input globally, and use this always, in case user code | |
68 | # overwrites it (like wx.py.PyShell does) |
|
73 | # overwrites it (like wx.py.PyShell does) | |
69 | raw_input_original = raw_input |
|
74 | raw_input_original = raw_input | |
70 |
|
75 | |||
71 | # compiled regexps for autoindent management |
|
76 | # compiled regexps for autoindent management | |
72 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
77 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
73 |
|
78 | |||
74 |
|
79 | |||
75 | #**************************************************************************** |
|
80 | #----------------------------------------------------------------------------- | |
76 | # Some utility function definitions |
|
81 | # Utilities | |
|
82 | #----------------------------------------------------------------------------- | |||
|
83 | ||||
77 |
|
84 | |||
78 | ini_spaces_re = re.compile(r'^(\s+)') |
|
85 | ini_spaces_re = re.compile(r'^(\s+)') | |
79 |
|
86 | |||
|
87 | ||||
80 | def num_ini_spaces(strng): |
|
88 | def num_ini_spaces(strng): | |
81 | """Return the number of initial spaces in a string""" |
|
89 | """Return the number of initial spaces in a string""" | |
82 |
|
90 | |||
83 | ini_spaces = ini_spaces_re.match(strng) |
|
91 | ini_spaces = ini_spaces_re.match(strng) | |
84 | if ini_spaces: |
|
92 | if ini_spaces: | |
85 | return ini_spaces.end() |
|
93 | return ini_spaces.end() | |
86 | else: |
|
94 | else: | |
87 | return 0 |
|
95 | return 0 | |
88 |
|
96 | |||
|
97 | ||||
89 | def softspace(file, newvalue): |
|
98 | def softspace(file, newvalue): | |
90 | """Copied from code.py, to remove the dependency""" |
|
99 | """Copied from code.py, to remove the dependency""" | |
91 |
|
100 | |||
92 | oldvalue = 0 |
|
101 | oldvalue = 0 | |
93 | try: |
|
102 | try: | |
94 | oldvalue = file.softspace |
|
103 | oldvalue = file.softspace | |
95 | except AttributeError: |
|
104 | except AttributeError: | |
96 | pass |
|
105 | pass | |
97 | try: |
|
106 | try: | |
98 | file.softspace = newvalue |
|
107 | file.softspace = newvalue | |
99 | except (AttributeError, TypeError): |
|
108 | except (AttributeError, TypeError): | |
100 | # "attribute-less object" or "read-only attributes" |
|
109 | # "attribute-less object" or "read-only attributes" | |
101 | pass |
|
110 | pass | |
102 | return oldvalue |
|
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 | class SpaceInInput(exceptions.Exception): pass |
|
114 | class SpaceInInput(exceptions.Exception): pass | |
303 |
|
115 | |||
304 |
|
||||
305 | #**************************************************************************** |
|
|||
306 | # Local use classes |
|
|||
307 | class Bunch: pass |
|
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 | class InputList(list): |
|
118 | class InputList(list): | |
329 | """Class to store user input. |
|
119 | """Class to store user input. | |
330 |
|
120 | |||
331 | It's basically a list, but slices return a string instead of a list, thus |
|
121 | It's basically a list, but slices return a string instead of a list, thus | |
332 | allowing things like (assuming 'In' is an instance): |
|
122 | allowing things like (assuming 'In' is an instance): | |
333 |
|
123 | |||
334 | exec In[4:7] |
|
124 | exec In[4:7] | |
335 |
|
125 | |||
336 | or |
|
126 | or | |
337 |
|
127 | |||
338 | exec In[5:9] + In[14] + In[21:25]""" |
|
128 | exec In[5:9] + In[14] + In[21:25]""" | |
339 |
|
129 | |||
340 | def __getslice__(self,i,j): |
|
130 | def __getslice__(self,i,j): | |
341 | return ''.join(list.__getslice__(self,i,j)) |
|
131 | return ''.join(list.__getslice__(self,i,j)) | |
342 |
|
132 | |||
|
133 | ||||
343 | class SyntaxTB(ultratb.ListTB): |
|
134 | class SyntaxTB(ultratb.ListTB): | |
344 | """Extension which holds some state: the last exception value""" |
|
135 | """Extension which holds some state: the last exception value""" | |
345 |
|
136 | |||
346 | def __init__(self,color_scheme = 'NoColor'): |
|
137 | def __init__(self,color_scheme = 'NoColor'): | |
347 | ultratb.ListTB.__init__(self,color_scheme) |
|
138 | ultratb.ListTB.__init__(self,color_scheme) | |
348 | self.last_syntax_error = None |
|
139 | self.last_syntax_error = None | |
349 |
|
140 | |||
350 | def __call__(self, etype, value, elist): |
|
141 | def __call__(self, etype, value, elist): | |
351 | self.last_syntax_error = value |
|
142 | self.last_syntax_error = value | |
352 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
143 | ultratb.ListTB.__call__(self,etype,value,elist) | |
353 |
|
144 | |||
354 | def clear_err_state(self): |
|
145 | def clear_err_state(self): | |
355 | """Return the current error state and clear it""" |
|
146 | """Return the current error state and clear it""" | |
356 | e = self.last_syntax_error |
|
147 | e = self.last_syntax_error | |
357 | self.last_syntax_error = None |
|
148 | self.last_syntax_error = None | |
358 | return e |
|
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 |
|
152 | def get_default_editor(): | |
364 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
153 | try: | |
365 | # attributes and methods, but too much user code out there relies on the |
|
154 | ed = os.environ['EDITOR'] | |
366 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
155 | except KeyError: | |
367 | # |
|
156 | if os.name == 'posix': | |
368 | # But at least now, all the pieces have been separated and we could, in |
|
157 | ed = 'vi' # the only one guaranteed to be there! | |
369 | # principle, stop using the mixin. This will ease the transition to the |
|
158 | else: | |
370 | # chainsaw branch. |
|
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 |
|
166 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. | |
373 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
167 | """ | |
374 | # class, to prevent clashes. |
|
|||
375 |
|
168 | |||
376 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
169 | def validate(self, obj, value): | |
377 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
170 | if value == '0': value = '' | |
378 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
171 | value = value.replace('\\n','\n') | |
379 | # 'self.value'] |
|
172 | return super(SeparateStr, self).validate(obj, value) | |
380 |
|
173 | |||
381 | class InteractiveShell(object,Magic): |
|
174 | ||
382 | """An enhanced console for Python.""" |
|
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 | # class attribute to indicate whether the class supports threads or not. |
|
264 | # class attribute to indicate whether the class supports threads or not. | |
385 | # Subclasses with thread support should override this as needed. |
|
265 | # Subclasses with thread support should override this as needed. | |
386 | isthreaded = False |
|
266 | isthreaded = False | |
387 |
|
267 | |||
388 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
268 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
389 |
user_ns=None,user_global_ns=None, |
|
269 | user_ns=None, user_global_ns=None, | |
390 | custom_exceptions=((),None),embedded=False): |
|
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 |
|
323 | def cleanup(self): | |
393 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
324 | self.restore_sys_module_state() | |
394 |
|
||||
395 | # Job manager (for jobs run as background threads) |
|
|||
396 | self.jobs = BackgroundJobManager() |
|
|||
397 |
|
325 | |||
398 | # Store the actual shell's name |
|
326 | #------------------------------------------------------------------------- | |
399 | self.name = name |
|
327 | # Traitlet changed handlers | |
400 | self.more = False |
|
328 | #------------------------------------------------------------------------- | |
401 |
|
329 | |||
402 | # We need to know whether the instance is meant for embedding, since |
|
330 | def _banner1_changed(self): | |
403 | # global/local namespaces need to be handled differently in that case |
|
331 | self.compute_banner() | |
404 | self.embedded = embedded |
|
332 | ||
405 | if embedded: |
|
333 | def _banner2_changed(self): | |
406 | # Control variable so users can, from within the embedded instance, |
|
334 | self.compute_banner() | |
407 | # permanently deactivate it. |
|
335 | ||
408 | self.embedded_active = True |
|
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 | # command compiler |
|
375 | # command compiler | |
411 | self.compile = codeop.CommandCompiler() |
|
376 | self.compile = codeop.CommandCompiler() | |
412 |
|
377 | |||
413 | # User input buffer |
|
378 | # User input buffer | |
414 | self.buffer = [] |
|
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 | # Make an empty namespace, which extension writers can rely on both |
|
381 | # Make an empty namespace, which extension writers can rely on both | |
425 | # existing and NEVER being used by ipython itself. This gives them a |
|
382 | # existing and NEVER being used by ipython itself. This gives them a | |
426 | # convenient location for storing additional information and state |
|
383 | # convenient location for storing additional information and state | |
427 | # their extensions may require, without fear of collisions with other |
|
384 | # their extensions may require, without fear of collisions with other | |
428 | # ipython names that may develop later. |
|
385 | # ipython names that may develop later. | |
429 | self.meta = Struct() |
|
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 | # Create the namespace where the user will operate. user_ns is |
|
441 | # Create the namespace where the user will operate. user_ns is | |
432 | # normally the only one used, and it is passed to the exec calls as |
|
442 | # normally the only one used, and it is passed to the exec calls as | |
433 | # the locals argument. But we do carry a user_global_ns namespace |
|
443 | # the locals argument. But we do carry a user_global_ns namespace | |
434 | # given as the exec 'globals' argument, This is useful in embedding |
|
444 | # given as the exec 'globals' argument, This is useful in embedding | |
435 | # situations where the ipython shell opens in a context where the |
|
445 | # situations where the ipython shell opens in a context where the | |
436 | # distinction between locals and globals is meaningful. For |
|
446 | # distinction between locals and globals is meaningful. For | |
437 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
447 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
438 |
|
448 | |||
439 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
449 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
440 | # level as a dict instead of a module. This is a manual fix, but I |
|
450 | # level as a dict instead of a module. This is a manual fix, but I | |
441 | # should really track down where the problem is coming from. Alex |
|
451 | # should really track down where the problem is coming from. Alex | |
442 | # Schmolck reported this problem first. |
|
452 | # Schmolck reported this problem first. | |
443 |
|
453 | |||
444 | # A useful post by Alex Martelli on this topic: |
|
454 | # A useful post by Alex Martelli on this topic: | |
445 | # Re: inconsistent value from __builtins__ |
|
455 | # Re: inconsistent value from __builtins__ | |
446 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
456 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
447 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
457 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
448 | # Gruppen: comp.lang.python |
|
458 | # Gruppen: comp.lang.python | |
449 |
|
459 | |||
450 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
460 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
451 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
461 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
452 | # > <type 'dict'> |
|
462 | # > <type 'dict'> | |
453 | # > >>> print type(__builtins__) |
|
463 | # > >>> print type(__builtins__) | |
454 | # > <type 'module'> |
|
464 | # > <type 'module'> | |
455 | # > Is this difference in return value intentional? |
|
465 | # > Is this difference in return value intentional? | |
456 |
|
466 | |||
457 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
467 | # Well, it's documented that '__builtins__' can be either a dictionary | |
458 | # or a module, and it's been that way for a long time. Whether it's |
|
468 | # or a module, and it's been that way for a long time. Whether it's | |
459 | # intentional (or sensible), I don't know. In any case, the idea is |
|
469 | # intentional (or sensible), I don't know. In any case, the idea is | |
460 | # that if you need to access the built-in namespace directly, you |
|
470 | # that if you need to access the built-in namespace directly, you | |
461 | # should start with "import __builtin__" (note, no 's') which will |
|
471 | # should start with "import __builtin__" (note, no 's') which will | |
462 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
472 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
463 |
|
473 | |||
464 | # These routines return properly built dicts as needed by the rest of |
|
474 | # These routines return properly built dicts as needed by the rest of | |
465 | # the code, and can also be used by extension writers to generate |
|
475 | # the code, and can also be used by extension writers to generate | |
466 | # properly initialized namespaces. |
|
476 | # properly initialized namespaces. | |
467 |
user_ns, user_global_ns = |
|
477 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
468 | user_global_ns) |
|
478 | user_global_ns) | |
469 |
|
479 | |||
470 | # Assign namespaces |
|
480 | # Assign namespaces | |
471 | # This is the namespace where all normal user variables live |
|
481 | # This is the namespace where all normal user variables live | |
472 | self.user_ns = user_ns |
|
482 | self.user_ns = user_ns | |
473 | self.user_global_ns = user_global_ns |
|
483 | self.user_global_ns = user_global_ns | |
474 |
|
484 | |||
475 | # An auxiliary namespace that checks what parts of the user_ns were |
|
485 | # An auxiliary namespace that checks what parts of the user_ns were | |
476 | # loaded at startup, so we can list later only variables defined in |
|
486 | # loaded at startup, so we can list later only variables defined in | |
477 | # actual interactive use. Since it is always a subset of user_ns, it |
|
487 | # actual interactive use. Since it is always a subset of user_ns, it | |
478 | # doesn't need to be seaparately tracked in the ns_table |
|
488 | # doesn't need to be seaparately tracked in the ns_table | |
479 | self.user_config_ns = {} |
|
489 | self.user_config_ns = {} | |
480 |
|
490 | |||
481 | # A namespace to keep track of internal data structures to prevent |
|
491 | # A namespace to keep track of internal data structures to prevent | |
482 | # them from cluttering user-visible stuff. Will be updated later |
|
492 | # them from cluttering user-visible stuff. Will be updated later | |
483 | self.internal_ns = {} |
|
493 | self.internal_ns = {} | |
484 |
|
494 | |||
485 | # Namespace of system aliases. Each entry in the alias |
|
495 | # Namespace of system aliases. Each entry in the alias | |
486 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
496 | # table must be a 2-tuple of the form (N,name), where N is the number | |
487 | # of positional arguments of the alias. |
|
497 | # of positional arguments of the alias. | |
488 | self.alias_table = {} |
|
498 | self.alias_table = {} | |
489 |
|
499 | |||
490 | # Now that FakeModule produces a real module, we've run into a nasty |
|
500 | # Now that FakeModule produces a real module, we've run into a nasty | |
491 | # problem: after script execution (via %run), the module where the user |
|
501 | # problem: after script execution (via %run), the module where the user | |
492 | # code ran is deleted. Now that this object is a true module (needed |
|
502 | # code ran is deleted. Now that this object is a true module (needed | |
493 | # so docetst and other tools work correctly), the Python module |
|
503 | # so docetst and other tools work correctly), the Python module | |
494 | # teardown mechanism runs over it, and sets to None every variable |
|
504 | # teardown mechanism runs over it, and sets to None every variable | |
495 | # present in that module. Top-level references to objects from the |
|
505 | # present in that module. Top-level references to objects from the | |
496 | # script survive, because the user_ns is updated with them. However, |
|
506 | # script survive, because the user_ns is updated with them. However, | |
497 | # calling functions defined in the script that use other things from |
|
507 | # calling functions defined in the script that use other things from | |
498 | # the script will fail, because the function's closure had references |
|
508 | # the script will fail, because the function's closure had references | |
499 | # to the original objects, which are now all None. So we must protect |
|
509 | # to the original objects, which are now all None. So we must protect | |
500 | # these modules from deletion by keeping a cache. |
|
510 | # these modules from deletion by keeping a cache. | |
501 | # |
|
511 | # | |
502 | # To avoid keeping stale modules around (we only need the one from the |
|
512 | # To avoid keeping stale modules around (we only need the one from the | |
503 | # last run), we use a dict keyed with the full path to the script, so |
|
513 | # last run), we use a dict keyed with the full path to the script, so | |
504 | # only the last version of the module is held in the cache. Note, |
|
514 | # only the last version of the module is held in the cache. Note, | |
505 | # however, that we must cache the module *namespace contents* (their |
|
515 | # however, that we must cache the module *namespace contents* (their | |
506 | # __dict__). Because if we try to cache the actual modules, old ones |
|
516 | # __dict__). Because if we try to cache the actual modules, old ones | |
507 | # (uncached) could be destroyed while still holding references (such as |
|
517 | # (uncached) could be destroyed while still holding references (such as | |
508 | # those held by GUI objects that tend to be long-lived)> |
|
518 | # those held by GUI objects that tend to be long-lived)> | |
509 | # |
|
519 | # | |
510 | # The %reset command will flush this cache. See the cache_main_mod() |
|
520 | # The %reset command will flush this cache. See the cache_main_mod() | |
511 | # and clear_main_mod_cache() methods for details on use. |
|
521 | # and clear_main_mod_cache() methods for details on use. | |
512 |
|
522 | |||
513 | # This is the cache used for 'main' namespaces |
|
523 | # This is the cache used for 'main' namespaces | |
514 | self._main_ns_cache = {} |
|
524 | self._main_ns_cache = {} | |
515 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
525 | # And this is the single instance of FakeModule whose __dict__ we keep | |
516 | # copying and clearing for reuse on each %run |
|
526 | # copying and clearing for reuse on each %run | |
517 | self._user_main_module = FakeModule() |
|
527 | self._user_main_module = FakeModule() | |
518 |
|
528 | |||
519 | # A table holding all the namespaces IPython deals with, so that |
|
529 | # A table holding all the namespaces IPython deals with, so that | |
520 | # introspection facilities can search easily. |
|
530 | # introspection facilities can search easily. | |
521 | self.ns_table = {'user':user_ns, |
|
531 | self.ns_table = {'user':user_ns, | |
522 | 'user_global':user_global_ns, |
|
532 | 'user_global':user_global_ns, | |
523 | 'alias':self.alias_table, |
|
533 | 'alias':self.alias_table, | |
524 | 'internal':self.internal_ns, |
|
534 | 'internal':self.internal_ns, | |
525 | 'builtin':__builtin__.__dict__ |
|
535 | 'builtin':__builtin__.__dict__ | |
526 | } |
|
536 | } | |
527 |
|
537 | |||
528 | # Similarly, track all namespaces where references can be held and that |
|
538 | # Similarly, track all namespaces where references can be held and that | |
529 | # we can safely clear (so it can NOT include builtin). This one can be |
|
539 | # we can safely clear (so it can NOT include builtin). This one can be | |
530 | # a simple list. |
|
540 | # a simple list. | |
531 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
541 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
532 | self.alias_table, self.internal_ns, |
|
542 | self.alias_table, self.internal_ns, | |
533 | self._main_ns_cache ] |
|
543 | self._main_ns_cache ] | |
534 |
|
544 | |||
|
545 | def init_sys_modules(self): | |||
535 | # We need to insert into sys.modules something that looks like a |
|
546 | # We need to insert into sys.modules something that looks like a | |
536 | # module but which accesses the IPython namespace, for shelve and |
|
547 | # module but which accesses the IPython namespace, for shelve and | |
537 | # pickle to work interactively. Normally they rely on getting |
|
548 | # pickle to work interactively. Normally they rely on getting | |
538 | # everything out of __main__, but for embedding purposes each IPython |
|
549 | # everything out of __main__, but for embedding purposes each IPython | |
539 | # instance has its own private namespace, so we can't go shoving |
|
550 | # instance has its own private namespace, so we can't go shoving | |
540 | # everything into __main__. |
|
551 | # everything into __main__. | |
541 |
|
552 | |||
542 | # note, however, that we should only do this for non-embedded |
|
553 | # note, however, that we should only do this for non-embedded | |
543 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
554 | # ipythons, which really mimic the __main__.__dict__ with their own | |
544 | # namespace. Embedded instances, on the other hand, should not do |
|
555 | # namespace. Embedded instances, on the other hand, should not do | |
545 | # this because they need to manage the user local/global namespaces |
|
556 | # this because they need to manage the user local/global namespaces | |
546 | # only, but they live within a 'normal' __main__ (meaning, they |
|
557 | # only, but they live within a 'normal' __main__ (meaning, they | |
547 | # shouldn't overtake the execution environment of the script they're |
|
558 | # shouldn't overtake the execution environment of the script they're | |
548 | # embedded in). |
|
559 | # embedded in). | |
549 |
|
560 | |||
550 | if not embedded: |
|
561 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
551 | try: |
|
562 | ||
552 | main_name = self.user_ns['__name__'] |
|
563 | try: | |
553 | except KeyError: |
|
564 | main_name = self.user_ns['__name__'] | |
554 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
565 | except KeyError: | |
555 | else: |
|
566 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
556 | #print "pickle hack in place" # dbg |
|
567 | else: | |
557 | #print 'main_name:',main_name # dbg |
|
568 | sys.modules[main_name] = FakeModule(self.user_ns) | |
558 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
569 | ||
559 |
|
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 | # List of input with multi-line handling. |
|
620 | # List of input with multi-line handling. | |
561 | self.input_hist = InputList() |
|
621 | self.input_hist = InputList() | |
562 | # This one will hold the 'raw' input history, without any |
|
622 | # This one will hold the 'raw' input history, without any | |
563 | # pre-processing. This will allow users to retrieve the input just as |
|
623 | # pre-processing. This will allow users to retrieve the input just as | |
564 | # it was exactly typed in by the user, with %hist -r. |
|
624 | # it was exactly typed in by the user, with %hist -r. | |
565 | self.input_hist_raw = InputList() |
|
625 | self.input_hist_raw = InputList() | |
566 |
|
626 | |||
567 | # list of visited directories |
|
627 | # list of visited directories | |
568 | try: |
|
628 | try: | |
569 | self.dir_hist = [os.getcwd()] |
|
629 | self.dir_hist = [os.getcwd()] | |
570 | except OSError: |
|
630 | except OSError: | |
571 | self.dir_hist = [] |
|
631 | self.dir_hist = [] | |
572 |
|
632 | |||
573 | # dict of output history |
|
633 | # dict of output history | |
574 | self.output_hist = {} |
|
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 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
648 | # Get system encoding at startup time. Certain terminals (like Emacs | |
577 | # under Win32 have it set to None, and we need to have a known valid |
|
649 | # under Win32 have it set to None, and we need to have a known valid | |
578 | # encoding to use in the raw_input() method |
|
650 | # encoding to use in the raw_input() method | |
579 | try: |
|
651 | try: | |
580 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
652 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
581 | except AttributeError: |
|
653 | except AttributeError: | |
582 | self.stdin_encoding = 'ascii' |
|
654 | self.stdin_encoding = 'ascii' | |
583 |
|
655 | |||
584 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
656 | def init_handlers(self): | |
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 |
|
||||
598 | # escapes for automatic behavior on the command line |
|
657 | # escapes for automatic behavior on the command line | |
599 | self.ESC_SHELL = '!' |
|
658 | self.ESC_SHELL = '!' | |
600 | self.ESC_SH_CAP = '!!' |
|
659 | self.ESC_SH_CAP = '!!' | |
601 | self.ESC_HELP = '?' |
|
660 | self.ESC_HELP = '?' | |
602 | self.ESC_MAGIC = '%' |
|
661 | self.ESC_MAGIC = '%' | |
603 | self.ESC_QUOTE = ',' |
|
662 | self.ESC_QUOTE = ',' | |
604 | self.ESC_QUOTE2 = ';' |
|
663 | self.ESC_QUOTE2 = ';' | |
605 | self.ESC_PAREN = '/' |
|
664 | self.ESC_PAREN = '/' | |
606 |
|
665 | |||
607 | # And their associated handlers |
|
666 | # And their associated handlers | |
608 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
667 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
609 | self.ESC_QUOTE : self.handle_auto, |
|
668 | self.ESC_QUOTE : self.handle_auto, | |
610 | self.ESC_QUOTE2 : self.handle_auto, |
|
669 | self.ESC_QUOTE2 : self.handle_auto, | |
611 | self.ESC_MAGIC : self.handle_magic, |
|
670 | self.ESC_MAGIC : self.handle_magic, | |
612 | self.ESC_HELP : self.handle_help, |
|
671 | self.ESC_HELP : self.handle_help, | |
613 | self.ESC_SHELL : self.handle_shell_escape, |
|
672 | self.ESC_SHELL : self.handle_shell_escape, | |
614 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
673 | self.ESC_SH_CAP : self.handle_shell_escape, | |
615 | } |
|
674 | } | |
616 |
|
675 | |||
617 | # class initializations |
|
676 | def init_syntax_highlighting(self): | |
618 | Magic.__init__(self,self) |
|
|||
619 |
|
||||
620 | # Python source parser/formatter for syntax highlighting |
|
677 | # Python source parser/formatter for syntax highlighting | |
621 | pyformat = PyColorize.Parser().format |
|
678 | pyformat = PyColorize.Parser().format | |
622 |
self.pycolorize = lambda src: pyformat(src,'str',self. |
|
679 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
623 |
|
680 | |||
|
681 | def init_hooks(self): | |||
624 | # hooks holds pointers used for user-side customizations |
|
682 | # hooks holds pointers used for user-side customizations | |
625 | self.hooks = Struct() |
|
683 | self.hooks = Struct() | |
626 |
|
684 | |||
627 | self.strdispatchers = {} |
|
685 | self.strdispatchers = {} | |
628 |
|
686 | |||
629 | # Set all default hooks, defined in the IPython.hooks module. |
|
687 | # Set all default hooks, defined in the IPython.hooks module. | |
630 | import IPython.core.hooks |
|
688 | import IPython.core.hooks | |
631 | hooks = IPython.core.hooks |
|
689 | hooks = IPython.core.hooks | |
632 | for hook_name in hooks.__all__: |
|
690 | for hook_name in hooks.__all__: | |
633 | # default hooks have priority 100, i.e. low; user hooks should have |
|
691 | # default hooks have priority 100, i.e. low; user hooks should have | |
634 | # 0-100 priority |
|
692 | # 0-100 priority | |
635 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
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) |
|
695 | def init_pushd_popd_magic(self): | |
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 | """ |
|
|||
674 | # for pushd/popd management |
|
696 | # for pushd/popd management | |
675 | try: |
|
697 | try: | |
676 | self.home_dir = get_home_dir() |
|
698 | self.home_dir = get_home_dir() | |
677 | except HomeDirError,msg: |
|
699 | except HomeDirError, msg: | |
678 | fatal(msg) |
|
700 | fatal(msg) | |
679 |
|
701 | |||
680 | self.dir_stack = [] |
|
702 | self.dir_stack = [] | |
681 |
|
703 | |||
682 | # Functions to call the underlying shell. |
|
704 | def init_traceback_handlers(self, custom_exceptions): | |
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 |
|
||||
711 | # Syntax error handler. |
|
705 | # Syntax error handler. | |
712 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
706 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
713 |
|
707 | |||
714 | # The interactive one is initialized with an offset, meaning we always |
|
708 | # The interactive one is initialized with an offset, meaning we always | |
715 | # want to remove the topmost item in the traceback, which is our own |
|
709 | # want to remove the topmost item in the traceback, which is our own | |
716 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
710 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
717 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
711 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
718 | color_scheme='NoColor', |
|
712 | color_scheme='NoColor', | |
719 | tb_offset = 1) |
|
713 | tb_offset = 1) | |
720 |
|
714 | |||
721 | # IPython itself shouldn't crash. This will produce a detailed |
|
715 | # IPython itself shouldn't crash. This will produce a detailed | |
722 | # post-mortem if it does. But we only install the crash handler for |
|
716 | # post-mortem if it does. But we only install the crash handler for | |
723 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
717 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
724 | # and lose the crash handler. This is because exceptions in the main |
|
718 | # and lose the crash handler. This is because exceptions in the main | |
725 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
719 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
726 | # and there's no point in printing crash dumps for every user exception. |
|
720 | # and there's no point in printing crash dumps for every user exception. | |
727 | if self.isthreaded: |
|
721 | if self.isthreaded: | |
728 | ipCrashHandler = ultratb.FormattedTB() |
|
722 | ipCrashHandler = ultratb.FormattedTB() | |
729 | else: |
|
723 | else: | |
730 | from IPython.core import crashhandler |
|
724 | from IPython.core import crashhandler | |
731 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
725 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) | |
732 | self.set_crash_handler(ipCrashHandler) |
|
726 | self.set_crash_handler(ipCrashHandler) | |
733 |
|
727 | |||
734 | # and add any custom exception handlers the user may have specified |
|
728 | # and add any custom exception handlers the user may have specified | |
735 | self.set_custom_exc(*custom_exceptions) |
|
729 | self.set_custom_exc(*custom_exceptions) | |
736 |
|
730 | |||
737 | # indentation management |
|
731 | def init_logger(self): | |
738 | self.autoindent = False |
|
732 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
739 | self.indent_current_nsp = 0 |
|
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 | # Make some aliases automatically |
|
763 | # Make some aliases automatically | |
742 | # Prepare list of shell aliases to auto-define |
|
764 | # Prepare list of shell aliases to auto-define | |
743 | if os.name == 'posix': |
|
765 | if os.name == 'posix': | |
744 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
766 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
745 | 'mv mv -i','rm rm -i','cp cp -i', |
|
767 | 'mv mv -i','rm rm -i','cp cp -i', | |
746 | 'cat cat','less less','clear clear', |
|
768 | 'cat cat','less less','clear clear', | |
747 | # a better ls |
|
769 | # a better ls | |
748 | 'ls ls -F', |
|
770 | 'ls ls -F', | |
749 | # long ls |
|
771 | # long ls | |
750 | 'll ls -lF') |
|
772 | 'll ls -lF') | |
751 | # Extra ls aliases with color, which need special treatment on BSD |
|
773 | # Extra ls aliases with color, which need special treatment on BSD | |
752 | # variants |
|
774 | # variants | |
753 | ls_extra = ( # color ls |
|
775 | ls_extra = ( # color ls | |
754 | 'lc ls -F -o --color', |
|
776 | 'lc ls -F -o --color', | |
755 | # ls normal files only |
|
777 | # ls normal files only | |
756 | 'lf ls -F -o --color %l | grep ^-', |
|
778 | 'lf ls -F -o --color %l | grep ^-', | |
757 | # ls symbolic links |
|
779 | # ls symbolic links | |
758 | 'lk ls -F -o --color %l | grep ^l', |
|
780 | 'lk ls -F -o --color %l | grep ^l', | |
759 | # directories or links to directories, |
|
781 | # directories or links to directories, | |
760 | 'ldir ls -F -o --color %l | grep /$', |
|
782 | 'ldir ls -F -o --color %l | grep /$', | |
761 | # things which are executable |
|
783 | # things which are executable | |
762 | 'lx ls -F -o --color %l | grep ^-..x', |
|
784 | 'lx ls -F -o --color %l | grep ^-..x', | |
763 | ) |
|
785 | ) | |
764 | # The BSDs don't ship GNU ls, so they don't understand the |
|
786 | # The BSDs don't ship GNU ls, so they don't understand the | |
765 | # --color switch out of the box |
|
787 | # --color switch out of the box | |
766 | if 'bsd' in sys.platform: |
|
788 | if 'bsd' in sys.platform: | |
767 | ls_extra = ( # ls normal files only |
|
789 | ls_extra = ( # ls normal files only | |
768 | 'lf ls -lF | grep ^-', |
|
790 | 'lf ls -lF | grep ^-', | |
769 | # ls symbolic links |
|
791 | # ls symbolic links | |
770 | 'lk ls -lF | grep ^l', |
|
792 | 'lk ls -lF | grep ^l', | |
771 | # directories or links to directories, |
|
793 | # directories or links to directories, | |
772 | 'ldir ls -lF | grep /$', |
|
794 | 'ldir ls -lF | grep /$', | |
773 | # things which are executable |
|
795 | # things which are executable | |
774 | 'lx ls -lF | grep ^-..x', |
|
796 | 'lx ls -lF | grep ^-..x', | |
775 | ) |
|
797 | ) | |
776 | auto_alias = auto_alias + ls_extra |
|
798 | auto_alias = auto_alias + ls_extra | |
777 | elif os.name in ['nt','dos']: |
|
799 | elif os.name in ['nt','dos']: | |
778 | auto_alias = ('ls dir /on', |
|
800 | auto_alias = ('ls dir /on', | |
779 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
801 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
780 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
802 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
781 | 'ren ren','cls cls','copy copy') |
|
803 | 'ren ren','cls cls','copy copy') | |
782 | else: |
|
804 | else: | |
783 | auto_alias = () |
|
805 | auto_alias = () | |
784 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
806 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
785 |
|
807 | |||
786 | # Produce a public API instance |
|
808 | # Load default aliases | |
787 | self.api = ipapi.IPApi(self) |
|
809 | for alias, cmd in self.auto_alias: | |
788 |
|
810 | self.define_alias(alias,cmd) | ||
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 | """ |
|
|||
813 |
|
811 | |||
814 | return str(ItplNS(cmd, |
|
812 | # Load user aliases | |
815 | self.user_ns, # globals |
|
813 | for alias in self.alias: | |
816 | # Skip our own frame in searching for locals: |
|
814 | self.magic_alias(alias) | |
817 | sys._getframe(depth+1).f_locals # locals |
|
|||
818 | )) |
|
|||
819 |
|
815 | |||
820 |
def |
|
816 | def init_builtins(self): | |
821 | """Pre-configuration init method |
|
817 | self.builtin_trap = BuiltinTrap(self) | |
822 |
|
818 | |||
823 | This is called before the configuration files are processed to |
|
819 | def init_shadow_hist(self): | |
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 |
|
|||
829 | try: |
|
820 | try: | |
830 |
self.db = pickleshare.PickleShareDB( |
|
821 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") | |
831 | except exceptions.UnicodeDecodeError: |
|
822 | except exceptions.UnicodeDecodeError: | |
832 | print "Your ipythondir can't be decoded to unicode!" |
|
823 | print "Your ipythondir can't be decoded to unicode!" | |
833 | print "Please set HOME environment variable to something that" |
|
824 | print "Please set HOME environment variable to something that" | |
834 | print r"only has ASCII characters, e.g. c:\home" |
|
825 | print r"only has ASCII characters, e.g. c:\home" | |
835 |
print "Now it is", |
|
826 | print "Now it is", self.config.IPYTHONDIR | |
836 | sys.exit() |
|
827 | sys.exit() | |
837 |
self.shadowhist = |
|
828 | self.shadowhist = ipcorehist.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 |
|
|||
846 |
|
829 | |||
|
830 | def init_inspector(self): | |||
847 | # Object inspector |
|
831 | # Object inspector | |
848 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
832 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
849 | PyColorize.ANSICodeColors, |
|
833 | PyColorize.ANSICodeColors, | |
850 | 'NoColor', |
|
834 | 'NoColor', | |
851 |
|
|
835 | self.object_info_string_level) | |
852 |
|
836 | |||
|
837 | def init_readline(self): | |||
|
838 | """Command history completion/saving/reloading.""" | |||
|
839 | ||||
853 | self.rl_next_input = None |
|
840 | self.rl_next_input = None | |
854 | self.rl_do_indent = False |
|
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 | # Initialize cache, set in/out prompts and printing system |
|
924 | # Initialize cache, set in/out prompts and printing system | |
863 | self.outputcache = CachedOutput(self, |
|
925 | self.outputcache = CachedOutput(self, | |
864 |
|
|
926 | self.cache_size, | |
865 |
|
|
927 | self.pprint, | |
866 |
input_sep = |
|
928 | input_sep = self.separate_in, | |
867 |
output_sep = |
|
929 | output_sep = self.separate_out, | |
868 |
output_sep2 = |
|
930 | output_sep2 = self.separate_out2, | |
869 |
ps1 = |
|
931 | ps1 = self.prompt_in1, | |
870 |
ps2 = |
|
932 | ps2 = self.prompt_in2, | |
871 |
ps_out = |
|
933 | ps_out = self.prompt_out, | |
872 |
pad_left = |
|
934 | pad_left = self.prompts_pad_left) | |
873 |
|
935 | |||
874 | # user may have over-ridden the default print hook: |
|
936 | # user may have over-ridden the default print hook: | |
875 | try: |
|
937 | try: | |
876 | self.outputcache.__class__.display = self.hooks.display |
|
938 | self.outputcache.__class__.display = self.hooks.display | |
877 | except AttributeError: |
|
939 | except AttributeError: | |
878 | pass |
|
940 | pass | |
879 |
|
941 | |||
|
942 | def init_displayhook(self): | |||
880 | # I don't like assigning globally to sys, because it means when |
|
943 | # I don't like assigning globally to sys, because it means when | |
881 | # embedding instances, each embedded instance overrides the previous |
|
944 | # embedding instances, each embedded instance overrides the previous | |
882 | # choice. But sys.displayhook seems to be called internally by exec, |
|
945 | # choice. But sys.displayhook seems to be called internally by exec, | |
883 | # so I don't see a way around it. We first save the original and then |
|
946 | # so I don't see a way around it. We first save the original and then | |
884 | # overwrite it. |
|
947 | # overwrite it. | |
885 | self.sys_displayhook = sys.displayhook |
|
948 | self.sys_displayhook = sys.displayhook | |
886 | sys.displayhook = self.outputcache |
|
949 | sys.displayhook = self.outputcache | |
887 |
|
950 | |||
|
951 | def init_reload_doctest(self): | |||
888 | # Do a proper resetting of doctest, including the necessary displayhook |
|
952 | # Do a proper resetting of doctest, including the necessary displayhook | |
889 | # monkeypatching |
|
953 | # monkeypatching | |
890 | try: |
|
954 | try: | |
891 | doctest_reload() |
|
955 | doctest_reload() | |
892 | except ImportError: |
|
956 | except ImportError: | |
893 | warn("doctest module does not exist.") |
|
957 | warn("doctest module does not exist.") | |
894 |
|
958 | |||
|
959 | def init_magics(self): | |||
895 | # Set user colors (don't do it in the constructor above so that it |
|
960 | # Set user colors (don't do it in the constructor above so that it | |
896 | # doesn't crash if colors option is invalid) |
|
961 | # doesn't crash if colors option is invalid) | |
897 |
self.magic_colors( |
|
962 | self.magic_colors(self.colors) | |
898 |
|
963 | |||
|
964 | def init_pdb(self): | |||
899 | # Set calling of pdb on exceptions |
|
965 | # Set calling of pdb on exceptions | |
900 |
self.call_pdb |
|
966 | # self.call_pdb is a property | |
901 |
|
967 | self.call_pdb = self.pdb | ||
902 | # Load user aliases |
|
968 | ||
903 | for alias in rc.alias: |
|
969 | # def init_exec_commands(self): | |
904 | self.magic_alias(alias) |
|
970 | # for cmd in self.config.EXECUTE: | |
905 |
|
971 | # print "execute:", cmd | ||
906 | self.hooks.late_startup_hook() |
|
972 | # self.api.runlines(cmd) | |
907 |
|
973 | # | ||
908 | for cmd in self.rc.autoexec: |
|
974 | # batchrun = False | |
909 | #print "autoexec>",cmd #dbg |
|
975 | # if self.config.has_key('EXECFILE'): | |
910 | self.api.runlines(cmd) |
|
976 | # for batchfile in [path(arg) for arg in self.config.EXECFILE | |
911 |
|
977 | # if arg.lower().endswith('.ipy')]: | ||
912 | batchrun = False |
|
978 | # if not batchfile.isfile(): | |
913 | for batchfile in [path(arg) for arg in self.rc.args |
|
979 | # print "No such batch file:", batchfile | |
914 | if arg.lower().endswith('.ipy')]: |
|
980 | # continue | |
915 | if not batchfile.isfile(): |
|
981 | # self.api.runlines(batchfile.text()) | |
916 | print "No such batch file:", batchfile |
|
982 | # batchrun = True | |
917 | continue |
|
983 | # # without -i option, exit after running the batch file | |
918 | self.api.runlines(batchfile.text()) |
|
984 | # if batchrun and not self.interactive: | |
919 | batchrun = True |
|
985 | # self.ask_exit() | |
920 | # without -i option, exit after running the batch file |
|
986 | ||
921 | if batchrun and not self.rc.interact: |
|
987 | # def load(self, mod): | |
922 | self.ask_exit() |
|
988 | # """ Load an extension. | |
923 |
|
989 | # | ||
924 | def init_namespaces(self): |
|
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 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1020 | """Initialize all user-visible namespaces to their minimum defaults. | |
926 |
|
1021 | |||
927 | Certain history lists are also initialized here, as they effectively |
|
1022 | Certain history lists are also initialized here, as they effectively | |
928 | act as user namespaces. |
|
1023 | act as user namespaces. | |
929 |
|
1024 | |||
930 | Notes |
|
1025 | Notes | |
931 | ----- |
|
1026 | ----- | |
932 | All data structures here are only filled in, they are NOT reset by this |
|
1027 | All data structures here are only filled in, they are NOT reset by this | |
933 | method. If they were not empty before, data will simply be added to |
|
1028 | method. If they were not empty before, data will simply be added to | |
934 | therm. |
|
1029 | therm. | |
935 | """ |
|
1030 | """ | |
936 | # The user namespace MUST have a pointer to the shell itself. |
|
1031 | # The user namespace MUST have a pointer to the shell itself. | |
937 | self.user_ns[self.name] = self |
|
1032 | self.user_ns[self.name] = self | |
938 |
|
1033 | |||
939 |
# Store the public api |
|
1034 | # Store myself as the public api!!! | |
940 |
self.user_ns['_ip'] = self |
|
1035 | self.user_ns['_ip'] = self | |
941 |
|
1036 | |||
942 | # make global variables for user access to the histories |
|
1037 | # make global variables for user access to the histories | |
943 | self.user_ns['_ih'] = self.input_hist |
|
1038 | self.user_ns['_ih'] = self.input_hist | |
944 | self.user_ns['_oh'] = self.output_hist |
|
1039 | self.user_ns['_oh'] = self.output_hist | |
945 | self.user_ns['_dh'] = self.dir_hist |
|
1040 | self.user_ns['_dh'] = self.dir_hist | |
946 |
|
1041 | |||
947 | # user aliases to input and output histories |
|
1042 | # user aliases to input and output histories | |
948 | self.user_ns['In'] = self.input_hist |
|
1043 | self.user_ns['In'] = self.input_hist | |
949 | self.user_ns['Out'] = self.output_hist |
|
1044 | self.user_ns['Out'] = self.output_hist | |
950 |
|
1045 | |||
951 | self.user_ns['_sh'] = shadowns |
|
1046 | self.user_ns['_sh'] = shadowns | |
952 |
|
1047 | |||
953 | # Fill the history zero entry, user counter starts at 1 |
|
1048 | # Put 'help' in the user namespace | |
954 | self.input_hist.append('\n') |
|
1049 | try: | |
955 | self.input_hist_raw.append('\n') |
|
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 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
1088 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
999 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
1089 | """set_hook(name,hook) -> sets an internal IPython hook. | |
1000 |
|
1090 | |||
1001 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
1091 | IPython exposes some of its internal API as user-modifiable hooks. By | |
1002 | adding your function to one of these hooks, you can modify IPython's |
|
1092 | adding your function to one of these hooks, you can modify IPython's | |
1003 | behavior to call at runtime your own routines.""" |
|
1093 | behavior to call at runtime your own routines.""" | |
1004 |
|
1094 | |||
1005 | # At some point in the future, this should validate the hook before it |
|
1095 | # At some point in the future, this should validate the hook before it | |
1006 | # accepts it. Probably at least check that the hook takes the number |
|
1096 | # accepts it. Probably at least check that the hook takes the number | |
1007 | # of args it's supposed to. |
|
1097 | # of args it's supposed to. | |
1008 |
|
1098 | |||
1009 | f = new.instancemethod(hook,self,self.__class__) |
|
1099 | f = new.instancemethod(hook,self,self.__class__) | |
1010 |
|
1100 | |||
1011 | # check if the hook is for strdispatcher first |
|
1101 | # check if the hook is for strdispatcher first | |
1012 | if str_key is not None: |
|
1102 | if str_key is not None: | |
1013 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1103 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
1014 | sdp.add_s(str_key, f, priority ) |
|
1104 | sdp.add_s(str_key, f, priority ) | |
1015 | self.strdispatchers[name] = sdp |
|
1105 | self.strdispatchers[name] = sdp | |
1016 | return |
|
1106 | return | |
1017 | if re_key is not None: |
|
1107 | if re_key is not None: | |
1018 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1108 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
1019 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1109 | sdp.add_re(re.compile(re_key), f, priority ) | |
1020 | self.strdispatchers[name] = sdp |
|
1110 | self.strdispatchers[name] = sdp | |
1021 | return |
|
1111 | return | |
1022 |
|
1112 | |||
1023 | dp = getattr(self.hooks, name, None) |
|
1113 | dp = getattr(self.hooks, name, None) | |
1024 | if name not in IPython.core.hooks.__all__: |
|
1114 | if name not in IPython.core.hooks.__all__: | |
1025 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
1115 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
1026 | if not dp: |
|
1116 | if not dp: | |
1027 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
1117 | dp = IPython.core.hooks.CommandChainDispatcher() | |
1028 |
|
1118 | |||
1029 | try: |
|
1119 | try: | |
1030 | dp.add(f,priority) |
|
1120 | dp.add(f,priority) | |
1031 | except AttributeError: |
|
1121 | except AttributeError: | |
1032 | # it was not commandchain, plain old func - replace |
|
1122 | # it was not commandchain, plain old func - replace | |
1033 | dp = f |
|
1123 | dp = f | |
1034 |
|
1124 | |||
1035 | setattr(self.hooks,name, dp) |
|
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 | """Set the IPython crash handler. |
|
1128 | """Set the IPython crash handler. | |
1042 |
|
1129 | |||
1043 | This must be a callable with a signature suitable for use as |
|
1130 | This must be a callable with a signature suitable for use as | |
1044 | sys.excepthook.""" |
|
1131 | sys.excepthook.""" | |
1045 |
|
1132 | |||
1046 | # Install the given crash handler as the Python exception hook |
|
1133 | # Install the given crash handler as the Python exception hook | |
1047 | sys.excepthook = crashHandler |
|
1134 | sys.excepthook = crashHandler | |
1048 |
|
1135 | |||
1049 | # The instance will store a pointer to this, so that runtime code |
|
1136 | # The instance will store a pointer to this, so that runtime code | |
1050 | # (such as magics) can access it. This is because during the |
|
1137 | # (such as magics) can access it. This is because during the | |
1051 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1138 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
1052 | # frameworks). |
|
1139 | # frameworks). | |
1053 | self.sys_excepthook = sys.excepthook |
|
1140 | self.sys_excepthook = sys.excepthook | |
1054 |
|
1141 | |||
1055 |
|
||||
1056 | def set_custom_exc(self,exc_tuple,handler): |
|
1142 | def set_custom_exc(self,exc_tuple,handler): | |
1057 | """set_custom_exc(exc_tuple,handler) |
|
1143 | """set_custom_exc(exc_tuple,handler) | |
1058 |
|
1144 | |||
1059 | Set a custom exception handler, which will be called if any of the |
|
1145 | Set a custom exception handler, which will be called if any of the | |
1060 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1146 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1061 | runcode() method. |
|
1147 | runcode() method. | |
1062 |
|
1148 | |||
1063 | Inputs: |
|
1149 | Inputs: | |
1064 |
|
1150 | |||
1065 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1151 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1066 | handler for. It is very important that you use a tuple, and NOT A |
|
1152 | handler for. It is very important that you use a tuple, and NOT A | |
1067 | LIST here, because of the way Python's except statement works. If |
|
1153 | LIST here, because of the way Python's except statement works. If | |
1068 | you only want to trap a single exception, use a singleton tuple: |
|
1154 | you only want to trap a single exception, use a singleton tuple: | |
1069 |
|
1155 | |||
1070 | exc_tuple == (MyCustomException,) |
|
1156 | exc_tuple == (MyCustomException,) | |
1071 |
|
1157 | |||
1072 | - handler: this must be defined as a function with the following |
|
1158 | - handler: this must be defined as a function with the following | |
1073 | basic interface: def my_handler(self,etype,value,tb). |
|
1159 | basic interface: def my_handler(self,etype,value,tb). | |
1074 |
|
1160 | |||
1075 | This will be made into an instance method (via new.instancemethod) |
|
1161 | This will be made into an instance method (via new.instancemethod) | |
1076 | of IPython itself, and it will be called if any of the exceptions |
|
1162 | of IPython itself, and it will be called if any of the exceptions | |
1077 | listed in the exc_tuple are caught. If the handler is None, an |
|
1163 | listed in the exc_tuple are caught. If the handler is None, an | |
1078 | internal basic one is used, which just prints basic info. |
|
1164 | internal basic one is used, which just prints basic info. | |
1079 |
|
1165 | |||
1080 | WARNING: by putting in your own exception handler into IPython's main |
|
1166 | WARNING: by putting in your own exception handler into IPython's main | |
1081 | execution loop, you run a very good chance of nasty crashes. This |
|
1167 | execution loop, you run a very good chance of nasty crashes. This | |
1082 | facility should only be used if you really know what you are doing.""" |
|
1168 | facility should only be used if you really know what you are doing.""" | |
1083 |
|
1169 | |||
1084 | assert type(exc_tuple)==type(()) , \ |
|
1170 | assert type(exc_tuple)==type(()) , \ | |
1085 | "The custom exceptions must be given AS A TUPLE." |
|
1171 | "The custom exceptions must be given AS A TUPLE." | |
1086 |
|
1172 | |||
1087 | def dummy_handler(self,etype,value,tb): |
|
1173 | def dummy_handler(self,etype,value,tb): | |
1088 | print '*** Simple custom exception handler ***' |
|
1174 | print '*** Simple custom exception handler ***' | |
1089 | print 'Exception type :',etype |
|
1175 | print 'Exception type :',etype | |
1090 | print 'Exception value:',value |
|
1176 | print 'Exception value:',value | |
1091 | print 'Traceback :',tb |
|
1177 | print 'Traceback :',tb | |
1092 | print 'Source code :','\n'.join(self.buffer) |
|
1178 | print 'Source code :','\n'.join(self.buffer) | |
1093 |
|
1179 | |||
1094 | if handler is None: handler = dummy_handler |
|
1180 | if handler is None: handler = dummy_handler | |
1095 |
|
1181 | |||
1096 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1182 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1097 | self.custom_exceptions = exc_tuple |
|
1183 | self.custom_exceptions = exc_tuple | |
1098 |
|
1184 | |||
1099 | def set_custom_completer(self,completer,pos=0): |
|
1185 | def set_custom_completer(self,completer,pos=0): | |
1100 | """set_custom_completer(completer,pos=0) |
|
1186 | """set_custom_completer(completer,pos=0) | |
1101 |
|
1187 | |||
1102 | Adds a new custom completer function. |
|
1188 | Adds a new custom completer function. | |
1103 |
|
1189 | |||
1104 | The position argument (defaults to 0) is the index in the completers |
|
1190 | The position argument (defaults to 0) is the index in the completers | |
1105 | list where you want the completer to be inserted.""" |
|
1191 | list where you want the completer to be inserted.""" | |
1106 |
|
1192 | |||
1107 | newcomp = new.instancemethod(completer,self.Completer, |
|
1193 | newcomp = new.instancemethod(completer,self.Completer, | |
1108 | self.Completer.__class__) |
|
1194 | self.Completer.__class__) | |
1109 | self.Completer.matchers.insert(pos,newcomp) |
|
1195 | self.Completer.matchers.insert(pos,newcomp) | |
1110 |
|
1196 | |||
1111 | def set_completer(self): |
|
1197 | def set_completer(self): | |
1112 | """reset readline's completer to be our own.""" |
|
1198 | """reset readline's completer to be our own.""" | |
1113 | self.readline.set_completer(self.Completer.complete) |
|
1199 | self.readline.set_completer(self.Completer.complete) | |
1114 |
|
1200 | |||
1115 | def _get_call_pdb(self): |
|
1201 | def _get_call_pdb(self): | |
1116 | return self._call_pdb |
|
1202 | return self._call_pdb | |
1117 |
|
1203 | |||
1118 | def _set_call_pdb(self,val): |
|
1204 | def _set_call_pdb(self,val): | |
1119 |
|
1205 | |||
1120 | if val not in (0,1,False,True): |
|
1206 | if val not in (0,1,False,True): | |
1121 | raise ValueError,'new call_pdb value must be boolean' |
|
1207 | raise ValueError,'new call_pdb value must be boolean' | |
1122 |
|
1208 | |||
1123 | # store value in instance |
|
1209 | # store value in instance | |
1124 | self._call_pdb = val |
|
1210 | self._call_pdb = val | |
1125 |
|
1211 | |||
1126 | # notify the actual exception handlers |
|
1212 | # notify the actual exception handlers | |
1127 | self.InteractiveTB.call_pdb = val |
|
1213 | self.InteractiveTB.call_pdb = val | |
1128 | if self.isthreaded: |
|
1214 | if self.isthreaded: | |
1129 | try: |
|
1215 | try: | |
1130 | self.sys_excepthook.call_pdb = val |
|
1216 | self.sys_excepthook.call_pdb = val | |
1131 | except: |
|
1217 | except: | |
1132 | warn('Failed to activate pdb for threaded exception handler') |
|
1218 | warn('Failed to activate pdb for threaded exception handler') | |
1133 |
|
1219 | |||
1134 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1220 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
1135 | 'Control auto-activation of pdb at exceptions') |
|
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 |
|
1223 | def magic(self,arg_s): | |
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): |
|
|||
1147 | """Call a magic function by name. |
|
1224 | """Call a magic function by name. | |
1148 |
|
1225 | |||
1149 | Input: a string containing the name of the magic function to call and any |
|
1226 | Input: a string containing the name of the magic function to call and any | |
1150 | additional arguments to be passed to the magic. |
|
1227 | additional arguments to be passed to the magic. | |
1151 |
|
1228 | |||
1152 |
|
|
1229 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1153 | prompt: |
|
1230 | prompt: | |
1154 |
|
1231 | |||
1155 | In[1]: %name -opt foo bar |
|
1232 | In[1]: %name -opt foo bar | |
1156 |
|
1233 | |||
1157 |
To call a magic without arguments, simply use |
|
1234 | To call a magic without arguments, simply use magic('name'). | |
1158 |
|
1235 | |||
1159 | This provides a proper Python function to call IPython's magics in any |
|
1236 | This provides a proper Python function to call IPython's magics in any | |
1160 | valid Python code you can type at the interpreter, including loops and |
|
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 |
|
1238 | compound statements. | |
1162 | namespace upon initialization.""" |
|
1239 | """ | |
1163 |
|
1240 | |||
1164 | args = arg_s.split(' ',1) |
|
1241 | args = arg_s.split(' ',1) | |
1165 | magic_name = args[0] |
|
1242 | magic_name = args[0] | |
1166 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1243 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
1167 |
|
1244 | |||
1168 | try: |
|
1245 | try: | |
1169 | magic_args = args[1] |
|
1246 | magic_args = args[1] | |
1170 | except IndexError: |
|
1247 | except IndexError: | |
1171 | magic_args = '' |
|
1248 | magic_args = '' | |
1172 | fn = getattr(self,'magic_'+magic_name,None) |
|
1249 | fn = getattr(self,'magic_'+magic_name,None) | |
1173 | if fn is None: |
|
1250 | if fn is None: | |
1174 | error("Magic function `%s` not found." % magic_name) |
|
1251 | error("Magic function `%s` not found." % magic_name) | |
1175 | else: |
|
1252 | else: | |
1176 | magic_args = self.var_expand(magic_args,1) |
|
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 | def ipalias(self,arg_s): |
|
1316 | def ipalias(self,arg_s): | |
1180 | """Call an alias by name. |
|
1317 | """Call an alias by name. | |
1181 |
|
1318 | |||
1182 | Input: a string containing the name of the alias to call and any |
|
1319 | Input: a string containing the name of the alias to call and any | |
1183 | additional arguments to be passed to the magic. |
|
1320 | additional arguments to be passed to the magic. | |
1184 |
|
1321 | |||
1185 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1322 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
1186 | prompt: |
|
1323 | prompt: | |
1187 |
|
1324 | |||
1188 | In[1]: name -opt foo bar |
|
1325 | In[1]: name -opt foo bar | |
1189 |
|
1326 | |||
1190 | To call an alias without arguments, simply use ipalias('name'). |
|
1327 | To call an alias without arguments, simply use ipalias('name'). | |
1191 |
|
1328 | |||
1192 | This provides a proper Python function to call IPython's aliases in any |
|
1329 | This provides a proper Python function to call IPython's aliases in any | |
1193 | valid Python code you can type at the interpreter, including loops and |
|
1330 | valid Python code you can type at the interpreter, including loops and | |
1194 | compound statements. It is added by IPython to the Python builtin |
|
1331 | compound statements. It is added by IPython to the Python builtin | |
1195 | namespace upon initialization.""" |
|
1332 | namespace upon initialization.""" | |
1196 |
|
1333 | |||
1197 | args = arg_s.split(' ',1) |
|
1334 | args = arg_s.split(' ',1) | |
1198 | alias_name = args[0] |
|
1335 | alias_name = args[0] | |
1199 | try: |
|
1336 | try: | |
1200 | alias_args = args[1] |
|
1337 | alias_args = args[1] | |
1201 | except IndexError: |
|
1338 | except IndexError: | |
1202 | alias_args = '' |
|
1339 | alias_args = '' | |
1203 | if alias_name in self.alias_table: |
|
1340 | if alias_name in self.alias_table: | |
1204 | self.call_alias(alias_name,alias_args) |
|
1341 | self.call_alias(alias_name,alias_args) | |
1205 | else: |
|
1342 | else: | |
1206 | error("Alias `%s` not found." % alias_name) |
|
1343 | error("Alias `%s` not found." % alias_name) | |
1207 |
|
1344 | |||
1208 |
def |
|
1345 | def system(self, cmd): | |
1209 | """Make a system call, using IPython.""" |
|
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 | """Return a sorted list of all possible completions on text. |
|
1374 | """Return a sorted list of all possible completions on text. | |
1215 |
|
1375 | |||
1216 | Inputs: |
|
1376 | Inputs: | |
1217 |
|
1377 | |||
1218 | - text: a string of text to be completed on. |
|
1378 | - text: a string of text to be completed on. | |
1219 |
|
1379 | |||
1220 | This is a wrapper around the completion mechanism, similar to what |
|
1380 | This is a wrapper around the completion mechanism, similar to what | |
1221 | readline does at the command line when the TAB key is hit. By |
|
1381 | readline does at the command line when the TAB key is hit. By | |
1222 | exposing it as a method, it can be used by other non-readline |
|
1382 | exposing it as a method, it can be used by other non-readline | |
1223 | environments (such as GUIs) for text completion. |
|
1383 | environments (such as GUIs) for text completion. | |
1224 |
|
1384 | |||
1225 | Simple usage example: |
|
1385 | Simple usage example: | |
1226 |
|
1386 | |||
1227 | In [7]: x = 'hello' |
|
1387 | In [7]: x = 'hello' | |
1228 |
|
1388 | |||
1229 | In [8]: x |
|
1389 | In [8]: x | |
1230 | Out[8]: 'hello' |
|
1390 | Out[8]: 'hello' | |
1231 |
|
1391 | |||
1232 | In [9]: print x |
|
1392 | In [9]: print x | |
1233 | hello |
|
1393 | hello | |
1234 |
|
1394 | |||
1235 |
In [10]: _ip. |
|
1395 | In [10]: _ip.complete('x.l') | |
1236 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1396 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1237 | """ |
|
1397 | """ | |
1238 |
|
1398 | |||
1239 | complete = self.Completer.complete |
|
1399 | # Inject names into __builtin__ so we can complete on the added names. | |
1240 | state = 0 |
|
1400 | with self.builtin_trap: | |
1241 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1401 | complete = self.Completer.complete | |
1242 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1402 | state = 0 | |
1243 | # start using sets instead, which are faster. |
|
1403 | # use a dict so we get unique keys, since ipyhton's multiple | |
1244 | comps = {} |
|
1404 | # completers can return duplicates. When we make 2.4 a requirement, | |
1245 | while True: |
|
1405 | # start using sets instead, which are faster. | |
1246 | newcomp = complete(text,state,line_buffer=text) |
|
1406 | comps = {} | |
1247 | if newcomp is None: |
|
1407 | while True: | |
1248 | break |
|
1408 | newcomp = complete(text,state,line_buffer=text) | |
1249 |
|
|
1409 | if newcomp is None: | |
1250 | state += 1 |
|
1410 | break | |
1251 | outcomps = comps.keys() |
|
1411 | comps[newcomp] = 1 | |
1252 | outcomps.sort() |
|
1412 | state += 1 | |
1253 | #print "T:",text,"OC:",outcomps # dbg |
|
1413 | outcomps = comps.keys() | |
1254 | #print "vars:",self.user_ns.keys() |
|
1414 | outcomps.sort() | |
|
1415 | #print "T:",text,"OC:",outcomps # dbg | |||
|
1416 | #print "vars:",self.user_ns.keys() | |||
1255 | return outcomps |
|
1417 | return outcomps | |
1256 |
|
1418 | |||
1257 | def set_completer_frame(self, frame=None): |
|
1419 | def set_completer_frame(self, frame=None): | |
1258 | if frame: |
|
1420 | if frame: | |
1259 | self.Completer.namespace = frame.f_locals |
|
1421 | self.Completer.namespace = frame.f_locals | |
1260 | self.Completer.global_namespace = frame.f_globals |
|
1422 | self.Completer.global_namespace = frame.f_globals | |
1261 | else: |
|
1423 | else: | |
1262 | self.Completer.namespace = self.user_ns |
|
1424 | self.Completer.namespace = self.user_ns | |
1263 | self.Completer.global_namespace = self.user_global_ns |
|
1425 | self.Completer.global_namespace = self.user_global_ns | |
1264 |
|
1426 | |||
1265 | def init_auto_alias(self): |
|
1427 | def init_auto_alias(self): | |
1266 | """Define some aliases automatically. |
|
1428 | """Define some aliases automatically. | |
1267 |
|
1429 | |||
1268 | These are ALL parameter-less aliases""" |
|
1430 | These are ALL parameter-less aliases""" | |
1269 |
|
1431 | |||
1270 | for alias,cmd in self.auto_alias: |
|
1432 | for alias,cmd in self.auto_alias: | |
1271 |
self. |
|
1433 | self.define_alias(alias,cmd) | |
1272 |
|
||||
1273 |
|
1434 | |||
1274 | def alias_table_validate(self,verbose=0): |
|
1435 | def alias_table_validate(self,verbose=0): | |
1275 | """Update information about the alias table. |
|
1436 | """Update information about the alias table. | |
1276 |
|
1437 | |||
1277 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1438 | In particular, make sure no Python keywords/builtins are in it.""" | |
1278 |
|
1439 | |||
1279 | no_alias = self.no_alias |
|
1440 | no_alias = self.no_alias | |
1280 | for k in self.alias_table.keys(): |
|
1441 | for k in self.alias_table.keys(): | |
1281 | if k in no_alias: |
|
1442 | if k in no_alias: | |
1282 | del self.alias_table[k] |
|
1443 | del self.alias_table[k] | |
1283 | if verbose: |
|
1444 | if verbose: | |
1284 | print ("Deleting alias <%s>, it's a Python " |
|
1445 | print ("Deleting alias <%s>, it's a Python " | |
1285 | "keyword or builtin." % k) |
|
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 | def set_autoindent(self,value=None): |
|
1461 | def set_autoindent(self,value=None): | |
1288 | """Set the autoindent flag, checking for readline support. |
|
1462 | """Set the autoindent flag, checking for readline support. | |
1289 |
|
1463 | |||
1290 | If called with no arguments, it acts as a toggle.""" |
|
1464 | If called with no arguments, it acts as a toggle.""" | |
1291 |
|
1465 | |||
1292 | if not self.has_readline: |
|
1466 | if not self.has_readline: | |
1293 | if os.name == 'posix': |
|
1467 | if os.name == 'posix': | |
1294 | warn("The auto-indent feature requires the readline library") |
|
1468 | warn("The auto-indent feature requires the readline library") | |
1295 | self.autoindent = 0 |
|
1469 | self.autoindent = 0 | |
1296 | return |
|
1470 | return | |
1297 | if value is None: |
|
1471 | if value is None: | |
1298 | self.autoindent = not self.autoindent |
|
1472 | self.autoindent = not self.autoindent | |
1299 | else: |
|
1473 | else: | |
1300 | self.autoindent = value |
|
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 | def atexit_operations(self): |
|
1476 | def atexit_operations(self): | |
1325 | """This will be executed at the time of exit. |
|
1477 | """This will be executed at the time of exit. | |
1326 |
|
1478 | |||
1327 | Saving of persistent data should be performed here. """ |
|
1479 | Saving of persistent data should be performed here. """ | |
1328 |
|
1480 | |||
1329 | #print '*** IPython exit cleanup ***' # dbg |
|
1481 | #print '*** IPython exit cleanup ***' # dbg | |
1330 | # input history |
|
1482 | # input history | |
1331 | self.savehist() |
|
1483 | self.savehist() | |
1332 |
|
1484 | |||
1333 | # Cleanup all tempfiles left around |
|
1485 | # Cleanup all tempfiles left around | |
1334 | for tfile in self.tempfiles: |
|
1486 | for tfile in self.tempfiles: | |
1335 | try: |
|
1487 | try: | |
1336 | os.unlink(tfile) |
|
1488 | os.unlink(tfile) | |
1337 | except OSError: |
|
1489 | except OSError: | |
1338 | pass |
|
1490 | pass | |
1339 |
|
1491 | |||
1340 | # Clear all user namespaces to release all references cleanly. |
|
1492 | # Clear all user namespaces to release all references cleanly. | |
1341 | self.reset() |
|
1493 | self.reset() | |
1342 |
|
1494 | |||
1343 | # Run user hooks |
|
1495 | # Run user hooks | |
1344 | self.hooks.shutdown_hook() |
|
1496 | self.hooks.shutdown_hook() | |
1345 |
|
1497 | |||
1346 | def reset(self): |
|
1498 | def reset(self): | |
1347 | """Clear all internal namespaces. |
|
1499 | """Clear all internal namespaces. | |
1348 |
|
1500 | |||
1349 | Note that this is much more aggressive than %reset, since it clears |
|
1501 | Note that this is much more aggressive than %reset, since it clears | |
1350 | fully all namespaces, as well as all input/output lists. |
|
1502 | fully all namespaces, as well as all input/output lists. | |
1351 | """ |
|
1503 | """ | |
1352 | for ns in self.ns_refs_table: |
|
1504 | for ns in self.ns_refs_table: | |
1353 | ns.clear() |
|
1505 | ns.clear() | |
1354 |
|
1506 | |||
1355 | # Clear input and output histories |
|
1507 | # Clear input and output histories | |
1356 | self.input_hist[:] = [] |
|
1508 | self.input_hist[:] = [] | |
1357 | self.input_hist_raw[:] = [] |
|
1509 | self.input_hist_raw[:] = [] | |
1358 | self.output_hist.clear() |
|
1510 | self.output_hist.clear() | |
1359 | # Restore the user namespaces to minimal usability |
|
1511 | # Restore the user namespaces to minimal usability | |
1360 |
self.init_ |
|
1512 | self.init_user_ns() | |
1361 |
|
1513 | |||
1362 | def savehist(self): |
|
1514 | def savehist(self): | |
1363 | """Save input history to a file (via readline library).""" |
|
1515 | """Save input history to a file (via readline library).""" | |
1364 |
|
1516 | |||
1365 | if not self.has_readline: |
|
1517 | if not self.has_readline: | |
1366 | return |
|
1518 | return | |
1367 |
|
1519 | |||
1368 | try: |
|
1520 | try: | |
1369 | self.readline.write_history_file(self.histfile) |
|
1521 | self.readline.write_history_file(self.histfile) | |
1370 | except: |
|
1522 | except: | |
1371 | print 'Unable to save IPython command history to file: ' + \ |
|
1523 | print 'Unable to save IPython command history to file: ' + \ | |
1372 | `self.histfile` |
|
1524 | `self.histfile` | |
1373 |
|
1525 | |||
1374 | def reloadhist(self): |
|
1526 | def reloadhist(self): | |
1375 | """Reload the input history from disk file.""" |
|
1527 | """Reload the input history from disk file.""" | |
1376 |
|
1528 | |||
1377 | if self.has_readline: |
|
1529 | if self.has_readline: | |
1378 | try: |
|
1530 | try: | |
1379 | self.readline.clear_history() |
|
1531 | self.readline.clear_history() | |
1380 | self.readline.read_history_file(self.shell.histfile) |
|
1532 | self.readline.read_history_file(self.shell.histfile) | |
1381 | except AttributeError: |
|
1533 | except AttributeError: | |
1382 | pass |
|
1534 | pass | |
1383 |
|
1535 | |||
1384 |
|
1536 | |||
1385 | def history_saving_wrapper(self, func): |
|
1537 | def history_saving_wrapper(self, func): | |
1386 | """ Wrap func for readline history saving |
|
1538 | """ Wrap func for readline history saving | |
1387 |
|
1539 | |||
1388 | Convert func into callable that saves & restores |
|
1540 | Convert func into callable that saves & restores | |
1389 | history around the call """ |
|
1541 | history around the call """ | |
1390 |
|
1542 | |||
1391 | if not self.has_readline: |
|
1543 | if not self.has_readline: | |
1392 | return func |
|
1544 | return func | |
1393 |
|
1545 | |||
1394 | def wrapper(): |
|
1546 | def wrapper(): | |
1395 | self.savehist() |
|
1547 | self.savehist() | |
1396 | try: |
|
1548 | try: | |
1397 | func() |
|
1549 | func() | |
1398 | finally: |
|
1550 | finally: | |
1399 | readline.read_history_file(self.histfile) |
|
1551 | readline.read_history_file(self.histfile) | |
1400 | return wrapper |
|
1552 | return wrapper | |
1401 |
|
1553 | |||
1402 | def pre_readline(self): |
|
1554 | def pre_readline(self): | |
1403 | """readline hook to be used at the start of each line. |
|
1555 | """readline hook to be used at the start of each line. | |
1404 |
|
1556 | |||
1405 | Currently it handles auto-indent only.""" |
|
1557 | Currently it handles auto-indent only.""" | |
1406 |
|
1558 | |||
1407 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1559 | #debugx('self.indent_current_nsp','pre_readline:') | |
1408 |
|
1560 | |||
1409 | if self.rl_do_indent: |
|
1561 | if self.rl_do_indent: | |
1410 | self.readline.insert_text(self.indent_current_str()) |
|
1562 | self.readline.insert_text(self.indent_current_str()) | |
1411 | if self.rl_next_input is not None: |
|
1563 | if self.rl_next_input is not None: | |
1412 | self.readline.insert_text(self.rl_next_input) |
|
1564 | self.readline.insert_text(self.rl_next_input) | |
1413 | self.rl_next_input = None |
|
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 | def ask_yes_no(self,prompt,default=True): |
|
1567 | def ask_yes_no(self,prompt,default=True): | |
1497 |
if self. |
|
1568 | if self.quiet: | |
1498 | return True |
|
1569 | return True | |
1499 | return ask_yes_no(prompt,default) |
|
1570 | return ask_yes_no(prompt,default) | |
1500 |
|
1571 | |||
1501 | def new_main_mod(self,ns=None): |
|
1572 | def new_main_mod(self,ns=None): | |
1502 | """Return a new 'main' module object for user code execution. |
|
1573 | """Return a new 'main' module object for user code execution. | |
1503 | """ |
|
1574 | """ | |
1504 | main_mod = self._user_main_module |
|
1575 | main_mod = self._user_main_module | |
1505 | init_fakemod_dict(main_mod,ns) |
|
1576 | init_fakemod_dict(main_mod,ns) | |
1506 | return main_mod |
|
1577 | return main_mod | |
1507 |
|
1578 | |||
1508 | def cache_main_mod(self,ns,fname): |
|
1579 | def cache_main_mod(self,ns,fname): | |
1509 | """Cache a main module's namespace. |
|
1580 | """Cache a main module's namespace. | |
1510 |
|
1581 | |||
1511 | When scripts are executed via %run, we must keep a reference to the |
|
1582 | When scripts are executed via %run, we must keep a reference to the | |
1512 | namespace of their __main__ module (a FakeModule instance) around so |
|
1583 | namespace of their __main__ module (a FakeModule instance) around so | |
1513 | that Python doesn't clear it, rendering objects defined therein |
|
1584 | that Python doesn't clear it, rendering objects defined therein | |
1514 | useless. |
|
1585 | useless. | |
1515 |
|
1586 | |||
1516 | This method keeps said reference in a private dict, keyed by the |
|
1587 | This method keeps said reference in a private dict, keyed by the | |
1517 | absolute path of the module object (which corresponds to the script |
|
1588 | absolute path of the module object (which corresponds to the script | |
1518 | path). This way, for multiple executions of the same script we only |
|
1589 | path). This way, for multiple executions of the same script we only | |
1519 | keep one copy of the namespace (the last one), thus preventing memory |
|
1590 | keep one copy of the namespace (the last one), thus preventing memory | |
1520 | leaks from old references while allowing the objects from the last |
|
1591 | leaks from old references while allowing the objects from the last | |
1521 | execution to be accessible. |
|
1592 | execution to be accessible. | |
1522 |
|
1593 | |||
1523 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
1594 | Note: we can not allow the actual FakeModule instances to be deleted, | |
1524 | because of how Python tears down modules (it hard-sets all their |
|
1595 | because of how Python tears down modules (it hard-sets all their | |
1525 | references to None without regard for reference counts). This method |
|
1596 | references to None without regard for reference counts). This method | |
1526 | must therefore make a *copy* of the given namespace, to allow the |
|
1597 | must therefore make a *copy* of the given namespace, to allow the | |
1527 | original module's __dict__ to be cleared and reused. |
|
1598 | original module's __dict__ to be cleared and reused. | |
1528 |
|
1599 | |||
1529 |
|
1600 | |||
1530 | Parameters |
|
1601 | Parameters | |
1531 | ---------- |
|
1602 | ---------- | |
1532 | ns : a namespace (a dict, typically) |
|
1603 | ns : a namespace (a dict, typically) | |
1533 |
|
1604 | |||
1534 | fname : str |
|
1605 | fname : str | |
1535 | Filename associated with the namespace. |
|
1606 | Filename associated with the namespace. | |
1536 |
|
1607 | |||
1537 | Examples |
|
1608 | Examples | |
1538 | -------- |
|
1609 | -------- | |
1539 |
|
1610 | |||
1540 | In [10]: import IPython |
|
1611 | In [10]: import IPython | |
1541 |
|
1612 | |||
1542 |
In [11]: _ip. |
|
1613 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
1543 |
|
1614 | |||
1544 |
In [12]: IPython.__file__ in _ip. |
|
1615 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
1545 | Out[12]: True |
|
1616 | Out[12]: True | |
1546 | """ |
|
1617 | """ | |
1547 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
1618 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
1548 |
|
1619 | |||
1549 | def clear_main_mod_cache(self): |
|
1620 | def clear_main_mod_cache(self): | |
1550 | """Clear the cache of main modules. |
|
1621 | """Clear the cache of main modules. | |
1551 |
|
1622 | |||
1552 | Mainly for use by utilities like %reset. |
|
1623 | Mainly for use by utilities like %reset. | |
1553 |
|
1624 | |||
1554 | Examples |
|
1625 | Examples | |
1555 | -------- |
|
1626 | -------- | |
1556 |
|
1627 | |||
1557 | In [15]: import IPython |
|
1628 | In [15]: import IPython | |
1558 |
|
1629 | |||
1559 |
In [16]: _ip. |
|
1630 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
1560 |
|
1631 | |||
1561 |
In [17]: len(_ip. |
|
1632 | In [17]: len(_ip._main_ns_cache) > 0 | |
1562 | Out[17]: True |
|
1633 | Out[17]: True | |
1563 |
|
1634 | |||
1564 |
In [18]: _ip. |
|
1635 | In [18]: _ip.clear_main_mod_cache() | |
1565 |
|
1636 | |||
1566 |
In [19]: len(_ip. |
|
1637 | In [19]: len(_ip._main_ns_cache) == 0 | |
1567 | Out[19]: True |
|
1638 | Out[19]: True | |
1568 | """ |
|
1639 | """ | |
1569 | self._main_ns_cache.clear() |
|
1640 | self._main_ns_cache.clear() | |
1570 |
|
1641 | |||
1571 | def _should_recompile(self,e): |
|
1642 | def _should_recompile(self,e): | |
1572 | """Utility routine for edit_syntax_error""" |
|
1643 | """Utility routine for edit_syntax_error""" | |
1573 |
|
1644 | |||
1574 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1645 | if e.filename in ('<ipython console>','<input>','<string>', | |
1575 | '<console>','<BackgroundJob compilation>', |
|
1646 | '<console>','<BackgroundJob compilation>', | |
1576 | None): |
|
1647 | None): | |
1577 |
|
1648 | |||
1578 | return False |
|
1649 | return False | |
1579 | try: |
|
1650 | try: | |
1580 |
if (self. |
|
1651 | if (self.autoedit_syntax and | |
1581 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1652 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1582 | '[Y/n] ','y')): |
|
1653 | '[Y/n] ','y')): | |
1583 | return False |
|
1654 | return False | |
1584 | except EOFError: |
|
1655 | except EOFError: | |
1585 | return False |
|
1656 | return False | |
1586 |
|
1657 | |||
1587 | def int0(x): |
|
1658 | def int0(x): | |
1588 | try: |
|
1659 | try: | |
1589 | return int(x) |
|
1660 | return int(x) | |
1590 | except TypeError: |
|
1661 | except TypeError: | |
1591 | return 0 |
|
1662 | return 0 | |
1592 | # always pass integer line and offset values to editor hook |
|
1663 | # always pass integer line and offset values to editor hook | |
1593 | try: |
|
1664 | try: | |
1594 | self.hooks.fix_error_editor(e.filename, |
|
1665 | self.hooks.fix_error_editor(e.filename, | |
1595 | int0(e.lineno),int0(e.offset),e.msg) |
|
1666 | int0(e.lineno),int0(e.offset),e.msg) | |
1596 |
except |
|
1667 | except TryNext: | |
1597 | warn('Could not open editor') |
|
1668 | warn('Could not open editor') | |
1598 | return False |
|
1669 | return False | |
1599 | return True |
|
1670 | return True | |
1600 |
|
1671 | |||
1601 | def edit_syntax_error(self): |
|
1672 | def edit_syntax_error(self): | |
1602 | """The bottom half of the syntax error handler called in the main loop. |
|
1673 | """The bottom half of the syntax error handler called in the main loop. | |
1603 |
|
1674 | |||
1604 | Loop until syntax error is fixed or user cancels. |
|
1675 | Loop until syntax error is fixed or user cancels. | |
1605 | """ |
|
1676 | """ | |
1606 |
|
1677 | |||
1607 | while self.SyntaxTB.last_syntax_error: |
|
1678 | while self.SyntaxTB.last_syntax_error: | |
1608 | # copy and clear last_syntax_error |
|
1679 | # copy and clear last_syntax_error | |
1609 | err = self.SyntaxTB.clear_err_state() |
|
1680 | err = self.SyntaxTB.clear_err_state() | |
1610 | if not self._should_recompile(err): |
|
1681 | if not self._should_recompile(err): | |
1611 | return |
|
1682 | return | |
1612 | try: |
|
1683 | try: | |
1613 | # may set last_syntax_error again if a SyntaxError is raised |
|
1684 | # may set last_syntax_error again if a SyntaxError is raised | |
1614 | self.safe_execfile(err.filename,self.user_ns) |
|
1685 | self.safe_execfile(err.filename,self.user_ns) | |
1615 | except: |
|
1686 | except: | |
1616 | self.showtraceback() |
|
1687 | self.showtraceback() | |
1617 | else: |
|
1688 | else: | |
1618 | try: |
|
1689 | try: | |
1619 | f = file(err.filename) |
|
1690 | f = file(err.filename) | |
1620 | try: |
|
1691 | try: | |
1621 | sys.displayhook(f.read()) |
|
1692 | sys.displayhook(f.read()) | |
1622 | finally: |
|
1693 | finally: | |
1623 | f.close() |
|
1694 | f.close() | |
1624 | except: |
|
1695 | except: | |
1625 | self.showtraceback() |
|
1696 | self.showtraceback() | |
1626 |
|
1697 | |||
1627 | def showsyntaxerror(self, filename=None): |
|
1698 | def showsyntaxerror(self, filename=None): | |
1628 | """Display the syntax error that just occurred. |
|
1699 | """Display the syntax error that just occurred. | |
1629 |
|
1700 | |||
1630 | This doesn't display a stack trace because there isn't one. |
|
1701 | This doesn't display a stack trace because there isn't one. | |
1631 |
|
1702 | |||
1632 | If a filename is given, it is stuffed in the exception instead |
|
1703 | If a filename is given, it is stuffed in the exception instead | |
1633 | of what was there before (because Python's parser always uses |
|
1704 | of what was there before (because Python's parser always uses | |
1634 | "<string>" when reading from a string). |
|
1705 | "<string>" when reading from a string). | |
1635 | """ |
|
1706 | """ | |
1636 | etype, value, last_traceback = sys.exc_info() |
|
1707 | etype, value, last_traceback = sys.exc_info() | |
1637 |
|
1708 | |||
1638 | # See note about these variables in showtraceback() below |
|
1709 | # See note about these variables in showtraceback() below | |
1639 | sys.last_type = etype |
|
1710 | sys.last_type = etype | |
1640 | sys.last_value = value |
|
1711 | sys.last_value = value | |
1641 | sys.last_traceback = last_traceback |
|
1712 | sys.last_traceback = last_traceback | |
1642 |
|
1713 | |||
1643 | if filename and etype is SyntaxError: |
|
1714 | if filename and etype is SyntaxError: | |
1644 | # Work hard to stuff the correct filename in the exception |
|
1715 | # Work hard to stuff the correct filename in the exception | |
1645 | try: |
|
1716 | try: | |
1646 | msg, (dummy_filename, lineno, offset, line) = value |
|
1717 | msg, (dummy_filename, lineno, offset, line) = value | |
1647 | except: |
|
1718 | except: | |
1648 | # Not the format we expect; leave it alone |
|
1719 | # Not the format we expect; leave it alone | |
1649 | pass |
|
1720 | pass | |
1650 | else: |
|
1721 | else: | |
1651 | # Stuff in the right filename |
|
1722 | # Stuff in the right filename | |
1652 | try: |
|
1723 | try: | |
1653 | # Assume SyntaxError is a class exception |
|
1724 | # Assume SyntaxError is a class exception | |
1654 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1725 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1655 | except: |
|
1726 | except: | |
1656 | # If that failed, assume SyntaxError is a string |
|
1727 | # If that failed, assume SyntaxError is a string | |
1657 | value = msg, (filename, lineno, offset, line) |
|
1728 | value = msg, (filename, lineno, offset, line) | |
1658 | self.SyntaxTB(etype,value,[]) |
|
1729 | self.SyntaxTB(etype,value,[]) | |
1659 |
|
1730 | |||
1660 | def debugger(self,force=False): |
|
1731 | def debugger(self,force=False): | |
1661 | """Call the pydb/pdb debugger. |
|
1732 | """Call the pydb/pdb debugger. | |
1662 |
|
1733 | |||
1663 | Keywords: |
|
1734 | Keywords: | |
1664 |
|
1735 | |||
1665 | - force(False): by default, this routine checks the instance call_pdb |
|
1736 | - force(False): by default, this routine checks the instance call_pdb | |
1666 | flag and does not actually invoke the debugger if the flag is false. |
|
1737 | flag and does not actually invoke the debugger if the flag is false. | |
1667 | The 'force' option forces the debugger to activate even if the flag |
|
1738 | The 'force' option forces the debugger to activate even if the flag | |
1668 | is false. |
|
1739 | is false. | |
1669 | """ |
|
1740 | """ | |
1670 |
|
1741 | |||
1671 | if not (force or self.call_pdb): |
|
1742 | if not (force or self.call_pdb): | |
1672 | return |
|
1743 | return | |
1673 |
|
1744 | |||
1674 | if not hasattr(sys,'last_traceback'): |
|
1745 | if not hasattr(sys,'last_traceback'): | |
1675 | error('No traceback has been produced, nothing to debug.') |
|
1746 | error('No traceback has been produced, nothing to debug.') | |
1676 | return |
|
1747 | return | |
1677 |
|
1748 | |||
1678 | # use pydb if available |
|
1749 | # use pydb if available | |
1679 | if debugger.has_pydb: |
|
1750 | if debugger.has_pydb: | |
1680 | from pydb import pm |
|
1751 | from pydb import pm | |
1681 | else: |
|
1752 | else: | |
1682 | # fallback to our internal debugger |
|
1753 | # fallback to our internal debugger | |
1683 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1754 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1684 | self.history_saving_wrapper(pm)() |
|
1755 | self.history_saving_wrapper(pm)() | |
1685 |
|
1756 | |||
1686 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1757 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1687 | """Display the exception that just occurred. |
|
1758 | """Display the exception that just occurred. | |
1688 |
|
1759 | |||
1689 | If nothing is known about the exception, this is the method which |
|
1760 | If nothing is known about the exception, this is the method which | |
1690 | should be used throughout the code for presenting user tracebacks, |
|
1761 | should be used throughout the code for presenting user tracebacks, | |
1691 | rather than directly invoking the InteractiveTB object. |
|
1762 | rather than directly invoking the InteractiveTB object. | |
1692 |
|
1763 | |||
1693 | A specific showsyntaxerror() also exists, but this method can take |
|
1764 | A specific showsyntaxerror() also exists, but this method can take | |
1694 | care of calling it if needed, so unless you are explicitly catching a |
|
1765 | care of calling it if needed, so unless you are explicitly catching a | |
1695 | SyntaxError exception, don't try to analyze the stack manually and |
|
1766 | SyntaxError exception, don't try to analyze the stack manually and | |
1696 | simply call this method.""" |
|
1767 | simply call this method.""" | |
1697 |
|
1768 | |||
1698 |
|
1769 | |||
1699 | # Though this won't be called by syntax errors in the input line, |
|
1770 | # Though this won't be called by syntax errors in the input line, | |
1700 | # there may be SyntaxError cases whith imported code. |
|
1771 | # there may be SyntaxError cases whith imported code. | |
1701 |
|
1772 | |||
1702 | try: |
|
1773 | try: | |
1703 | if exc_tuple is None: |
|
1774 | if exc_tuple is None: | |
1704 | etype, value, tb = sys.exc_info() |
|
1775 | etype, value, tb = sys.exc_info() | |
1705 | else: |
|
1776 | else: | |
1706 | etype, value, tb = exc_tuple |
|
1777 | etype, value, tb = exc_tuple | |
1707 |
|
1778 | |||
1708 | if etype is SyntaxError: |
|
1779 | if etype is SyntaxError: | |
1709 | self.showsyntaxerror(filename) |
|
1780 | self.showsyntaxerror(filename) | |
1710 |
elif etype is |
|
1781 | elif etype is UsageError: | |
1711 | print "UsageError:", value |
|
1782 | print "UsageError:", value | |
1712 | else: |
|
1783 | else: | |
1713 | # WARNING: these variables are somewhat deprecated and not |
|
1784 | # WARNING: these variables are somewhat deprecated and not | |
1714 | # necessarily safe to use in a threaded environment, but tools |
|
1785 | # necessarily safe to use in a threaded environment, but tools | |
1715 | # like pdb depend on their existence, so let's set them. If we |
|
1786 | # like pdb depend on their existence, so let's set them. If we | |
1716 | # find problems in the field, we'll need to revisit their use. |
|
1787 | # find problems in the field, we'll need to revisit their use. | |
1717 | sys.last_type = etype |
|
1788 | sys.last_type = etype | |
1718 | sys.last_value = value |
|
1789 | sys.last_value = value | |
1719 | sys.last_traceback = tb |
|
1790 | sys.last_traceback = tb | |
1720 |
|
1791 | |||
1721 | if etype in self.custom_exceptions: |
|
1792 | if etype in self.custom_exceptions: | |
1722 | self.CustomTB(etype,value,tb) |
|
1793 | self.CustomTB(etype,value,tb) | |
1723 | else: |
|
1794 | else: | |
1724 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1795 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1725 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1796 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1726 | # pdb mucks up readline, fix it back |
|
1797 | # pdb mucks up readline, fix it back | |
1727 | self.set_completer() |
|
1798 | self.set_completer() | |
1728 | except KeyboardInterrupt: |
|
1799 | except KeyboardInterrupt: | |
1729 | self.write("\nKeyboardInterrupt\n") |
|
1800 | self.write("\nKeyboardInterrupt\n") | |
1730 |
|
1801 | |||
1731 | def mainloop(self,banner=None): |
|
1802 | def mainloop(self, banner=None): | |
1732 |
""" |
|
1803 | """Start the mainloop. | |
1733 |
|
1804 | |||
1734 | If an optional banner argument is given, it will override the |
|
1805 | If an optional banner argument is given, it will override the | |
1735 |
internally created default banner. |
|
1806 | internally created default banner. | |
1736 |
|
1807 | """ | ||
1737 | if self.rc.c: # Emulate Python's -c option |
|
1808 | ||
1738 | self.exec_init_cmd() |
|
1809 | with self.builtin_trap: | |
1739 | if banner is None: |
|
1810 | if self.c: # Emulate Python's -c option | |
1740 |
|
|
1811 | self.exec_init_cmd() | |
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) |
|
|||
1752 |
|
1812 | |||
1753 | while 1: |
|
1813 | if self.display_banner: | |
1754 | try: |
|
1814 | if banner is None: | |
1755 | self.interact(banner) |
|
1815 | banner = self.banner | |
1756 | #self.interact_with_readline() |
|
|||
1757 |
|
1816 | |||
1758 | # XXX for testing of a readline-decoupled repl loop, call |
|
1817 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1759 | # interact_with_readline above |
|
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 |
|
|
1822 | while 1: | |
1762 | except KeyboardInterrupt: |
|
1823 | try: | |
1763 | # this should not be necessary, but KeyboardInterrupt |
|
1824 | self.interact() | |
1764 | # handling seems rather unpredictable... |
|
1825 | #self.interact_with_readline() | |
1765 | self.write("\nKeyboardInterrupt in interact()\n") |
|
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 | def exec_init_cmd(self): |
|
1834 | def exec_init_cmd(self): | |
1768 | """Execute a command given at the command line. |
|
1835 | """Execute a command given at the command line. | |
1769 |
|
1836 | |||
1770 | This emulates Python's -c option.""" |
|
1837 | This emulates Python's -c option.""" | |
1771 |
|
1838 | |||
1772 | #sys.argv = ['-c'] |
|
1839 | #sys.argv = ['-c'] | |
1773 |
self.push(self.prefilter(self |
|
1840 | self.push_line(self.prefilter(self.c, False)) | |
1774 |
if not self. |
|
1841 | if not self.interactive: | |
1775 | self.ask_exit() |
|
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 | def interact_prompt(self): |
|
1844 | def interact_prompt(self): | |
1849 | """ Print the prompt (in read-eval-print loop) |
|
1845 | """ Print the prompt (in read-eval-print loop) | |
1850 |
|
1846 | |||
1851 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1847 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1852 | used in standard IPython flow. |
|
1848 | used in standard IPython flow. | |
1853 | """ |
|
1849 | """ | |
1854 | if self.more: |
|
1850 | if self.more: | |
1855 | try: |
|
1851 | try: | |
1856 | prompt = self.hooks.generate_prompt(True) |
|
1852 | prompt = self.hooks.generate_prompt(True) | |
1857 | except: |
|
1853 | except: | |
1858 | self.showtraceback() |
|
1854 | self.showtraceback() | |
1859 | if self.autoindent: |
|
1855 | if self.autoindent: | |
1860 | self.rl_do_indent = True |
|
1856 | self.rl_do_indent = True | |
1861 |
|
1857 | |||
1862 | else: |
|
1858 | else: | |
1863 | try: |
|
1859 | try: | |
1864 | prompt = self.hooks.generate_prompt(False) |
|
1860 | prompt = self.hooks.generate_prompt(False) | |
1865 | except: |
|
1861 | except: | |
1866 | self.showtraceback() |
|
1862 | self.showtraceback() | |
1867 | self.write(prompt) |
|
1863 | self.write(prompt) | |
1868 |
|
1864 | |||
1869 | def interact_handle_input(self,line): |
|
1865 | def interact_handle_input(self,line): | |
1870 | """ Handle the input line (in read-eval-print loop) |
|
1866 | """ Handle the input line (in read-eval-print loop) | |
1871 |
|
1867 | |||
1872 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1868 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1873 | used in standard IPython flow. |
|
1869 | used in standard IPython flow. | |
1874 | """ |
|
1870 | """ | |
1875 | if line.lstrip() == line: |
|
1871 | if line.lstrip() == line: | |
1876 | self.shadowhist.add(line.strip()) |
|
1872 | self.shadowhist.add(line.strip()) | |
1877 | lineout = self.prefilter(line,self.more) |
|
1873 | lineout = self.prefilter(line,self.more) | |
1878 |
|
1874 | |||
1879 | if line.strip(): |
|
1875 | if line.strip(): | |
1880 | if self.more: |
|
1876 | if self.more: | |
1881 | self.input_hist_raw[-1] += '%s\n' % line |
|
1877 | self.input_hist_raw[-1] += '%s\n' % line | |
1882 | else: |
|
1878 | else: | |
1883 | self.input_hist_raw.append('%s\n' % line) |
|
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 | if (self.SyntaxTB.last_syntax_error and |
|
1883 | if (self.SyntaxTB.last_syntax_error and | |
1888 |
self |
|
1884 | self.autoedit_syntax): | |
1889 | self.edit_syntax_error() |
|
1885 | self.edit_syntax_error() | |
1890 |
|
1886 | |||
1891 | def interact_with_readline(self): |
|
1887 | def interact_with_readline(self): | |
1892 | """ Demo of using interact_handle_input, interact_prompt |
|
1888 | """ Demo of using interact_handle_input, interact_prompt | |
1893 |
|
1889 | |||
1894 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1890 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1895 | it should work like this. |
|
1891 | it should work like this. | |
1896 | """ |
|
1892 | """ | |
1897 | self.readline_startup_hook(self.pre_readline) |
|
1893 | self.readline_startup_hook(self.pre_readline) | |
1898 | while not self.exit_now: |
|
1894 | while not self.exit_now: | |
1899 | self.interact_prompt() |
|
1895 | self.interact_prompt() | |
1900 | if self.more: |
|
1896 | if self.more: | |
1901 | self.rl_do_indent = True |
|
1897 | self.rl_do_indent = True | |
1902 | else: |
|
1898 | else: | |
1903 | self.rl_do_indent = False |
|
1899 | self.rl_do_indent = False | |
1904 | line = raw_input_original().decode(self.stdin_encoding) |
|
1900 | line = raw_input_original().decode(self.stdin_encoding) | |
1905 | self.interact_handle_input(line) |
|
1901 | self.interact_handle_input(line) | |
1906 |
|
1902 | |||
1907 |
|
||||
1908 | def interact(self, banner=None): |
|
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 |
|
1906 | # batch run -> do not interact | |
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 |
|
||||
1920 | if self.exit_now: |
|
1907 | if self.exit_now: | |
1921 | # batch run -> do not interact |
|
|||
1922 | return |
|
1908 | return | |
1923 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1909 | ||
1924 |
if banner |
|
1910 | if self.display_banner: | |
1925 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1911 | if banner is None: | |
1926 | (sys.version, sys.platform, cprt, |
|
1912 | banner = self.banner | |
1927 | self.__class__.__name__)) |
|
|||
1928 | else: |
|
|||
1929 | self.write(banner) |
|
1913 | self.write(banner) | |
1930 |
|
1914 | |||
1931 | more = 0 |
|
1915 | more = 0 | |
1932 |
|
1916 | |||
1933 | # Mark activity in the builtins |
|
1917 | # Mark activity in the builtins | |
1934 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1918 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1935 |
|
1919 | |||
1936 | if self.has_readline: |
|
1920 | if self.has_readline: | |
1937 | self.readline_startup_hook(self.pre_readline) |
|
1921 | self.readline_startup_hook(self.pre_readline) | |
1938 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1922 | # exit_now is set by a call to %Exit or %Quit, through the | |
1939 | # ask_exit callback. |
|
1923 | # ask_exit callback. | |
1940 |
|
1924 | |||
1941 | while not self.exit_now: |
|
1925 | while not self.exit_now: | |
1942 | self.hooks.pre_prompt_hook() |
|
1926 | self.hooks.pre_prompt_hook() | |
1943 | if more: |
|
1927 | if more: | |
1944 | try: |
|
1928 | try: | |
1945 | prompt = self.hooks.generate_prompt(True) |
|
1929 | prompt = self.hooks.generate_prompt(True) | |
1946 | except: |
|
1930 | except: | |
1947 | self.showtraceback() |
|
1931 | self.showtraceback() | |
1948 | if self.autoindent: |
|
1932 | if self.autoindent: | |
1949 | self.rl_do_indent = True |
|
1933 | self.rl_do_indent = True | |
1950 |
|
1934 | |||
1951 | else: |
|
1935 | else: | |
1952 | try: |
|
1936 | try: | |
1953 | prompt = self.hooks.generate_prompt(False) |
|
1937 | prompt = self.hooks.generate_prompt(False) | |
1954 | except: |
|
1938 | except: | |
1955 | self.showtraceback() |
|
1939 | self.showtraceback() | |
1956 | try: |
|
1940 | try: | |
1957 | line = self.raw_input(prompt,more) |
|
1941 | line = self.raw_input(prompt, more) | |
1958 | if self.exit_now: |
|
1942 | if self.exit_now: | |
1959 | # quick exit on sys.std[in|out] close |
|
1943 | # quick exit on sys.std[in|out] close | |
1960 | break |
|
1944 | break | |
1961 | if self.autoindent: |
|
1945 | if self.autoindent: | |
1962 | self.rl_do_indent = False |
|
1946 | self.rl_do_indent = False | |
1963 |
|
1947 | |||
1964 | except KeyboardInterrupt: |
|
1948 | except KeyboardInterrupt: | |
1965 | #double-guard against keyboardinterrupts during kbdint handling |
|
1949 | #double-guard against keyboardinterrupts during kbdint handling | |
1966 | try: |
|
1950 | try: | |
1967 | self.write('\nKeyboardInterrupt\n') |
|
1951 | self.write('\nKeyboardInterrupt\n') | |
1968 | self.resetbuffer() |
|
1952 | self.resetbuffer() | |
1969 | # keep cache in sync with the prompt counter: |
|
1953 | # keep cache in sync with the prompt counter: | |
1970 | self.outputcache.prompt_count -= 1 |
|
1954 | self.outputcache.prompt_count -= 1 | |
1971 |
|
1955 | |||
1972 | if self.autoindent: |
|
1956 | if self.autoindent: | |
1973 | self.indent_current_nsp = 0 |
|
1957 | self.indent_current_nsp = 0 | |
1974 | more = 0 |
|
1958 | more = 0 | |
1975 | except KeyboardInterrupt: |
|
1959 | except KeyboardInterrupt: | |
1976 | pass |
|
1960 | pass | |
1977 | except EOFError: |
|
1961 | except EOFError: | |
1978 | if self.autoindent: |
|
1962 | if self.autoindent: | |
1979 | self.rl_do_indent = False |
|
1963 | self.rl_do_indent = False | |
1980 | self.readline_startup_hook(None) |
|
1964 | self.readline_startup_hook(None) | |
1981 | self.write('\n') |
|
1965 | self.write('\n') | |
1982 | self.exit() |
|
1966 | self.exit() | |
1983 | except bdb.BdbQuit: |
|
1967 | except bdb.BdbQuit: | |
1984 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1968 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1985 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1969 | 'Because of how pdb handles the stack, it is impossible\n' | |
1986 | 'for IPython to properly format this particular exception.\n' |
|
1970 | 'for IPython to properly format this particular exception.\n' | |
1987 | 'IPython will resume normal operation.') |
|
1971 | 'IPython will resume normal operation.') | |
1988 | except: |
|
1972 | except: | |
1989 | # exceptions here are VERY RARE, but they can be triggered |
|
1973 | # exceptions here are VERY RARE, but they can be triggered | |
1990 | # asynchronously by signal handlers, for example. |
|
1974 | # asynchronously by signal handlers, for example. | |
1991 | self.showtraceback() |
|
1975 | self.showtraceback() | |
1992 | else: |
|
1976 | else: | |
1993 | more = self.push(line) |
|
1977 | more = self.push_line(line) | |
1994 | if (self.SyntaxTB.last_syntax_error and |
|
1978 | if (self.SyntaxTB.last_syntax_error and | |
1995 |
self |
|
1979 | self.autoedit_syntax): | |
1996 | self.edit_syntax_error() |
|
1980 | self.edit_syntax_error() | |
1997 |
|
1981 | |||
1998 | # We are off again... |
|
1982 | # We are off again... | |
1999 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1983 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
2000 |
|
1984 | |||
2001 | def excepthook(self, etype, value, tb): |
|
1985 | def excepthook(self, etype, value, tb): | |
2002 | """One more defense for GUI apps that call sys.excepthook. |
|
1986 | """One more defense for GUI apps that call sys.excepthook. | |
2003 |
|
1987 | |||
2004 | GUI frameworks like wxPython trap exceptions and call |
|
1988 | GUI frameworks like wxPython trap exceptions and call | |
2005 | sys.excepthook themselves. I guess this is a feature that |
|
1989 | sys.excepthook themselves. I guess this is a feature that | |
2006 | enables them to keep running after exceptions that would |
|
1990 | enables them to keep running after exceptions that would | |
2007 | otherwise kill their mainloop. This is a bother for IPython |
|
1991 | otherwise kill their mainloop. This is a bother for IPython | |
2008 | which excepts to catch all of the program exceptions with a try: |
|
1992 | which excepts to catch all of the program exceptions with a try: | |
2009 | except: statement. |
|
1993 | except: statement. | |
2010 |
|
1994 | |||
2011 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1995 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
2012 | any app directly invokes sys.excepthook, it will look to the user like |
|
1996 | any app directly invokes sys.excepthook, it will look to the user like | |
2013 | IPython crashed. In order to work around this, we can disable the |
|
1997 | IPython crashed. In order to work around this, we can disable the | |
2014 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1998 | CrashHandler and replace it with this excepthook instead, which prints a | |
2015 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1999 | regular traceback using our InteractiveTB. In this fashion, apps which | |
2016 | call sys.excepthook will generate a regular-looking exception from |
|
2000 | call sys.excepthook will generate a regular-looking exception from | |
2017 | IPython, and the CrashHandler will only be triggered by real IPython |
|
2001 | IPython, and the CrashHandler will only be triggered by real IPython | |
2018 | crashes. |
|
2002 | crashes. | |
2019 |
|
2003 | |||
2020 | This hook should be used sparingly, only in places which are not likely |
|
2004 | This hook should be used sparingly, only in places which are not likely | |
2021 | to be true IPython errors. |
|
2005 | to be true IPython errors. | |
2022 | """ |
|
2006 | """ | |
2023 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
2007 | self.showtraceback((etype,value,tb),tb_offset=0) | |
2024 |
|
2008 | |||
2025 |
def expand_alias |
|
2009 | def expand_alias(self, line): | |
2026 | """ Expand multiple levels of aliases: |
|
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 | if: |
|
2026 | if: | |
2029 |
|
2027 | |||
2030 | alias foo bar /tmp |
|
2028 | alias foo bar /tmp | |
2031 | alias baz foo |
|
2029 | alias baz foo | |
2032 |
|
2030 | |||
2033 | then: |
|
2031 | then: | |
2034 |
|
2032 | |||
2035 | baz huhhahhei -> bar /tmp huhhahhei |
|
2033 | baz huhhahhei -> bar /tmp huhhahhei | |
2036 |
|
2034 | |||
2037 | """ |
|
2035 | """ | |
2038 | line = fn + " " + rest |
|
2036 | line = fn + " " + rest | |
2039 |
|
2037 | |||
2040 | done = set() |
|
2038 | done = set() | |
2041 | while 1: |
|
2039 | while 1: | |
2042 | pre,fn,rest = prefilter.splitUserInput(line, |
|
2040 | pre,fn,rest = prefilter.splitUserInput(line, | |
2043 | prefilter.shell_line_split) |
|
2041 | prefilter.shell_line_split) | |
2044 | if fn in self.alias_table: |
|
2042 | if fn in self.alias_table: | |
2045 | if fn in done: |
|
2043 | if fn in done: | |
2046 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
2044 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
2047 | return "" |
|
2045 | return "" | |
2048 | done.add(fn) |
|
2046 | done.add(fn) | |
2049 |
|
2047 | |||
2050 | l2 = self.transform_alias(fn,rest) |
|
2048 | l2 = self.transform_alias(fn,rest) | |
2051 | # dir -> dir |
|
2049 | # dir -> dir | |
2052 | # print "alias",line, "->",l2 #dbg |
|
2050 | # print "alias",line, "->",l2 #dbg | |
2053 | if l2 == line: |
|
2051 | if l2 == line: | |
2054 | break |
|
2052 | break | |
2055 | # ls -> ls -F should not recurse forever |
|
2053 | # ls -> ls -F should not recurse forever | |
2056 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
2054 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
2057 | line = l2 |
|
2055 | line = l2 | |
2058 | break |
|
2056 | break | |
2059 |
|
2057 | |||
2060 | line=l2 |
|
2058 | line=l2 | |
2061 |
|
2059 | |||
2062 |
|
2060 | |||
2063 | # print "al expand to",line #dbg |
|
2061 | # print "al expand to",line #dbg | |
2064 | else: |
|
2062 | else: | |
2065 | break |
|
2063 | break | |
2066 |
|
2064 | |||
2067 | return line |
|
2065 | return line | |
2068 |
|
2066 | |||
2069 | def transform_alias(self, alias,rest=''): |
|
2067 | def transform_alias(self, alias,rest=''): | |
2070 | """ Transform alias to system command string. |
|
2068 | """ Transform alias to system command string. | |
2071 | """ |
|
2069 | """ | |
2072 | trg = self.alias_table[alias] |
|
2070 | trg = self.alias_table[alias] | |
2073 |
|
2071 | |||
2074 | nargs,cmd = trg |
|
2072 | nargs,cmd = trg | |
2075 | # print trg #dbg |
|
2073 | # print trg #dbg | |
2076 | if ' ' in cmd and os.path.isfile(cmd): |
|
2074 | if ' ' in cmd and os.path.isfile(cmd): | |
2077 | cmd = '"%s"' % cmd |
|
2075 | cmd = '"%s"' % cmd | |
2078 |
|
2076 | |||
2079 | # Expand the %l special to be the user's input line |
|
2077 | # Expand the %l special to be the user's input line | |
2080 | if cmd.find('%l') >= 0: |
|
2078 | if cmd.find('%l') >= 0: | |
2081 | cmd = cmd.replace('%l',rest) |
|
2079 | cmd = cmd.replace('%l',rest) | |
2082 | rest = '' |
|
2080 | rest = '' | |
2083 | if nargs==0: |
|
2081 | if nargs==0: | |
2084 | # Simple, argument-less aliases |
|
2082 | # Simple, argument-less aliases | |
2085 | cmd = '%s %s' % (cmd,rest) |
|
2083 | cmd = '%s %s' % (cmd,rest) | |
2086 | else: |
|
2084 | else: | |
2087 | # Handle aliases with positional arguments |
|
2085 | # Handle aliases with positional arguments | |
2088 | args = rest.split(None,nargs) |
|
2086 | args = rest.split(None,nargs) | |
2089 | if len(args)< nargs: |
|
2087 | if len(args)< nargs: | |
2090 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2088 | error('Alias <%s> requires %s arguments, %s given.' % | |
2091 | (alias,nargs,len(args))) |
|
2089 | (alias,nargs,len(args))) | |
2092 | return None |
|
2090 | return None | |
2093 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2091 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
2094 | # Now call the macro, evaluating in the user's namespace |
|
2092 | # Now call the macro, evaluating in the user's namespace | |
2095 | #print 'new command: <%r>' % cmd # dbg |
|
2093 | #print 'new command: <%r>' % cmd # dbg | |
2096 | return cmd |
|
2094 | return cmd | |
2097 |
|
2095 | |||
2098 | def call_alias(self,alias,rest=''): |
|
2096 | def call_alias(self,alias,rest=''): | |
2099 | """Call an alias given its name and the rest of the line. |
|
2097 | """Call an alias given its name and the rest of the line. | |
2100 |
|
2098 | |||
2101 | This is only used to provide backwards compatibility for users of |
|
2099 | This is only used to provide backwards compatibility for users of | |
2102 | ipalias(), use of which is not recommended for anymore.""" |
|
2100 | ipalias(), use of which is not recommended for anymore.""" | |
2103 |
|
2101 | |||
2104 | # Now call the macro, evaluating in the user's namespace |
|
2102 | # Now call the macro, evaluating in the user's namespace | |
2105 | cmd = self.transform_alias(alias, rest) |
|
2103 | cmd = self.transform_alias(alias, rest) | |
2106 | try: |
|
2104 | try: | |
2107 | self.system(cmd) |
|
2105 | self.system(cmd) | |
2108 | except: |
|
2106 | except: | |
2109 | self.showtraceback() |
|
2107 | self.showtraceback() | |
2110 |
|
2108 | |||
2111 | def indent_current_str(self): |
|
2109 | def indent_current_str(self): | |
2112 | """return the current level of indentation as a string""" |
|
2110 | """return the current level of indentation as a string""" | |
2113 | return self.indent_current_nsp * ' ' |
|
2111 | return self.indent_current_nsp * ' ' | |
2114 |
|
2112 | |||
2115 | def autoindent_update(self,line): |
|
2113 | def autoindent_update(self,line): | |
2116 | """Keep track of the indent level.""" |
|
2114 | """Keep track of the indent level.""" | |
2117 |
|
2115 | |||
2118 | #debugx('line') |
|
2116 | #debugx('line') | |
2119 | #debugx('self.indent_current_nsp') |
|
2117 | #debugx('self.indent_current_nsp') | |
2120 | if self.autoindent: |
|
2118 | if self.autoindent: | |
2121 | if line: |
|
2119 | if line: | |
2122 | inisp = num_ini_spaces(line) |
|
2120 | inisp = num_ini_spaces(line) | |
2123 | if inisp < self.indent_current_nsp: |
|
2121 | if inisp < self.indent_current_nsp: | |
2124 | self.indent_current_nsp = inisp |
|
2122 | self.indent_current_nsp = inisp | |
2125 |
|
2123 | |||
2126 | if line[-1] == ':': |
|
2124 | if line[-1] == ':': | |
2127 | self.indent_current_nsp += 4 |
|
2125 | self.indent_current_nsp += 4 | |
2128 | elif dedent_re.match(line): |
|
2126 | elif dedent_re.match(line): | |
2129 | self.indent_current_nsp -= 4 |
|
2127 | self.indent_current_nsp -= 4 | |
2130 | else: |
|
2128 | else: | |
2131 | self.indent_current_nsp = 0 |
|
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 | """Run a string of one or more lines of source. |
|
2221 | """Run a string of one or more lines of source. | |
2135 |
|
2222 | |||
2136 | This method is capable of running a string containing multiple source |
|
2223 | This method is capable of running a string containing multiple source | |
2137 | lines, as if they had been entered at the IPython prompt. Since it |
|
2224 | lines, as if they had been entered at the IPython prompt. Since it | |
2138 | exposes IPython's processing machinery, the given strings can contain |
|
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 | # We must start with a clean buffer, in case this is run from an |
|
2235 | # We must start with a clean buffer, in case this is run from an | |
2142 | # interactive IPython session (via a magic, for example). |
|
2236 | # interactive IPython session (via a magic, for example). | |
2143 | self.resetbuffer() |
|
2237 | self.resetbuffer() | |
2144 |
lines = lines.split( |
|
2238 | lines = lines.splitlines() | |
2145 | more = 0 |
|
2239 | more = 0 | |
2146 |
|
2240 | |||
2147 | for line in lines: |
|
2241 | with self.builtin_trap: | |
2148 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2242 | for line in lines: | |
2149 | # NOT skip even a blank line if we are in a code block (more is |
|
2243 | # skip blank lines so we don't mess up the prompt counter, but do | |
2150 | # true) |
|
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: |
|
2247 | if line or more: | |
2153 | # push to raw history, so hist line numbers stay in sync |
|
2248 | # push to raw history, so hist line numbers stay in sync | |
2154 | self.input_hist_raw.append("# " + line + "\n") |
|
2249 | self.input_hist_raw.append("# " + line + "\n") | |
2155 | more = self.push(self.prefilter(line,more)) |
|
2250 | more = self.push_line(self.prefilter(line,more)) | |
2156 | # IPython's runsource returns None if there was an error |
|
2251 | # IPython's runsource returns None if there was an error | |
2157 | # compiling the code. This allows us to stop processing right |
|
2252 | # compiling the code. This allows us to stop processing right | |
2158 | # away, so the user gets the error message at the right place. |
|
2253 | # away, so the user gets the error message at the right place. | |
2159 | if more is None: |
|
2254 | if more is None: | |
2160 | break |
|
2255 | break | |
2161 | else: |
|
2256 | else: | |
2162 | self.input_hist_raw.append("\n") |
|
2257 | self.input_hist_raw.append("\n") | |
2163 | # final newline in case the input didn't have it, so that the code |
|
2258 | # final newline in case the input didn't have it, so that the code | |
2164 | # actually does get executed |
|
2259 | # actually does get executed | |
2165 | if more: |
|
2260 | if more: | |
2166 | self.push('\n') |
|
2261 | self.push_line('\n') | |
2167 |
|
2262 | |||
2168 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2263 | def runsource(self, source, filename='<input>', symbol='single'): | |
2169 | """Compile and run some source in the interpreter. |
|
2264 | """Compile and run some source in the interpreter. | |
2170 |
|
2265 | |||
2171 | Arguments are as for compile_command(). |
|
2266 | Arguments are as for compile_command(). | |
2172 |
|
2267 | |||
2173 | One several things can happen: |
|
2268 | One several things can happen: | |
2174 |
|
2269 | |||
2175 | 1) The input is incorrect; compile_command() raised an |
|
2270 | 1) The input is incorrect; compile_command() raised an | |
2176 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2271 | exception (SyntaxError or OverflowError). A syntax traceback | |
2177 | will be printed by calling the showsyntaxerror() method. |
|
2272 | will be printed by calling the showsyntaxerror() method. | |
2178 |
|
2273 | |||
2179 | 2) The input is incomplete, and more input is required; |
|
2274 | 2) The input is incomplete, and more input is required; | |
2180 | compile_command() returned None. Nothing happens. |
|
2275 | compile_command() returned None. Nothing happens. | |
2181 |
|
2276 | |||
2182 | 3) The input is complete; compile_command() returned a code |
|
2277 | 3) The input is complete; compile_command() returned a code | |
2183 | object. The code is executed by calling self.runcode() (which |
|
2278 | object. The code is executed by calling self.runcode() (which | |
2184 | also handles run-time exceptions, except for SystemExit). |
|
2279 | also handles run-time exceptions, except for SystemExit). | |
2185 |
|
2280 | |||
2186 | The return value is: |
|
2281 | The return value is: | |
2187 |
|
2282 | |||
2188 | - True in case 2 |
|
2283 | - True in case 2 | |
2189 |
|
2284 | |||
2190 | - False in the other cases, unless an exception is raised, where |
|
2285 | - False in the other cases, unless an exception is raised, where | |
2191 | None is returned instead. This can be used by external callers to |
|
2286 | None is returned instead. This can be used by external callers to | |
2192 | know whether to continue feeding input or not. |
|
2287 | know whether to continue feeding input or not. | |
2193 |
|
2288 | |||
2194 | The return value can be used to decide whether to use sys.ps1 or |
|
2289 | The return value can be used to decide whether to use sys.ps1 or | |
2195 | sys.ps2 to prompt the next line.""" |
|
2290 | sys.ps2 to prompt the next line.""" | |
2196 |
|
2291 | |||
2197 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2292 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2198 | # this allows execution of indented pasted code. It is tempting |
|
2293 | # this allows execution of indented pasted code. It is tempting | |
2199 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2294 | # to add '\n' at the end of source to run commands like ' a=1' | |
2200 | # directly, but this fails for more complicated scenarios |
|
2295 | # directly, but this fails for more complicated scenarios | |
2201 | source=source.encode(self.stdin_encoding) |
|
2296 | source=source.encode(self.stdin_encoding) | |
2202 | if source[:1] in [' ', '\t']: |
|
2297 | if source[:1] in [' ', '\t']: | |
2203 | source = 'if 1:\n%s' % source |
|
2298 | source = 'if 1:\n%s' % source | |
2204 |
|
2299 | |||
2205 | try: |
|
2300 | try: | |
2206 | code = self.compile(source,filename,symbol) |
|
2301 | code = self.compile(source,filename,symbol) | |
2207 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2302 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2208 | # Case 1 |
|
2303 | # Case 1 | |
2209 | self.showsyntaxerror(filename) |
|
2304 | self.showsyntaxerror(filename) | |
2210 | return None |
|
2305 | return None | |
2211 |
|
2306 | |||
2212 | if code is None: |
|
2307 | if code is None: | |
2213 | # Case 2 |
|
2308 | # Case 2 | |
2214 | return True |
|
2309 | return True | |
2215 |
|
2310 | |||
2216 | # Case 3 |
|
2311 | # Case 3 | |
2217 | # We store the code object so that threaded shells and |
|
2312 | # We store the code object so that threaded shells and | |
2218 | # custom exception handlers can access all this info if needed. |
|
2313 | # custom exception handlers can access all this info if needed. | |
2219 | # The source corresponding to this can be obtained from the |
|
2314 | # The source corresponding to this can be obtained from the | |
2220 | # buffer attribute as '\n'.join(self.buffer). |
|
2315 | # buffer attribute as '\n'.join(self.buffer). | |
2221 | self.code_to_run = code |
|
2316 | self.code_to_run = code | |
2222 | # now actually execute the code object |
|
2317 | # now actually execute the code object | |
2223 | if self.runcode(code) == 0: |
|
2318 | if self.runcode(code) == 0: | |
2224 | return False |
|
2319 | return False | |
2225 | else: |
|
2320 | else: | |
2226 | return None |
|
2321 | return None | |
2227 |
|
2322 | |||
2228 | def runcode(self,code_obj): |
|
2323 | def runcode(self,code_obj): | |
2229 | """Execute a code object. |
|
2324 | """Execute a code object. | |
2230 |
|
2325 | |||
2231 | When an exception occurs, self.showtraceback() is called to display a |
|
2326 | When an exception occurs, self.showtraceback() is called to display a | |
2232 | traceback. |
|
2327 | traceback. | |
2233 |
|
2328 | |||
2234 | Return value: a flag indicating whether the code to be run completed |
|
2329 | Return value: a flag indicating whether the code to be run completed | |
2235 | successfully: |
|
2330 | successfully: | |
2236 |
|
2331 | |||
2237 | - 0: successful execution. |
|
2332 | - 0: successful execution. | |
2238 | - 1: an error occurred. |
|
2333 | - 1: an error occurred. | |
2239 | """ |
|
2334 | """ | |
2240 |
|
2335 | |||
2241 | # Set our own excepthook in case the user code tries to call it |
|
2336 | # Set our own excepthook in case the user code tries to call it | |
2242 | # directly, so that the IPython crash handler doesn't get triggered |
|
2337 | # directly, so that the IPython crash handler doesn't get triggered | |
2243 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2338 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2244 |
|
2339 | |||
2245 | # we save the original sys.excepthook in the instance, in case config |
|
2340 | # we save the original sys.excepthook in the instance, in case config | |
2246 | # code (such as magics) needs access to it. |
|
2341 | # code (such as magics) needs access to it. | |
2247 | self.sys_excepthook = old_excepthook |
|
2342 | self.sys_excepthook = old_excepthook | |
2248 | outflag = 1 # happens in more places, so it's easier as default |
|
2343 | outflag = 1 # happens in more places, so it's easier as default | |
2249 | try: |
|
2344 | try: | |
2250 | try: |
|
2345 | try: | |
2251 | self.hooks.pre_runcode_hook() |
|
2346 | self.hooks.pre_runcode_hook() | |
2252 | exec code_obj in self.user_global_ns, self.user_ns |
|
2347 | exec code_obj in self.user_global_ns, self.user_ns | |
2253 | finally: |
|
2348 | finally: | |
2254 | # Reset our crash handler in place |
|
2349 | # Reset our crash handler in place | |
2255 | sys.excepthook = old_excepthook |
|
2350 | sys.excepthook = old_excepthook | |
2256 | except SystemExit: |
|
2351 | except SystemExit: | |
2257 | self.resetbuffer() |
|
2352 | self.resetbuffer() | |
2258 | self.showtraceback() |
|
2353 | self.showtraceback() | |
2259 | warn("Type %exit or %quit to exit IPython " |
|
2354 | warn("Type %exit or %quit to exit IPython " | |
2260 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2355 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2261 | except self.custom_exceptions: |
|
2356 | except self.custom_exceptions: | |
2262 | etype,value,tb = sys.exc_info() |
|
2357 | etype,value,tb = sys.exc_info() | |
2263 | self.CustomTB(etype,value,tb) |
|
2358 | self.CustomTB(etype,value,tb) | |
2264 | except: |
|
2359 | except: | |
2265 | self.showtraceback() |
|
2360 | self.showtraceback() | |
2266 | else: |
|
2361 | else: | |
2267 | outflag = 0 |
|
2362 | outflag = 0 | |
2268 | if softspace(sys.stdout, 0): |
|
2363 | if softspace(sys.stdout, 0): | |
2269 |
|
2364 | |||
2270 | # Flush out code object which has been run (and source) |
|
2365 | # Flush out code object which has been run (and source) | |
2271 | self.code_to_run = None |
|
2366 | self.code_to_run = None | |
2272 | return outflag |
|
2367 | return outflag | |
2273 |
|
2368 | |||
2274 | def push(self, line): |
|
2369 | def push_line(self, line): | |
2275 | """Push a line to the interpreter. |
|
2370 | """Push a line to the interpreter. | |
2276 |
|
2371 | |||
2277 | The line should not have a trailing newline; it may have |
|
2372 | The line should not have a trailing newline; it may have | |
2278 | internal newlines. The line is appended to a buffer and the |
|
2373 | internal newlines. The line is appended to a buffer and the | |
2279 | interpreter's runsource() method is called with the |
|
2374 | interpreter's runsource() method is called with the | |
2280 | concatenated contents of the buffer as source. If this |
|
2375 | concatenated contents of the buffer as source. If this | |
2281 | indicates that the command was executed or invalid, the buffer |
|
2376 | indicates that the command was executed or invalid, the buffer | |
2282 | is reset; otherwise, the command is incomplete, and the buffer |
|
2377 | is reset; otherwise, the command is incomplete, and the buffer | |
2283 | is left as it was after the line was appended. The return |
|
2378 | is left as it was after the line was appended. The return | |
2284 | value is 1 if more input is required, 0 if the line was dealt |
|
2379 | value is 1 if more input is required, 0 if the line was dealt | |
2285 | with in some way (this is the same as runsource()). |
|
2380 | with in some way (this is the same as runsource()). | |
2286 | """ |
|
2381 | """ | |
2287 |
|
2382 | |||
2288 | # autoindent management should be done here, and not in the |
|
2383 | # autoindent management should be done here, and not in the | |
2289 | # interactive loop, since that one is only seen by keyboard input. We |
|
2384 | # interactive loop, since that one is only seen by keyboard input. We | |
2290 | # need this done correctly even for code run via runlines (which uses |
|
2385 | # need this done correctly even for code run via runlines (which uses | |
2291 | # push). |
|
2386 | # push). | |
2292 |
|
2387 | |||
2293 | #print 'push line: <%s>' % line # dbg |
|
2388 | #print 'push line: <%s>' % line # dbg | |
2294 | for subline in line.splitlines(): |
|
2389 | for subline in line.splitlines(): | |
2295 | self.autoindent_update(subline) |
|
2390 | self.autoindent_update(subline) | |
2296 | self.buffer.append(line) |
|
2391 | self.buffer.append(line) | |
2297 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2392 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2298 | if not more: |
|
2393 | if not more: | |
2299 | self.resetbuffer() |
|
2394 | self.resetbuffer() | |
2300 | return more |
|
2395 | return more | |
2301 |
|
2396 | |||
2302 | def split_user_input(self, line): |
|
2397 | def split_user_input(self, line): | |
2303 | # This is really a hold-over to support ipapi and some extensions |
|
2398 | # This is really a hold-over to support ipapi and some extensions | |
2304 | return prefilter.splitUserInput(line) |
|
2399 | return prefilter.splitUserInput(line) | |
2305 |
|
2400 | |||
2306 | def resetbuffer(self): |
|
2401 | def resetbuffer(self): | |
2307 | """Reset the input buffer.""" |
|
2402 | """Reset the input buffer.""" | |
2308 | self.buffer[:] = [] |
|
2403 | self.buffer[:] = [] | |
2309 |
|
2404 | |||
2310 | def raw_input(self,prompt='',continue_prompt=False): |
|
2405 | def raw_input(self,prompt='',continue_prompt=False): | |
2311 | """Write a prompt and read a line. |
|
2406 | """Write a prompt and read a line. | |
2312 |
|
2407 | |||
2313 | The returned line does not include the trailing newline. |
|
2408 | The returned line does not include the trailing newline. | |
2314 | When the user enters the EOF key sequence, EOFError is raised. |
|
2409 | When the user enters the EOF key sequence, EOFError is raised. | |
2315 |
|
2410 | |||
2316 | Optional inputs: |
|
2411 | Optional inputs: | |
2317 |
|
2412 | |||
2318 | - prompt(''): a string to be printed to prompt the user. |
|
2413 | - prompt(''): a string to be printed to prompt the user. | |
2319 |
|
2414 | |||
2320 | - continue_prompt(False): whether this line is the first one or a |
|
2415 | - continue_prompt(False): whether this line is the first one or a | |
2321 | continuation in a sequence of inputs. |
|
2416 | continuation in a sequence of inputs. | |
2322 | """ |
|
2417 | """ | |
2323 |
|
2418 | |||
2324 | # Code run by the user may have modified the readline completer state. |
|
2419 | # Code run by the user may have modified the readline completer state. | |
2325 | # We must ensure that our completer is back in place. |
|
2420 | # We must ensure that our completer is back in place. | |
2326 | if self.has_readline: |
|
2421 | if self.has_readline: | |
2327 | self.set_completer() |
|
2422 | self.set_completer() | |
2328 |
|
2423 | |||
2329 | try: |
|
2424 | try: | |
2330 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2425 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2331 | except ValueError: |
|
2426 | except ValueError: | |
2332 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2427 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2333 | " or sys.stdout.close()!\nExiting IPython!") |
|
2428 | " or sys.stdout.close()!\nExiting IPython!") | |
2334 | self.ask_exit() |
|
2429 | self.ask_exit() | |
2335 | return "" |
|
2430 | return "" | |
2336 |
|
2431 | |||
2337 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2432 | # Try to be reasonably smart about not re-indenting pasted input more | |
2338 | # than necessary. We do this by trimming out the auto-indent initial |
|
2433 | # than necessary. We do this by trimming out the auto-indent initial | |
2339 | # spaces, if the user's actual input started itself with whitespace. |
|
2434 | # spaces, if the user's actual input started itself with whitespace. | |
2340 | #debugx('self.buffer[-1]') |
|
2435 | #debugx('self.buffer[-1]') | |
2341 |
|
2436 | |||
2342 | if self.autoindent: |
|
2437 | if self.autoindent: | |
2343 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2438 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2344 | line = line[self.indent_current_nsp:] |
|
2439 | line = line[self.indent_current_nsp:] | |
2345 | self.indent_current_nsp = 0 |
|
2440 | self.indent_current_nsp = 0 | |
2346 |
|
2441 | |||
2347 | # store the unfiltered input before the user has any chance to modify |
|
2442 | # store the unfiltered input before the user has any chance to modify | |
2348 | # it. |
|
2443 | # it. | |
2349 | if line.strip(): |
|
2444 | if line.strip(): | |
2350 | if continue_prompt: |
|
2445 | if continue_prompt: | |
2351 | self.input_hist_raw[-1] += '%s\n' % line |
|
2446 | self.input_hist_raw[-1] += '%s\n' % line | |
2352 | if self.has_readline: # and some config option is set? |
|
2447 | if self.has_readline: # and some config option is set? | |
2353 | try: |
|
2448 | try: | |
2354 | histlen = self.readline.get_current_history_length() |
|
2449 | histlen = self.readline.get_current_history_length() | |
2355 | if histlen > 1: |
|
2450 | if histlen > 1: | |
2356 | newhist = self.input_hist_raw[-1].rstrip() |
|
2451 | newhist = self.input_hist_raw[-1].rstrip() | |
2357 | self.readline.remove_history_item(histlen-1) |
|
2452 | self.readline.remove_history_item(histlen-1) | |
2358 | self.readline.replace_history_item(histlen-2, |
|
2453 | self.readline.replace_history_item(histlen-2, | |
2359 | newhist.encode(self.stdin_encoding)) |
|
2454 | newhist.encode(self.stdin_encoding)) | |
2360 | except AttributeError: |
|
2455 | except AttributeError: | |
2361 | pass # re{move,place}_history_item are new in 2.4. |
|
2456 | pass # re{move,place}_history_item are new in 2.4. | |
2362 | else: |
|
2457 | else: | |
2363 | self.input_hist_raw.append('%s\n' % line) |
|
2458 | self.input_hist_raw.append('%s\n' % line) | |
2364 | # only entries starting at first column go to shadow history |
|
2459 | # only entries starting at first column go to shadow history | |
2365 | if line.lstrip() == line: |
|
2460 | if line.lstrip() == line: | |
2366 | self.shadowhist.add(line.strip()) |
|
2461 | self.shadowhist.add(line.strip()) | |
2367 | elif not continue_prompt: |
|
2462 | elif not continue_prompt: | |
2368 | self.input_hist_raw.append('\n') |
|
2463 | self.input_hist_raw.append('\n') | |
2369 | try: |
|
2464 | try: | |
2370 | lineout = self.prefilter(line,continue_prompt) |
|
2465 | lineout = self.prefilter(line,continue_prompt) | |
2371 | except: |
|
2466 | except: | |
2372 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2467 | # blanket except, in case a user-defined prefilter crashes, so it | |
2373 | # can't take all of ipython with it. |
|
2468 | # can't take all of ipython with it. | |
2374 | self.showtraceback() |
|
2469 | self.showtraceback() | |
2375 | return '' |
|
2470 | return '' | |
2376 | else: |
|
2471 | else: | |
2377 | return lineout |
|
2472 | return lineout | |
2378 |
|
2473 | |||
2379 | def _prefilter(self, line, continue_prompt): |
|
2474 | def _prefilter(self, line, continue_prompt): | |
2380 | """Calls different preprocessors, depending on the form of line.""" |
|
2475 | """Calls different preprocessors, depending on the form of line.""" | |
2381 |
|
2476 | |||
2382 | # All handlers *must* return a value, even if it's blank (''). |
|
2477 | # All handlers *must* return a value, even if it's blank (''). | |
2383 |
|
2478 | |||
2384 | # Lines are NOT logged here. Handlers should process the line as |
|
2479 | # Lines are NOT logged here. Handlers should process the line as | |
2385 | # needed, update the cache AND log it (so that the input cache array |
|
2480 | # needed, update the cache AND log it (so that the input cache array | |
2386 | # stays synced). |
|
2481 | # stays synced). | |
2387 |
|
2482 | |||
2388 | #..................................................................... |
|
2483 | #..................................................................... | |
2389 | # Code begins |
|
2484 | # Code begins | |
2390 |
|
2485 | |||
2391 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2486 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2392 |
|
2487 | |||
2393 | # save the line away in case we crash, so the post-mortem handler can |
|
2488 | # save the line away in case we crash, so the post-mortem handler can | |
2394 | # record it |
|
2489 | # record it | |
2395 | self._last_input_line = line |
|
2490 | self._last_input_line = line | |
2396 |
|
2491 | |||
2397 | #print '***line: <%s>' % line # dbg |
|
2492 | #print '***line: <%s>' % line # dbg | |
2398 |
|
2493 | |||
2399 | if not line: |
|
2494 | if not line: | |
2400 | # Return immediately on purely empty lines, so that if the user |
|
2495 | # Return immediately on purely empty lines, so that if the user | |
2401 | # previously typed some whitespace that started a continuation |
|
2496 | # previously typed some whitespace that started a continuation | |
2402 | # prompt, he can break out of that loop with just an empty line. |
|
2497 | # prompt, he can break out of that loop with just an empty line. | |
2403 | # This is how the default python prompt works. |
|
2498 | # This is how the default python prompt works. | |
2404 |
|
2499 | |||
2405 | # Only return if the accumulated input buffer was just whitespace! |
|
2500 | # Only return if the accumulated input buffer was just whitespace! | |
2406 | if ''.join(self.buffer).isspace(): |
|
2501 | if ''.join(self.buffer).isspace(): | |
2407 | self.buffer[:] = [] |
|
2502 | self.buffer[:] = [] | |
2408 | return '' |
|
2503 | return '' | |
2409 |
|
2504 | |||
2410 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2505 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2411 |
|
2506 | |||
2412 | # the input history needs to track even empty lines |
|
2507 | # the input history needs to track even empty lines | |
2413 | stripped = line.strip() |
|
2508 | stripped = line.strip() | |
2414 |
|
2509 | |||
2415 | if not stripped: |
|
2510 | if not stripped: | |
2416 | if not continue_prompt: |
|
2511 | if not continue_prompt: | |
2417 | self.outputcache.prompt_count -= 1 |
|
2512 | self.outputcache.prompt_count -= 1 | |
2418 | return self.handle_normal(line_info) |
|
2513 | return self.handle_normal(line_info) | |
2419 |
|
2514 | |||
2420 | # print '***cont',continue_prompt # dbg |
|
2515 | # print '***cont',continue_prompt # dbg | |
2421 | # special handlers are only allowed for single line statements |
|
2516 | # special handlers are only allowed for single line statements | |
2422 |
if continue_prompt and not self. |
|
2517 | if continue_prompt and not self.multi_line_specials: | |
2423 | return self.handle_normal(line_info) |
|
2518 | return self.handle_normal(line_info) | |
2424 |
|
2519 | |||
2425 |
|
2520 | |||
2426 | # See whether any pre-existing handler can take care of it |
|
2521 | # See whether any pre-existing handler can take care of it | |
2427 | rewritten = self.hooks.input_prefilter(stripped) |
|
2522 | rewritten = self.hooks.input_prefilter(stripped) | |
2428 | if rewritten != stripped: # ok, some prefilter did something |
|
2523 | if rewritten != stripped: # ok, some prefilter did something | |
2429 | rewritten = line_info.pre + rewritten # add indentation |
|
2524 | rewritten = line_info.pre + rewritten # add indentation | |
2430 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2525 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2431 | continue_prompt)) |
|
2526 | continue_prompt)) | |
2432 |
|
2527 | |||
2433 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2528 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2434 |
|
2529 | |||
2435 | return prefilter.prefilter(line_info, self) |
|
2530 | return prefilter.prefilter(line_info, self) | |
2436 |
|
2531 | |||
2437 |
|
2532 | |||
2438 | def _prefilter_dumb(self, line, continue_prompt): |
|
2533 | def _prefilter_dumb(self, line, continue_prompt): | |
2439 | """simple prefilter function, for debugging""" |
|
2534 | """simple prefilter function, for debugging""" | |
2440 | return self.handle_normal(line,continue_prompt) |
|
2535 | return self.handle_normal(line,continue_prompt) | |
2441 |
|
2536 | |||
2442 |
|
2537 | |||
2443 | def multiline_prefilter(self, line, continue_prompt): |
|
2538 | def multiline_prefilter(self, line, continue_prompt): | |
2444 | """ Run _prefilter for each line of input |
|
2539 | """ Run _prefilter for each line of input | |
2445 |
|
2540 | |||
2446 | Covers cases where there are multiple lines in the user entry, |
|
2541 | Covers cases where there are multiple lines in the user entry, | |
2447 | which is the case when the user goes back to a multiline history |
|
2542 | which is the case when the user goes back to a multiline history | |
2448 | entry and presses enter. |
|
2543 | entry and presses enter. | |
2449 |
|
2544 | |||
2450 | """ |
|
2545 | """ | |
2451 | out = [] |
|
2546 | out = [] | |
2452 | for l in line.rstrip('\n').split('\n'): |
|
2547 | for l in line.rstrip('\n').split('\n'): | |
2453 | out.append(self._prefilter(l, continue_prompt)) |
|
2548 | out.append(self._prefilter(l, continue_prompt)) | |
2454 | return '\n'.join(out) |
|
2549 | return '\n'.join(out) | |
2455 |
|
2550 | |||
2456 | # Set the default prefilter() function (this can be user-overridden) |
|
2551 | # Set the default prefilter() function (this can be user-overridden) | |
2457 | prefilter = multiline_prefilter |
|
2552 | prefilter = multiline_prefilter | |
2458 |
|
2553 | |||
2459 | def handle_normal(self,line_info): |
|
2554 | def handle_normal(self,line_info): | |
2460 | """Handle normal input lines. Use as a template for handlers.""" |
|
2555 | """Handle normal input lines. Use as a template for handlers.""" | |
2461 |
|
2556 | |||
2462 | # With autoindent on, we need some way to exit the input loop, and I |
|
2557 | # With autoindent on, we need some way to exit the input loop, and I | |
2463 | # don't want to force the user to have to backspace all the way to |
|
2558 | # don't want to force the user to have to backspace all the way to | |
2464 | # clear the line. The rule will be in this case, that either two |
|
2559 | # clear the line. The rule will be in this case, that either two | |
2465 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2560 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2466 | # of a size different to the indent level, will exit the input loop. |
|
2561 | # of a size different to the indent level, will exit the input loop. | |
2467 | line = line_info.line |
|
2562 | line = line_info.line | |
2468 | continue_prompt = line_info.continue_prompt |
|
2563 | continue_prompt = line_info.continue_prompt | |
2469 |
|
2564 | |||
2470 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2565 | if (continue_prompt and self.autoindent and line.isspace() and | |
2471 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2566 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2472 | (self.buffer[-1]).isspace() )): |
|
2567 | (self.buffer[-1]).isspace() )): | |
2473 | line = '' |
|
2568 | line = '' | |
2474 |
|
2569 | |||
2475 | self.log(line,line,continue_prompt) |
|
2570 | self.log(line,line,continue_prompt) | |
2476 | return line |
|
2571 | return line | |
2477 |
|
2572 | |||
2478 | def handle_alias(self,line_info): |
|
2573 | def handle_alias(self,line_info): | |
2479 | """Handle alias input lines. """ |
|
2574 | """Handle alias input lines. """ | |
2480 | tgt = self.alias_table[line_info.iFun] |
|
2575 | tgt = self.alias_table[line_info.iFun] | |
2481 | # print "=>",tgt #dbg |
|
2576 | # print "=>",tgt #dbg | |
2482 | if callable(tgt): |
|
2577 | if callable(tgt): | |
2483 | if '$' in line_info.line: |
|
2578 | if '$' in line_info.line: | |
2484 |
call_meth = '(_ip, _ip. |
|
2579 | call_meth = '(_ip, _ip.var_expand(%s))' | |
2485 | else: |
|
2580 | else: | |
2486 | call_meth = '(_ip,%s)' |
|
2581 | call_meth = '(_ip,%s)' | |
2487 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2582 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2488 | line_info.iFun, |
|
2583 | line_info.iFun, | |
2489 | make_quoted_expr(line_info.line)) |
|
2584 | make_quoted_expr(line_info.line)) | |
2490 | else: |
|
2585 | else: | |
2491 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2586 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2492 |
|
2587 | |||
2493 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2588 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2494 | # aliases won't work in indented sections. |
|
2589 | # aliases won't work in indented sections. | |
2495 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2590 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2496 | make_quoted_expr( transformed )) |
|
2591 | make_quoted_expr( transformed )) | |
2497 |
|
2592 | |||
2498 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2593 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2499 | #print 'line out:',line_out # dbg |
|
2594 | #print 'line out:',line_out # dbg | |
2500 | return line_out |
|
2595 | return line_out | |
2501 |
|
2596 | |||
2502 | def handle_shell_escape(self, line_info): |
|
2597 | def handle_shell_escape(self, line_info): | |
2503 | """Execute the line in a shell, empty return value""" |
|
2598 | """Execute the line in a shell, empty return value""" | |
2504 | #print 'line in :', `line` # dbg |
|
2599 | #print 'line in :', `line` # dbg | |
2505 | line = line_info.line |
|
2600 | line = line_info.line | |
2506 | if line.lstrip().startswith('!!'): |
|
2601 | if line.lstrip().startswith('!!'): | |
2507 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2602 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2508 | # call to %sx and the actual command to be executed, so |
|
2603 | # call to %sx and the actual command to be executed, so | |
2509 | # handle_magic can work correctly. Note that this works even if |
|
2604 | # handle_magic can work correctly. Note that this works even if | |
2510 | # the line is indented, so it handles multi_line_specials |
|
2605 | # the line is indented, so it handles multi_line_specials | |
2511 | # properly. |
|
2606 | # properly. | |
2512 | new_rest = line.lstrip()[2:] |
|
2607 | new_rest = line.lstrip()[2:] | |
2513 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2608 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2514 | line_info.iFun = 'sx' |
|
2609 | line_info.iFun = 'sx' | |
2515 | line_info.theRest = new_rest |
|
2610 | line_info.theRest = new_rest | |
2516 | return self.handle_magic(line_info) |
|
2611 | return self.handle_magic(line_info) | |
2517 | else: |
|
2612 | else: | |
2518 | cmd = line.lstrip().lstrip('!') |
|
2613 | cmd = line.lstrip().lstrip('!') | |
2519 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2614 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2520 | make_quoted_expr(cmd)) |
|
2615 | make_quoted_expr(cmd)) | |
2521 | # update cache/log and return |
|
2616 | # update cache/log and return | |
2522 | self.log(line,line_out,line_info.continue_prompt) |
|
2617 | self.log(line,line_out,line_info.continue_prompt) | |
2523 | return line_out |
|
2618 | return line_out | |
2524 |
|
2619 | |||
2525 | def handle_magic(self, line_info): |
|
2620 | def handle_magic(self, line_info): | |
2526 | """Execute magic functions.""" |
|
2621 | """Execute magic functions.""" | |
2527 | iFun = line_info.iFun |
|
2622 | iFun = line_info.iFun | |
2528 | theRest = line_info.theRest |
|
2623 | theRest = line_info.theRest | |
2529 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2624 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2530 | make_quoted_expr(iFun + " " + theRest)) |
|
2625 | make_quoted_expr(iFun + " " + theRest)) | |
2531 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2626 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2532 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2627 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2533 | return cmd |
|
2628 | return cmd | |
2534 |
|
2629 | |||
2535 | def handle_auto(self, line_info): |
|
2630 | def handle_auto(self, line_info): | |
2536 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2631 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2537 |
|
2632 | |||
2538 | line = line_info.line |
|
2633 | line = line_info.line | |
2539 | iFun = line_info.iFun |
|
2634 | iFun = line_info.iFun | |
2540 | theRest = line_info.theRest |
|
2635 | theRest = line_info.theRest | |
2541 | pre = line_info.pre |
|
2636 | pre = line_info.pre | |
2542 | continue_prompt = line_info.continue_prompt |
|
2637 | continue_prompt = line_info.continue_prompt | |
2543 | obj = line_info.ofind(self)['obj'] |
|
2638 | obj = line_info.ofind(self)['obj'] | |
2544 |
|
2639 | |||
2545 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2640 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2546 |
|
2641 | |||
2547 | # This should only be active for single-line input! |
|
2642 | # This should only be active for single-line input! | |
2548 | if continue_prompt: |
|
2643 | if continue_prompt: | |
2549 | self.log(line,line,continue_prompt) |
|
2644 | self.log(line,line,continue_prompt) | |
2550 | return line |
|
2645 | return line | |
2551 |
|
2646 | |||
2552 |
force_auto = isinstance(obj, |
|
2647 | force_auto = isinstance(obj, IPyAutocall) | |
2553 | auto_rewrite = True |
|
2648 | auto_rewrite = True | |
2554 |
|
2649 | |||
2555 | if pre == self.ESC_QUOTE: |
|
2650 | if pre == self.ESC_QUOTE: | |
2556 | # Auto-quote splitting on whitespace |
|
2651 | # Auto-quote splitting on whitespace | |
2557 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2652 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2558 | elif pre == self.ESC_QUOTE2: |
|
2653 | elif pre == self.ESC_QUOTE2: | |
2559 | # Auto-quote whole string |
|
2654 | # Auto-quote whole string | |
2560 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2655 | newcmd = '%s("%s")' % (iFun,theRest) | |
2561 | elif pre == self.ESC_PAREN: |
|
2656 | elif pre == self.ESC_PAREN: | |
2562 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2657 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2563 | else: |
|
2658 | else: | |
2564 | # Auto-paren. |
|
2659 | # Auto-paren. | |
2565 | # We only apply it to argument-less calls if the autocall |
|
2660 | # We only apply it to argument-less calls if the autocall | |
2566 | # parameter is set to 2. We only need to check that autocall is < |
|
2661 | # parameter is set to 2. We only need to check that autocall is < | |
2567 | # 2, since this function isn't called unless it's at least 1. |
|
2662 | # 2, since this function isn't called unless it's at least 1. | |
2568 |
if not theRest and (self |
|
2663 | if not theRest and (self.autocall < 2) and not force_auto: | |
2569 | newcmd = '%s %s' % (iFun,theRest) |
|
2664 | newcmd = '%s %s' % (iFun,theRest) | |
2570 | auto_rewrite = False |
|
2665 | auto_rewrite = False | |
2571 | else: |
|
2666 | else: | |
2572 | if not force_auto and theRest.startswith('['): |
|
2667 | if not force_auto and theRest.startswith('['): | |
2573 | if hasattr(obj,'__getitem__'): |
|
2668 | if hasattr(obj,'__getitem__'): | |
2574 | # Don't autocall in this case: item access for an object |
|
2669 | # Don't autocall in this case: item access for an object | |
2575 | # which is BOTH callable and implements __getitem__. |
|
2670 | # which is BOTH callable and implements __getitem__. | |
2576 | newcmd = '%s %s' % (iFun,theRest) |
|
2671 | newcmd = '%s %s' % (iFun,theRest) | |
2577 | auto_rewrite = False |
|
2672 | auto_rewrite = False | |
2578 | else: |
|
2673 | else: | |
2579 | # if the object doesn't support [] access, go ahead and |
|
2674 | # if the object doesn't support [] access, go ahead and | |
2580 | # autocall |
|
2675 | # autocall | |
2581 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2676 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2582 | elif theRest.endswith(';'): |
|
2677 | elif theRest.endswith(';'): | |
2583 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2678 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2584 | else: |
|
2679 | else: | |
2585 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2680 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2586 |
|
2681 | |||
2587 | if auto_rewrite: |
|
2682 | if auto_rewrite: | |
2588 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2683 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2589 |
|
2684 | |||
2590 | try: |
|
2685 | try: | |
2591 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2686 | # plain ascii works better w/ pyreadline, on some machines, so | |
2592 | # we use it and only print uncolored rewrite if we have unicode |
|
2687 | # we use it and only print uncolored rewrite if we have unicode | |
2593 | rw = str(rw) |
|
2688 | rw = str(rw) | |
2594 | print >>Term.cout, rw |
|
2689 | print >>Term.cout, rw | |
2595 | except UnicodeEncodeError: |
|
2690 | except UnicodeEncodeError: | |
2596 | print "-------------->" + newcmd |
|
2691 | print "-------------->" + newcmd | |
2597 |
|
2692 | |||
2598 | # log what is now valid Python, not the actual user input (without the |
|
2693 | # log what is now valid Python, not the actual user input (without the | |
2599 | # final newline) |
|
2694 | # final newline) | |
2600 | self.log(line,newcmd,continue_prompt) |
|
2695 | self.log(line,newcmd,continue_prompt) | |
2601 | return newcmd |
|
2696 | return newcmd | |
2602 |
|
2697 | |||
2603 | def handle_help(self, line_info): |
|
2698 | def handle_help(self, line_info): | |
2604 | """Try to get some help for the object. |
|
2699 | """Try to get some help for the object. | |
2605 |
|
2700 | |||
2606 | obj? or ?obj -> basic information. |
|
2701 | obj? or ?obj -> basic information. | |
2607 | obj?? or ??obj -> more details. |
|
2702 | obj?? or ??obj -> more details. | |
2608 | """ |
|
2703 | """ | |
2609 |
|
2704 | |||
2610 | line = line_info.line |
|
2705 | line = line_info.line | |
2611 | # We need to make sure that we don't process lines which would be |
|
2706 | # We need to make sure that we don't process lines which would be | |
2612 | # otherwise valid python, such as "x=1 # what?" |
|
2707 | # otherwise valid python, such as "x=1 # what?" | |
2613 | try: |
|
2708 | try: | |
2614 | codeop.compile_command(line) |
|
2709 | codeop.compile_command(line) | |
2615 | except SyntaxError: |
|
2710 | except SyntaxError: | |
2616 | # We should only handle as help stuff which is NOT valid syntax |
|
2711 | # We should only handle as help stuff which is NOT valid syntax | |
2617 | if line[0]==self.ESC_HELP: |
|
2712 | if line[0]==self.ESC_HELP: | |
2618 | line = line[1:] |
|
2713 | line = line[1:] | |
2619 | elif line[-1]==self.ESC_HELP: |
|
2714 | elif line[-1]==self.ESC_HELP: | |
2620 | line = line[:-1] |
|
2715 | line = line[:-1] | |
2621 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2716 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2622 | if line: |
|
2717 | if line: | |
2623 | #print 'line:<%r>' % line # dbg |
|
2718 | #print 'line:<%r>' % line # dbg | |
2624 | self.magic_pinfo(line) |
|
2719 | self.magic_pinfo(line) | |
2625 | else: |
|
2720 | else: | |
2626 |
page(self.usage,screen_lines=self. |
|
2721 | page(self.usage,screen_lines=self.usable_screen_length) | |
2627 | return '' # Empty string is needed here! |
|
2722 | return '' # Empty string is needed here! | |
2628 | except: |
|
2723 | except: | |
2629 | # Pass any other exceptions through to the normal handler |
|
2724 | # Pass any other exceptions through to the normal handler | |
2630 | return self.handle_normal(line_info) |
|
2725 | return self.handle_normal(line_info) | |
2631 | else: |
|
2726 | else: | |
2632 | # If the code compiles ok, we should handle it normally |
|
2727 | # If the code compiles ok, we should handle it normally | |
2633 | return self.handle_normal(line_info) |
|
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 | def handle_emacs(self, line_info): |
|
2730 | def handle_emacs(self, line_info): | |
2648 | """Handle input lines marked by python-mode.""" |
|
2731 | """Handle input lines marked by python-mode.""" | |
2649 |
|
2732 | |||
2650 | # Currently, nothing is done. Later more functionality can be added |
|
2733 | # Currently, nothing is done. Later more functionality can be added | |
2651 | # here if needed. |
|
2734 | # here if needed. | |
2652 |
|
2735 | |||
2653 | # The input cache shouldn't be updated |
|
2736 | # The input cache shouldn't be updated | |
2654 | return line_info.line |
|
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 | def mktempfile(self,data=None): |
|
2755 | def mktempfile(self,data=None): | |
2658 | """Make a new tempfile and return its filename. |
|
2756 | """Make a new tempfile and return its filename. | |
2659 |
|
2757 | |||
2660 | This makes a call to tempfile.mktemp, but it registers the created |
|
2758 | This makes a call to tempfile.mktemp, but it registers the created | |
2661 | filename internally so ipython cleans it up at exit time. |
|
2759 | filename internally so ipython cleans it up at exit time. | |
2662 |
|
2760 | |||
2663 | Optional inputs: |
|
2761 | Optional inputs: | |
2664 |
|
2762 | |||
2665 | - data(None): if data is given, it gets written out to the temp file |
|
2763 | - data(None): if data is given, it gets written out to the temp file | |
2666 | immediately, and the file is closed again.""" |
|
2764 | immediately, and the file is closed again.""" | |
2667 |
|
2765 | |||
2668 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2766 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2669 | self.tempfiles.append(filename) |
|
2767 | self.tempfiles.append(filename) | |
2670 |
|
2768 | |||
2671 | if data: |
|
2769 | if data: | |
2672 | tmp_file = open(filename,'w') |
|
2770 | tmp_file = open(filename,'w') | |
2673 | tmp_file.write(data) |
|
2771 | tmp_file.write(data) | |
2674 | tmp_file.close() |
|
2772 | tmp_file.close() | |
2675 | return filename |
|
2773 | return filename | |
2676 |
|
2774 | |||
2677 | def write(self,data): |
|
2775 | def write(self,data): | |
2678 | """Write a string to the default output""" |
|
2776 | """Write a string to the default output""" | |
2679 | Term.cout.write(data) |
|
2777 | Term.cout.write(data) | |
2680 |
|
2778 | |||
2681 | def write_err(self,data): |
|
2779 | def write_err(self,data): | |
2682 | """Write a string to the default error output""" |
|
2780 | """Write a string to the default error output""" | |
2683 | Term.cerr.write(data) |
|
2781 | Term.cerr.write(data) | |
2684 |
|
2782 | |||
2685 | def ask_exit(self): |
|
2783 | def ask_exit(self): | |
2686 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2784 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2687 | self.exit_now = True |
|
2785 | self.exit_now = True | |
2688 |
|
2786 | |||
2689 | def exit(self): |
|
2787 | def exit(self): | |
2690 | """Handle interactive exit. |
|
2788 | """Handle interactive exit. | |
2691 |
|
2789 | |||
2692 | This method calls the ask_exit callback.""" |
|
2790 | This method calls the ask_exit callback.""" | |
2693 |
|
2791 | if self.confirm_exit: | ||
2694 | if self.rc.confirm_exit: |
|
|||
2695 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2792 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2696 | self.ask_exit() |
|
2793 | self.ask_exit() | |
2697 | else: |
|
2794 | else: | |
2698 | self.ask_exit() |
|
2795 | self.ask_exit() | |
2699 |
|
2796 | |||
2700 | def safe_execfile(self,fname,*where,**kw): |
|
2797 | def safe_execfile(self,fname,*where,**kw): | |
2701 | """A safe version of the builtin execfile(). |
|
2798 | """A safe version of the builtin execfile(). | |
2702 |
|
2799 | |||
2703 | This version will never throw an exception, and knows how to handle |
|
2800 | This version will never throw an exception, and knows how to handle | |
2704 | ipython logs as well. |
|
2801 | ipython logs as well. | |
2705 |
|
2802 | |||
2706 | :Parameters: |
|
2803 | :Parameters: | |
2707 | fname : string |
|
2804 | fname : string | |
2708 | Name of the file to be executed. |
|
2805 | Name of the file to be executed. | |
2709 |
|
2806 | |||
2710 | where : tuple |
|
2807 | where : tuple | |
2711 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2808 | One or two namespaces, passed to execfile() as (globals,locals). | |
2712 | If only one is given, it is passed as both. |
|
2809 | If only one is given, it is passed as both. | |
2713 |
|
2810 | |||
2714 | :Keywords: |
|
2811 | :Keywords: | |
2715 | islog : boolean (False) |
|
2812 | islog : boolean (False) | |
2716 |
|
2813 | |||
2717 | quiet : boolean (True) |
|
2814 | quiet : boolean (True) | |
2718 |
|
2815 | |||
2719 | exit_ignore : boolean (False) |
|
2816 | exit_ignore : boolean (False) | |
2720 | """ |
|
2817 | """ | |
2721 |
|
2818 | |||
2722 | def syspath_cleanup(): |
|
2819 | def syspath_cleanup(): | |
2723 | """Internal cleanup routine for sys.path.""" |
|
2820 | """Internal cleanup routine for sys.path.""" | |
2724 | if add_dname: |
|
2821 | if add_dname: | |
2725 | try: |
|
2822 | try: | |
2726 | sys.path.remove(dname) |
|
2823 | sys.path.remove(dname) | |
2727 | except ValueError: |
|
2824 | except ValueError: | |
2728 | # For some reason the user has already removed it, ignore. |
|
2825 | # For some reason the user has already removed it, ignore. | |
2729 | pass |
|
2826 | pass | |
2730 |
|
2827 | |||
2731 | fname = os.path.expanduser(fname) |
|
2828 | fname = os.path.expanduser(fname) | |
2732 |
|
2829 | |||
2733 | # Find things also in current directory. This is needed to mimic the |
|
2830 | # Find things also in current directory. This is needed to mimic the | |
2734 | # behavior of running a script from the system command line, where |
|
2831 | # behavior of running a script from the system command line, where | |
2735 | # Python inserts the script's directory into sys.path |
|
2832 | # Python inserts the script's directory into sys.path | |
2736 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2833 | dname = os.path.dirname(os.path.abspath(fname)) | |
2737 | add_dname = False |
|
2834 | add_dname = False | |
2738 | if dname not in sys.path: |
|
2835 | if dname not in sys.path: | |
2739 | sys.path.insert(0,dname) |
|
2836 | sys.path.insert(0,dname) | |
2740 | add_dname = True |
|
2837 | add_dname = True | |
2741 |
|
2838 | |||
2742 | try: |
|
2839 | try: | |
2743 | xfile = open(fname) |
|
2840 | xfile = open(fname) | |
2744 | except: |
|
2841 | except: | |
2745 | print >> Term.cerr, \ |
|
2842 | print >> Term.cerr, \ | |
2746 | 'Could not open file <%s> for safe execution.' % fname |
|
2843 | 'Could not open file <%s> for safe execution.' % fname | |
2747 | syspath_cleanup() |
|
2844 | syspath_cleanup() | |
2748 | return None |
|
2845 | return None | |
2749 |
|
2846 | |||
2750 | kw.setdefault('islog',0) |
|
2847 | kw.setdefault('islog',0) | |
2751 | kw.setdefault('quiet',1) |
|
2848 | kw.setdefault('quiet',1) | |
2752 | kw.setdefault('exit_ignore',0) |
|
2849 | kw.setdefault('exit_ignore',0) | |
2753 |
|
2850 | |||
2754 | first = xfile.readline() |
|
2851 | first = xfile.readline() | |
2755 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2852 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2756 | xfile.close() |
|
2853 | xfile.close() | |
2757 | # line by line execution |
|
2854 | # line by line execution | |
2758 | if first.startswith(loghead) or kw['islog']: |
|
2855 | if first.startswith(loghead) or kw['islog']: | |
2759 | print 'Loading log file <%s> one line at a time...' % fname |
|
2856 | print 'Loading log file <%s> one line at a time...' % fname | |
2760 | if kw['quiet']: |
|
2857 | if kw['quiet']: | |
2761 | stdout_save = sys.stdout |
|
2858 | stdout_save = sys.stdout | |
2762 | sys.stdout = StringIO.StringIO() |
|
2859 | sys.stdout = StringIO.StringIO() | |
2763 | try: |
|
2860 | try: | |
2764 | globs,locs = where[0:2] |
|
2861 | globs,locs = where[0:2] | |
2765 | except: |
|
2862 | except: | |
2766 | try: |
|
2863 | try: | |
2767 | globs = locs = where[0] |
|
2864 | globs = locs = where[0] | |
2768 | except: |
|
2865 | except: | |
2769 | globs = locs = globals() |
|
2866 | globs = locs = globals() | |
2770 | badblocks = [] |
|
2867 | badblocks = [] | |
2771 |
|
2868 | |||
2772 | # we also need to identify indented blocks of code when replaying |
|
2869 | # we also need to identify indented blocks of code when replaying | |
2773 | # logs and put them together before passing them to an exec |
|
2870 | # logs and put them together before passing them to an exec | |
2774 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2871 | # statement. This takes a bit of regexp and look-ahead work in the | |
2775 | # file. It's easiest if we swallow the whole thing in memory |
|
2872 | # file. It's easiest if we swallow the whole thing in memory | |
2776 | # first, and manually walk through the lines list moving the |
|
2873 | # first, and manually walk through the lines list moving the | |
2777 | # counter ourselves. |
|
2874 | # counter ourselves. | |
2778 | indent_re = re.compile('\s+\S') |
|
2875 | indent_re = re.compile('\s+\S') | |
2779 | xfile = open(fname) |
|
2876 | xfile = open(fname) | |
2780 | filelines = xfile.readlines() |
|
2877 | filelines = xfile.readlines() | |
2781 | xfile.close() |
|
2878 | xfile.close() | |
2782 | nlines = len(filelines) |
|
2879 | nlines = len(filelines) | |
2783 | lnum = 0 |
|
2880 | lnum = 0 | |
2784 | while lnum < nlines: |
|
2881 | while lnum < nlines: | |
2785 | line = filelines[lnum] |
|
2882 | line = filelines[lnum] | |
2786 | lnum += 1 |
|
2883 | lnum += 1 | |
2787 | # don't re-insert logger status info into cache |
|
2884 | # don't re-insert logger status info into cache | |
2788 | if line.startswith('#log#'): |
|
2885 | if line.startswith('#log#'): | |
2789 | continue |
|
2886 | continue | |
2790 | else: |
|
2887 | else: | |
2791 | # build a block of code (maybe a single line) for execution |
|
2888 | # build a block of code (maybe a single line) for execution | |
2792 | block = line |
|
2889 | block = line | |
2793 | try: |
|
2890 | try: | |
2794 | next = filelines[lnum] # lnum has already incremented |
|
2891 | next = filelines[lnum] # lnum has already incremented | |
2795 | except: |
|
2892 | except: | |
2796 | next = None |
|
2893 | next = None | |
2797 | while next and indent_re.match(next): |
|
2894 | while next and indent_re.match(next): | |
2798 | block += next |
|
2895 | block += next | |
2799 | lnum += 1 |
|
2896 | lnum += 1 | |
2800 | try: |
|
2897 | try: | |
2801 | next = filelines[lnum] |
|
2898 | next = filelines[lnum] | |
2802 | except: |
|
2899 | except: | |
2803 | next = None |
|
2900 | next = None | |
2804 | # now execute the block of one or more lines |
|
2901 | # now execute the block of one or more lines | |
2805 | try: |
|
2902 | try: | |
2806 | exec block in globs,locs |
|
2903 | exec block in globs,locs | |
2807 | except SystemExit: |
|
2904 | except SystemExit: | |
2808 | pass |
|
2905 | pass | |
2809 | except: |
|
2906 | except: | |
2810 | badblocks.append(block.rstrip()) |
|
2907 | badblocks.append(block.rstrip()) | |
2811 | if kw['quiet']: # restore stdout |
|
2908 | if kw['quiet']: # restore stdout | |
2812 | sys.stdout.close() |
|
2909 | sys.stdout.close() | |
2813 | sys.stdout = stdout_save |
|
2910 | sys.stdout = stdout_save | |
2814 | print 'Finished replaying log file <%s>' % fname |
|
2911 | print 'Finished replaying log file <%s>' % fname | |
2815 | if badblocks: |
|
2912 | if badblocks: | |
2816 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2913 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2817 | '<%s> reported errors:' % fname) |
|
2914 | '<%s> reported errors:' % fname) | |
2818 |
|
2915 | |||
2819 | for badline in badblocks: |
|
2916 | for badline in badblocks: | |
2820 | print >> sys.stderr, badline |
|
2917 | print >> sys.stderr, badline | |
2821 | else: # regular file execution |
|
2918 | else: # regular file execution | |
2822 | try: |
|
2919 | try: | |
2823 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2920 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2824 | # Work around a bug in Python for Windows. The bug was |
|
2921 | # Work around a bug in Python for Windows. The bug was | |
2825 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2922 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2826 | # SVN Python as of March/07. For details, see: |
|
2923 | # SVN Python as of March/07. For details, see: | |
2827 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2924 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2828 | try: |
|
2925 | try: | |
2829 | globs,locs = where[0:2] |
|
2926 | globs,locs = where[0:2] | |
2830 | except: |
|
2927 | except: | |
2831 | try: |
|
2928 | try: | |
2832 | globs = locs = where[0] |
|
2929 | globs = locs = where[0] | |
2833 | except: |
|
2930 | except: | |
2834 | globs = locs = globals() |
|
2931 | globs = locs = globals() | |
2835 | exec file(fname) in globs,locs |
|
2932 | exec file(fname) in globs,locs | |
2836 | else: |
|
2933 | else: | |
2837 | execfile(fname,*where) |
|
2934 | execfile(fname,*where) | |
2838 | except SyntaxError: |
|
2935 | except SyntaxError: | |
2839 | self.showsyntaxerror() |
|
2936 | self.showsyntaxerror() | |
2840 | warn('Failure executing file: <%s>' % fname) |
|
2937 | warn('Failure executing file: <%s>' % fname) | |
2841 | except SystemExit,status: |
|
2938 | except SystemExit,status: | |
2842 | # Code that correctly sets the exit status flag to success (0) |
|
2939 | # Code that correctly sets the exit status flag to success (0) | |
2843 | # shouldn't be bothered with a traceback. Note that a plain |
|
2940 | # shouldn't be bothered with a traceback. Note that a plain | |
2844 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2941 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2845 | # will still get a traceback. Note that the structure of the |
|
2942 | # will still get a traceback. Note that the structure of the | |
2846 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2943 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2847 | # the checks must be done in a version-dependent way. |
|
2944 | # the checks must be done in a version-dependent way. | |
2848 | show = False |
|
2945 | show = False | |
2849 |
|
2946 | |||
2850 | if sys.version_info[:2] > (2,5): |
|
2947 | if sys.version_info[:2] > (2,5): | |
2851 | if status.message!=0 and not kw['exit_ignore']: |
|
2948 | if status.message!=0 and not kw['exit_ignore']: | |
2852 | show = True |
|
2949 | show = True | |
2853 | else: |
|
2950 | else: | |
2854 | if status.code and not kw['exit_ignore']: |
|
2951 | if status.code and not kw['exit_ignore']: | |
2855 | show = True |
|
2952 | show = True | |
2856 | if show: |
|
2953 | if show: | |
2857 | self.showtraceback() |
|
2954 | self.showtraceback() | |
2858 | warn('Failure executing file: <%s>' % fname) |
|
2955 | warn('Failure executing file: <%s>' % fname) | |
2859 | except: |
|
2956 | except: | |
2860 | self.showtraceback() |
|
2957 | self.showtraceback() | |
2861 | warn('Failure executing file: <%s>' % fname) |
|
2958 | warn('Failure executing file: <%s>' % fname) | |
2862 |
|
2959 | |||
2863 | syspath_cleanup() |
|
2960 | syspath_cleanup() | |
2864 |
|
2961 | |||
2865 | #************************* end of file <iplib.py> ***************************** |
|
2962 | #************************* end of file <iplib.py> ***************************** |
@@ -1,43 +1,41 b'' | |||||
1 | """Support for interactive macros in IPython""" |
|
1 | """Support for interactive macros in IPython""" | |
2 |
|
2 | |||
3 | #***************************************************************************** |
|
3 | #***************************************************************************** | |
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #***************************************************************************** |
|
8 | #***************************************************************************** | |
9 |
|
9 | |||
10 | from IPython.core import ipapi |
|
|||
11 |
|
||||
12 | from IPython.utils.genutils import Term |
|
10 | from IPython.utils.genutils import Term | |
13 |
from IPython.core. |
|
11 | from IPython.core.autocall import IPyAutocall | |
14 |
|
12 | |||
15 | class Macro(IPyAutocall): |
|
13 | class Macro(IPyAutocall): | |
16 | """Simple class to store the value of macros as strings. |
|
14 | """Simple class to store the value of macros as strings. | |
17 |
|
15 | |||
18 | Macro is just a callable that executes a string of IPython |
|
16 | Macro is just a callable that executes a string of IPython | |
19 | input when called. |
|
17 | input when called. | |
20 |
|
18 | |||
21 | Args to macro are available in _margv list if you need them. |
|
19 | Args to macro are available in _margv list if you need them. | |
22 | """ |
|
20 | """ | |
23 |
|
21 | |||
24 | def __init__(self,data): |
|
22 | def __init__(self,data): | |
25 |
|
23 | |||
26 | # store the macro value, as a single string which can be evaluated by |
|
24 | # store the macro value, as a single string which can be evaluated by | |
27 | # runlines() |
|
25 | # runlines() | |
28 | self.value = ''.join(data).rstrip()+'\n' |
|
26 | self.value = ''.join(data).rstrip()+'\n' | |
29 |
|
27 | |||
30 | def __str__(self): |
|
28 | def __str__(self): | |
31 | return self.value |
|
29 | return self.value | |
32 |
|
30 | |||
33 | def __repr__(self): |
|
31 | def __repr__(self): | |
34 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
32 | return 'IPython.macro.Macro(%s)' % repr(self.value) | |
35 |
|
33 | |||
36 | def __call__(self,*args): |
|
34 | def __call__(self,*args): | |
37 | Term.cout.flush() |
|
35 | Term.cout.flush() | |
38 | self._ip.user_ns['_margv'] = args |
|
36 | self._ip.user_ns['_margv'] = args | |
39 | self._ip.runlines(self.value) |
|
37 | self._ip.runlines(self.value) | |
40 |
|
38 | |||
41 | def __getstate__(self): |
|
39 | def __getstate__(self): | |
42 | """ needed for safe pickling via %store """ |
|
40 | """ needed for safe pickling via %store """ | |
43 | return {'value': self.value} |
|
41 | return {'value': self.value} |
@@ -1,3587 +1,3585 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #***************************************************************************** |
|
5 | #***************************************************************************** | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 |
|
12 | |||
13 | #**************************************************************************** |
|
13 | #**************************************************************************** | |
14 | # Modules and globals |
|
14 | # Modules and globals | |
15 |
|
15 | |||
16 | # Python standard modules |
|
16 | # Python standard modules | |
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 | import pdb |
|
21 | import pdb | |
22 | import pydoc |
|
22 | import pydoc | |
23 | import sys |
|
23 | import sys | |
24 | import re |
|
24 | import re | |
25 | import tempfile |
|
25 | import tempfile | |
26 | import time |
|
26 | import time | |
27 | import cPickle as pickle |
|
27 | import cPickle as pickle | |
28 | import textwrap |
|
28 | import textwrap | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pprint, pformat |
|
31 | from pprint import pprint, pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | # Homebrewed |
|
44 | # Homebrewed | |
45 | import IPython |
|
45 | import IPython | |
46 | from IPython.utils import wildcard |
|
46 | from IPython.utils import wildcard | |
47 | from IPython.core import debugger, oinspect |
|
47 | from IPython.core import debugger, oinspect | |
|
48 | from IPython.core.error import TryNext | |||
48 | from IPython.core.fakemodule import FakeModule |
|
49 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns |
|
50 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns | |
50 | from IPython.utils.PyColorize import Parser |
|
51 | from IPython.utils.PyColorize import Parser | |
51 | from IPython.utils.ipstruct import Struct |
|
52 | from IPython.utils.ipstruct import Struct | |
52 | from IPython.core.macro import Macro |
|
53 | from IPython.core.macro import Macro | |
53 | from IPython.utils.genutils import * |
|
54 | from IPython.utils.genutils import * | |
|
55 | from IPython.core.page import page | |||
54 | from IPython.utils import platutils |
|
56 | from IPython.utils import platutils | |
55 | import IPython.utils.generics |
|
57 | import IPython.utils.generics | |
56 |
from IPython.core import |
|
58 | from IPython.core.error import UsageError | |
57 | from IPython.core.ipapi import UsageError |
|
|||
58 | from IPython.testing import decorators as testdec |
|
59 | from IPython.testing import decorators as testdec | |
59 |
|
60 | |||
60 | #*************************************************************************** |
|
61 | #*************************************************************************** | |
61 | # Utility functions |
|
62 | # Utility functions | |
62 | def on_off(tag): |
|
63 | def on_off(tag): | |
63 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
64 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
64 | return ['OFF','ON'][tag] |
|
65 | return ['OFF','ON'][tag] | |
65 |
|
66 | |||
66 | class Bunch: pass |
|
67 | class Bunch: pass | |
67 |
|
68 | |||
68 | def compress_dhist(dh): |
|
69 | def compress_dhist(dh): | |
69 | head, tail = dh[:-10], dh[-10:] |
|
70 | head, tail = dh[:-10], dh[-10:] | |
70 |
|
71 | |||
71 | newhead = [] |
|
72 | newhead = [] | |
72 | done = set() |
|
73 | done = set() | |
73 | for h in head: |
|
74 | for h in head: | |
74 | if h in done: |
|
75 | if h in done: | |
75 | continue |
|
76 | continue | |
76 | newhead.append(h) |
|
77 | newhead.append(h) | |
77 | done.add(h) |
|
78 | done.add(h) | |
78 |
|
79 | |||
79 | return newhead + tail |
|
80 | return newhead + tail | |
80 |
|
81 | |||
81 |
|
82 | |||
82 | #*************************************************************************** |
|
83 | #*************************************************************************** | |
83 | # Main class implementing Magic functionality |
|
84 | # Main class implementing Magic functionality | |
84 | class Magic: |
|
85 | class Magic: | |
85 | """Magic functions for InteractiveShell. |
|
86 | """Magic functions for InteractiveShell. | |
86 |
|
87 | |||
87 | Shell functions which can be reached as %function_name. All magic |
|
88 | Shell functions which can be reached as %function_name. All magic | |
88 | functions should accept a string, which they can parse for their own |
|
89 | functions should accept a string, which they can parse for their own | |
89 | needs. This can make some functions easier to type, eg `%cd ../` |
|
90 | needs. This can make some functions easier to type, eg `%cd ../` | |
90 | vs. `%cd("../")` |
|
91 | vs. `%cd("../")` | |
91 |
|
92 | |||
92 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
93 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
93 | at the command line, but it is is needed in the definition. """ |
|
94 | at the command line, but it is is needed in the definition. """ | |
94 |
|
95 | |||
95 | # class globals |
|
96 | # class globals | |
96 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
97 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
97 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
98 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
98 |
|
99 | |||
99 | #...................................................................... |
|
100 | #...................................................................... | |
100 | # some utility functions |
|
101 | # some utility functions | |
101 |
|
102 | |||
102 | def __init__(self,shell): |
|
103 | def __init__(self,shell): | |
103 |
|
104 | |||
104 | self.options_table = {} |
|
105 | self.options_table = {} | |
105 | if profile is None: |
|
106 | if profile is None: | |
106 | self.magic_prun = self.profile_missing_notice |
|
107 | self.magic_prun = self.profile_missing_notice | |
107 | self.shell = shell |
|
108 | self.shell = shell | |
108 |
|
109 | |||
109 | # namespace for holding state we may need |
|
110 | # namespace for holding state we may need | |
110 | self._magic_state = Bunch() |
|
111 | self._magic_state = Bunch() | |
111 |
|
112 | |||
112 | def profile_missing_notice(self, *args, **kwargs): |
|
113 | def profile_missing_notice(self, *args, **kwargs): | |
113 | error("""\ |
|
114 | error("""\ | |
114 | The profile module could not be found. It has been removed from the standard |
|
115 | The profile module could not be found. It has been removed from the standard | |
115 | python packages because of its non-free license. To use profiling, install the |
|
116 | python packages because of its non-free license. To use profiling, install the | |
116 | python-profiler package from non-free.""") |
|
117 | python-profiler package from non-free.""") | |
117 |
|
118 | |||
118 | def default_option(self,fn,optstr): |
|
119 | def default_option(self,fn,optstr): | |
119 | """Make an entry in the options_table for fn, with value optstr""" |
|
120 | """Make an entry in the options_table for fn, with value optstr""" | |
120 |
|
121 | |||
121 | if fn not in self.lsmagic(): |
|
122 | if fn not in self.lsmagic(): | |
122 | error("%s is not a magic function" % fn) |
|
123 | error("%s is not a magic function" % fn) | |
123 | self.options_table[fn] = optstr |
|
124 | self.options_table[fn] = optstr | |
124 |
|
125 | |||
125 | def lsmagic(self): |
|
126 | def lsmagic(self): | |
126 | """Return a list of currently available magic functions. |
|
127 | """Return a list of currently available magic functions. | |
127 |
|
128 | |||
128 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
129 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
129 | ['magic_ls','magic_cd',...]""" |
|
130 | ['magic_ls','magic_cd',...]""" | |
130 |
|
131 | |||
131 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
132 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
132 |
|
133 | |||
133 | # magics in class definition |
|
134 | # magics in class definition | |
134 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
135 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
135 | callable(Magic.__dict__[fn]) |
|
136 | callable(Magic.__dict__[fn]) | |
136 | # in instance namespace (run-time user additions) |
|
137 | # in instance namespace (run-time user additions) | |
137 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
138 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
138 | callable(self.__dict__[fn]) |
|
139 | callable(self.__dict__[fn]) | |
139 | # and bound magics by user (so they can access self): |
|
140 | # and bound magics by user (so they can access self): | |
140 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
141 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
141 | callable(self.__class__.__dict__[fn]) |
|
142 | callable(self.__class__.__dict__[fn]) | |
142 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
143 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
143 | filter(inst_magic,self.__dict__.keys()) + \ |
|
144 | filter(inst_magic,self.__dict__.keys()) + \ | |
144 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
145 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
145 | out = [] |
|
146 | out = [] | |
146 | for fn in set(magics): |
|
147 | for fn in set(magics): | |
147 | out.append(fn.replace('magic_','',1)) |
|
148 | out.append(fn.replace('magic_','',1)) | |
148 | out.sort() |
|
149 | out.sort() | |
149 | return out |
|
150 | return out | |
150 |
|
151 | |||
151 | def extract_input_slices(self,slices,raw=False): |
|
152 | def extract_input_slices(self,slices,raw=False): | |
152 | """Return as a string a set of input history slices. |
|
153 | """Return as a string a set of input history slices. | |
153 |
|
154 | |||
154 | Inputs: |
|
155 | Inputs: | |
155 |
|
156 | |||
156 | - slices: the set of slices is given as a list of strings (like |
|
157 | - slices: the set of slices is given as a list of strings (like | |
157 | ['1','4:8','9'], since this function is for use by magic functions |
|
158 | ['1','4:8','9'], since this function is for use by magic functions | |
158 | which get their arguments as strings. |
|
159 | which get their arguments as strings. | |
159 |
|
160 | |||
160 | Optional inputs: |
|
161 | Optional inputs: | |
161 |
|
162 | |||
162 | - raw(False): by default, the processed input is used. If this is |
|
163 | - raw(False): by default, the processed input is used. If this is | |
163 | true, the raw input history is used instead. |
|
164 | true, the raw input history is used instead. | |
164 |
|
165 | |||
165 | Note that slices can be called with two notations: |
|
166 | Note that slices can be called with two notations: | |
166 |
|
167 | |||
167 | N:M -> standard python form, means including items N...(M-1). |
|
168 | N:M -> standard python form, means including items N...(M-1). | |
168 |
|
169 | |||
169 | N-M -> include items N..M (closed endpoint).""" |
|
170 | N-M -> include items N..M (closed endpoint).""" | |
170 |
|
171 | |||
171 | if raw: |
|
172 | if raw: | |
172 | hist = self.shell.input_hist_raw |
|
173 | hist = self.shell.input_hist_raw | |
173 | else: |
|
174 | else: | |
174 | hist = self.shell.input_hist |
|
175 | hist = self.shell.input_hist | |
175 |
|
176 | |||
176 | cmds = [] |
|
177 | cmds = [] | |
177 | for chunk in slices: |
|
178 | for chunk in slices: | |
178 | if ':' in chunk: |
|
179 | if ':' in chunk: | |
179 | ini,fin = map(int,chunk.split(':')) |
|
180 | ini,fin = map(int,chunk.split(':')) | |
180 | elif '-' in chunk: |
|
181 | elif '-' in chunk: | |
181 | ini,fin = map(int,chunk.split('-')) |
|
182 | ini,fin = map(int,chunk.split('-')) | |
182 | fin += 1 |
|
183 | fin += 1 | |
183 | else: |
|
184 | else: | |
184 | ini = int(chunk) |
|
185 | ini = int(chunk) | |
185 | fin = ini+1 |
|
186 | fin = ini+1 | |
186 | cmds.append(hist[ini:fin]) |
|
187 | cmds.append(hist[ini:fin]) | |
187 | return cmds |
|
188 | return cmds | |
188 |
|
189 | |||
189 | def _ofind(self, oname, namespaces=None): |
|
190 | def _ofind(self, oname, namespaces=None): | |
190 | """Find an object in the available namespaces. |
|
191 | """Find an object in the available namespaces. | |
191 |
|
192 | |||
192 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
193 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
193 |
|
194 | |||
194 | Has special code to detect magic functions. |
|
195 | Has special code to detect magic functions. | |
195 | """ |
|
196 | """ | |
196 |
|
197 | |||
197 | oname = oname.strip() |
|
198 | oname = oname.strip() | |
198 |
|
199 | |||
199 | alias_ns = None |
|
200 | alias_ns = None | |
200 | if namespaces is None: |
|
201 | if namespaces is None: | |
201 | # Namespaces to search in: |
|
202 | # Namespaces to search in: | |
202 | # Put them in a list. The order is important so that we |
|
203 | # Put them in a list. The order is important so that we | |
203 | # find things in the same order that Python finds them. |
|
204 | # find things in the same order that Python finds them. | |
204 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
205 | namespaces = [ ('Interactive', self.shell.user_ns), | |
205 | ('IPython internal', self.shell.internal_ns), |
|
206 | ('IPython internal', self.shell.internal_ns), | |
206 | ('Python builtin', __builtin__.__dict__), |
|
207 | ('Python builtin', __builtin__.__dict__), | |
207 | ('Alias', self.shell.alias_table), |
|
208 | ('Alias', self.shell.alias_table), | |
208 | ] |
|
209 | ] | |
209 | alias_ns = self.shell.alias_table |
|
210 | alias_ns = self.shell.alias_table | |
210 |
|
211 | |||
211 | # initialize results to 'null' |
|
212 | # initialize results to 'null' | |
212 | found = 0; obj = None; ospace = None; ds = None; |
|
213 | found = 0; obj = None; ospace = None; ds = None; | |
213 | ismagic = 0; isalias = 0; parent = None |
|
214 | ismagic = 0; isalias = 0; parent = None | |
214 |
|
215 | |||
215 | # Look for the given name by splitting it in parts. If the head is |
|
216 | # Look for the given name by splitting it in parts. If the head is | |
216 | # found, then we look for all the remaining parts as members, and only |
|
217 | # found, then we look for all the remaining parts as members, and only | |
217 | # declare success if we can find them all. |
|
218 | # declare success if we can find them all. | |
218 | oname_parts = oname.split('.') |
|
219 | oname_parts = oname.split('.') | |
219 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
220 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
220 | for nsname,ns in namespaces: |
|
221 | for nsname,ns in namespaces: | |
221 | try: |
|
222 | try: | |
222 | obj = ns[oname_head] |
|
223 | obj = ns[oname_head] | |
223 | except KeyError: |
|
224 | except KeyError: | |
224 | continue |
|
225 | continue | |
225 | else: |
|
226 | else: | |
226 | #print 'oname_rest:', oname_rest # dbg |
|
227 | #print 'oname_rest:', oname_rest # dbg | |
227 | for part in oname_rest: |
|
228 | for part in oname_rest: | |
228 | try: |
|
229 | try: | |
229 | parent = obj |
|
230 | parent = obj | |
230 | obj = getattr(obj,part) |
|
231 | obj = getattr(obj,part) | |
231 | except: |
|
232 | except: | |
232 | # Blanket except b/c some badly implemented objects |
|
233 | # Blanket except b/c some badly implemented objects | |
233 | # allow __getattr__ to raise exceptions other than |
|
234 | # allow __getattr__ to raise exceptions other than | |
234 | # AttributeError, which then crashes IPython. |
|
235 | # AttributeError, which then crashes IPython. | |
235 | break |
|
236 | break | |
236 | else: |
|
237 | else: | |
237 | # If we finish the for loop (no break), we got all members |
|
238 | # If we finish the for loop (no break), we got all members | |
238 | found = 1 |
|
239 | found = 1 | |
239 | ospace = nsname |
|
240 | ospace = nsname | |
240 | if ns == alias_ns: |
|
241 | if ns == alias_ns: | |
241 | isalias = 1 |
|
242 | isalias = 1 | |
242 | break # namespace loop |
|
243 | break # namespace loop | |
243 |
|
244 | |||
244 | # Try to see if it's magic |
|
245 | # Try to see if it's magic | |
245 | if not found: |
|
246 | if not found: | |
246 | if oname.startswith(self.shell.ESC_MAGIC): |
|
247 | if oname.startswith(self.shell.ESC_MAGIC): | |
247 | oname = oname[1:] |
|
248 | oname = oname[1:] | |
248 | obj = getattr(self,'magic_'+oname,None) |
|
249 | obj = getattr(self,'magic_'+oname,None) | |
249 | if obj is not None: |
|
250 | if obj is not None: | |
250 | found = 1 |
|
251 | found = 1 | |
251 | ospace = 'IPython internal' |
|
252 | ospace = 'IPython internal' | |
252 | ismagic = 1 |
|
253 | ismagic = 1 | |
253 |
|
254 | |||
254 | # Last try: special-case some literals like '', [], {}, etc: |
|
255 | # Last try: special-case some literals like '', [], {}, etc: | |
255 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
256 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
256 | obj = eval(oname_head) |
|
257 | obj = eval(oname_head) | |
257 | found = 1 |
|
258 | found = 1 | |
258 | ospace = 'Interactive' |
|
259 | ospace = 'Interactive' | |
259 |
|
260 | |||
260 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
261 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
261 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
262 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
262 |
|
263 | |||
263 | def arg_err(self,func): |
|
264 | def arg_err(self,func): | |
264 | """Print docstring if incorrect arguments were passed""" |
|
265 | """Print docstring if incorrect arguments were passed""" | |
265 | print 'Error in arguments:' |
|
266 | print 'Error in arguments:' | |
266 | print OInspect.getdoc(func) |
|
267 | print OInspect.getdoc(func) | |
267 |
|
268 | |||
268 | def format_latex(self,strng): |
|
269 | def format_latex(self,strng): | |
269 | """Format a string for latex inclusion.""" |
|
270 | """Format a string for latex inclusion.""" | |
270 |
|
271 | |||
271 | # Characters that need to be escaped for latex: |
|
272 | # Characters that need to be escaped for latex: | |
272 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
273 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
273 | # Magic command names as headers: |
|
274 | # Magic command names as headers: | |
274 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
275 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
275 | re.MULTILINE) |
|
276 | re.MULTILINE) | |
276 | # Magic commands |
|
277 | # Magic commands | |
277 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
278 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
278 | re.MULTILINE) |
|
279 | re.MULTILINE) | |
279 | # Paragraph continue |
|
280 | # Paragraph continue | |
280 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
281 | par_re = re.compile(r'\\$',re.MULTILINE) | |
281 |
|
282 | |||
282 | # The "\n" symbol |
|
283 | # The "\n" symbol | |
283 | newline_re = re.compile(r'\\n') |
|
284 | newline_re = re.compile(r'\\n') | |
284 |
|
285 | |||
285 | # Now build the string for output: |
|
286 | # Now build the string for output: | |
286 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
287 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
287 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
288 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
288 | strng) |
|
289 | strng) | |
289 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
290 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
290 | strng = par_re.sub(r'\\\\',strng) |
|
291 | strng = par_re.sub(r'\\\\',strng) | |
291 | strng = escape_re.sub(r'\\\1',strng) |
|
292 | strng = escape_re.sub(r'\\\1',strng) | |
292 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
293 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
293 | return strng |
|
294 | return strng | |
294 |
|
295 | |||
295 | def format_screen(self,strng): |
|
296 | def format_screen(self,strng): | |
296 | """Format a string for screen printing. |
|
297 | """Format a string for screen printing. | |
297 |
|
298 | |||
298 | This removes some latex-type format codes.""" |
|
299 | This removes some latex-type format codes.""" | |
299 | # Paragraph continue |
|
300 | # Paragraph continue | |
300 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
301 | par_re = re.compile(r'\\$',re.MULTILINE) | |
301 | strng = par_re.sub('',strng) |
|
302 | strng = par_re.sub('',strng) | |
302 | return strng |
|
303 | return strng | |
303 |
|
304 | |||
304 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
305 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
305 | """Parse options passed to an argument string. |
|
306 | """Parse options passed to an argument string. | |
306 |
|
307 | |||
307 | The interface is similar to that of getopt(), but it returns back a |
|
308 | The interface is similar to that of getopt(), but it returns back a | |
308 | Struct with the options as keys and the stripped argument string still |
|
309 | Struct with the options as keys and the stripped argument string still | |
309 | as a string. |
|
310 | as a string. | |
310 |
|
311 | |||
311 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
312 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
312 | This allows us to easily expand variables, glob files, quote |
|
313 | This allows us to easily expand variables, glob files, quote | |
313 | arguments, etc. |
|
314 | arguments, etc. | |
314 |
|
315 | |||
315 | Options: |
|
316 | Options: | |
316 | -mode: default 'string'. If given as 'list', the argument string is |
|
317 | -mode: default 'string'. If given as 'list', the argument string is | |
317 | returned as a list (split on whitespace) instead of a string. |
|
318 | returned as a list (split on whitespace) instead of a string. | |
318 |
|
319 | |||
319 | -list_all: put all option values in lists. Normally only options |
|
320 | -list_all: put all option values in lists. Normally only options | |
320 | appearing more than once are put in a list. |
|
321 | appearing more than once are put in a list. | |
321 |
|
322 | |||
322 | -posix (True): whether to split the input line in POSIX mode or not, |
|
323 | -posix (True): whether to split the input line in POSIX mode or not, | |
323 | as per the conventions outlined in the shlex module from the |
|
324 | as per the conventions outlined in the shlex module from the | |
324 | standard library.""" |
|
325 | standard library.""" | |
325 |
|
326 | |||
326 | # inject default options at the beginning of the input line |
|
327 | # inject default options at the beginning of the input line | |
327 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
328 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
328 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
329 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
329 |
|
330 | |||
330 | mode = kw.get('mode','string') |
|
331 | mode = kw.get('mode','string') | |
331 | if mode not in ['string','list']: |
|
332 | if mode not in ['string','list']: | |
332 | raise ValueError,'incorrect mode given: %s' % mode |
|
333 | raise ValueError,'incorrect mode given: %s' % mode | |
333 | # Get options |
|
334 | # Get options | |
334 | list_all = kw.get('list_all',0) |
|
335 | list_all = kw.get('list_all',0) | |
335 | posix = kw.get('posix',True) |
|
336 | posix = kw.get('posix',True) | |
336 |
|
337 | |||
337 | # Check if we have more than one argument to warrant extra processing: |
|
338 | # Check if we have more than one argument to warrant extra processing: | |
338 | odict = {} # Dictionary with options |
|
339 | odict = {} # Dictionary with options | |
339 | args = arg_str.split() |
|
340 | args = arg_str.split() | |
340 | if len(args) >= 1: |
|
341 | if len(args) >= 1: | |
341 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
342 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
342 | # need to look for options |
|
343 | # need to look for options | |
343 | argv = arg_split(arg_str,posix) |
|
344 | argv = arg_split(arg_str,posix) | |
344 | # Do regular option processing |
|
345 | # Do regular option processing | |
345 | try: |
|
346 | try: | |
346 | opts,args = getopt(argv,opt_str,*long_opts) |
|
347 | opts,args = getopt(argv,opt_str,*long_opts) | |
347 | except GetoptError,e: |
|
348 | except GetoptError,e: | |
348 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
349 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
349 | " ".join(long_opts))) |
|
350 | " ".join(long_opts))) | |
350 | for o,a in opts: |
|
351 | for o,a in opts: | |
351 | if o.startswith('--'): |
|
352 | if o.startswith('--'): | |
352 | o = o[2:] |
|
353 | o = o[2:] | |
353 | else: |
|
354 | else: | |
354 | o = o[1:] |
|
355 | o = o[1:] | |
355 | try: |
|
356 | try: | |
356 | odict[o].append(a) |
|
357 | odict[o].append(a) | |
357 | except AttributeError: |
|
358 | except AttributeError: | |
358 | odict[o] = [odict[o],a] |
|
359 | odict[o] = [odict[o],a] | |
359 | except KeyError: |
|
360 | except KeyError: | |
360 | if list_all: |
|
361 | if list_all: | |
361 | odict[o] = [a] |
|
362 | odict[o] = [a] | |
362 | else: |
|
363 | else: | |
363 | odict[o] = a |
|
364 | odict[o] = a | |
364 |
|
365 | |||
365 | # Prepare opts,args for return |
|
366 | # Prepare opts,args for return | |
366 | opts = Struct(odict) |
|
367 | opts = Struct(odict) | |
367 | if mode == 'string': |
|
368 | if mode == 'string': | |
368 | args = ' '.join(args) |
|
369 | args = ' '.join(args) | |
369 |
|
370 | |||
370 | return opts,args |
|
371 | return opts,args | |
371 |
|
372 | |||
372 | #...................................................................... |
|
373 | #...................................................................... | |
373 | # And now the actual magic functions |
|
374 | # And now the actual magic functions | |
374 |
|
375 | |||
375 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
376 | # Functions for IPython shell work (vars,funcs, config, etc) | |
376 | def magic_lsmagic(self, parameter_s = ''): |
|
377 | def magic_lsmagic(self, parameter_s = ''): | |
377 | """List currently available magic functions.""" |
|
378 | """List currently available magic functions.""" | |
378 | mesc = self.shell.ESC_MAGIC |
|
379 | mesc = self.shell.ESC_MAGIC | |
379 | print 'Available magic functions:\n'+mesc+\ |
|
380 | print 'Available magic functions:\n'+mesc+\ | |
380 | (' '+mesc).join(self.lsmagic()) |
|
381 | (' '+mesc).join(self.lsmagic()) | |
381 |
print '\n' + Magic.auto_status[self.shell. |
|
382 | print '\n' + Magic.auto_status[self.shell.automagic] | |
382 | return None |
|
383 | return None | |
383 |
|
384 | |||
384 | def magic_magic(self, parameter_s = ''): |
|
385 | def magic_magic(self, parameter_s = ''): | |
385 | """Print information about the magic function system. |
|
386 | """Print information about the magic function system. | |
386 |
|
387 | |||
387 | Supported formats: -latex, -brief, -rest |
|
388 | Supported formats: -latex, -brief, -rest | |
388 | """ |
|
389 | """ | |
389 |
|
390 | |||
390 | mode = '' |
|
391 | mode = '' | |
391 | try: |
|
392 | try: | |
392 | if parameter_s.split()[0] == '-latex': |
|
393 | if parameter_s.split()[0] == '-latex': | |
393 | mode = 'latex' |
|
394 | mode = 'latex' | |
394 | if parameter_s.split()[0] == '-brief': |
|
395 | if parameter_s.split()[0] == '-brief': | |
395 | mode = 'brief' |
|
396 | mode = 'brief' | |
396 | if parameter_s.split()[0] == '-rest': |
|
397 | if parameter_s.split()[0] == '-rest': | |
397 | mode = 'rest' |
|
398 | mode = 'rest' | |
398 | rest_docs = [] |
|
399 | rest_docs = [] | |
399 | except: |
|
400 | except: | |
400 | pass |
|
401 | pass | |
401 |
|
402 | |||
402 | magic_docs = [] |
|
403 | magic_docs = [] | |
403 | for fname in self.lsmagic(): |
|
404 | for fname in self.lsmagic(): | |
404 | mname = 'magic_' + fname |
|
405 | mname = 'magic_' + fname | |
405 | for space in (Magic,self,self.__class__): |
|
406 | for space in (Magic,self,self.__class__): | |
406 | try: |
|
407 | try: | |
407 | fn = space.__dict__[mname] |
|
408 | fn = space.__dict__[mname] | |
408 | except KeyError: |
|
409 | except KeyError: | |
409 | pass |
|
410 | pass | |
410 | else: |
|
411 | else: | |
411 | break |
|
412 | break | |
412 | if mode == 'brief': |
|
413 | if mode == 'brief': | |
413 | # only first line |
|
414 | # only first line | |
414 | if fn.__doc__: |
|
415 | if fn.__doc__: | |
415 | fndoc = fn.__doc__.split('\n',1)[0] |
|
416 | fndoc = fn.__doc__.split('\n',1)[0] | |
416 | else: |
|
417 | else: | |
417 | fndoc = 'No documentation' |
|
418 | fndoc = 'No documentation' | |
418 | else: |
|
419 | else: | |
419 | if fn.__doc__: |
|
420 | if fn.__doc__: | |
420 | fndoc = fn.__doc__.rstrip() |
|
421 | fndoc = fn.__doc__.rstrip() | |
421 | else: |
|
422 | else: | |
422 | fndoc = 'No documentation' |
|
423 | fndoc = 'No documentation' | |
423 |
|
424 | |||
424 |
|
425 | |||
425 | if mode == 'rest': |
|
426 | if mode == 'rest': | |
426 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
427 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, | |
427 | fname,fndoc)) |
|
428 | fname,fndoc)) | |
428 |
|
429 | |||
429 | else: |
|
430 | else: | |
430 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
431 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
431 | fname,fndoc)) |
|
432 | fname,fndoc)) | |
432 |
|
433 | |||
433 | magic_docs = ''.join(magic_docs) |
|
434 | magic_docs = ''.join(magic_docs) | |
434 |
|
435 | |||
435 | if mode == 'rest': |
|
436 | if mode == 'rest': | |
436 | return "".join(rest_docs) |
|
437 | return "".join(rest_docs) | |
437 |
|
438 | |||
438 | if mode == 'latex': |
|
439 | if mode == 'latex': | |
439 | print self.format_latex(magic_docs) |
|
440 | print self.format_latex(magic_docs) | |
440 | return |
|
441 | return | |
441 | else: |
|
442 | else: | |
442 | magic_docs = self.format_screen(magic_docs) |
|
443 | magic_docs = self.format_screen(magic_docs) | |
443 | if mode == 'brief': |
|
444 | if mode == 'brief': | |
444 | return magic_docs |
|
445 | return magic_docs | |
445 |
|
446 | |||
446 | outmsg = """ |
|
447 | outmsg = """ | |
447 | IPython's 'magic' functions |
|
448 | IPython's 'magic' functions | |
448 | =========================== |
|
449 | =========================== | |
449 |
|
450 | |||
450 | The magic function system provides a series of functions which allow you to |
|
451 | The magic function system provides a series of functions which allow you to | |
451 | control the behavior of IPython itself, plus a lot of system-type |
|
452 | control the behavior of IPython itself, plus a lot of system-type | |
452 | features. All these functions are prefixed with a % character, but parameters |
|
453 | features. All these functions are prefixed with a % character, but parameters | |
453 | are given without parentheses or quotes. |
|
454 | are given without parentheses or quotes. | |
454 |
|
455 | |||
455 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
456 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
456 | %automagic function), you don't need to type in the % explicitly. By default, |
|
457 | %automagic function), you don't need to type in the % explicitly. By default, | |
457 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
458 | IPython ships with automagic on, so you should only rarely need the % escape. | |
458 |
|
459 | |||
459 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
460 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
460 | to 'mydir', if it exists. |
|
461 | to 'mydir', if it exists. | |
461 |
|
462 | |||
462 | You can define your own magic functions to extend the system. See the supplied |
|
463 | You can define your own magic functions to extend the system. See the supplied | |
463 | ipythonrc and example-magic.py files for details (in your ipython |
|
464 | ipythonrc and example-magic.py files for details (in your ipython | |
464 | configuration directory, typically $HOME/.ipython/). |
|
465 | configuration directory, typically $HOME/.ipython/). | |
465 |
|
466 | |||
466 | You can also define your own aliased names for magic functions. In your |
|
467 | You can also define your own aliased names for magic functions. In your | |
467 | ipythonrc file, placing a line like: |
|
468 | ipythonrc file, placing a line like: | |
468 |
|
469 | |||
469 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
470 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
470 |
|
471 | |||
471 | will define %pf as a new name for %profile. |
|
472 | will define %pf as a new name for %profile. | |
472 |
|
473 | |||
473 |
You can also call magics in code using the |
|
474 | You can also call magics in code using the magic() function, which IPython | |
474 |
automatically adds to the builtin namespace. Type ' |
|
475 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
475 |
|
476 | |||
476 | For a list of the available magic functions, use %lsmagic. For a description |
|
477 | For a list of the available magic functions, use %lsmagic. For a description | |
477 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
478 | of any of them, type %magic_name?, e.g. '%cd?'. | |
478 |
|
479 | |||
479 | Currently the magic system has the following functions:\n""" |
|
480 | Currently the magic system has the following functions:\n""" | |
480 |
|
481 | |||
481 | mesc = self.shell.ESC_MAGIC |
|
482 | mesc = self.shell.ESC_MAGIC | |
482 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
483 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
483 | "\n\n%s%s\n\n%s" % (outmsg, |
|
484 | "\n\n%s%s\n\n%s" % (outmsg, | |
484 | magic_docs,mesc,mesc, |
|
485 | magic_docs,mesc,mesc, | |
485 | (' '+mesc).join(self.lsmagic()), |
|
486 | (' '+mesc).join(self.lsmagic()), | |
486 |
Magic.auto_status[self.shell. |
|
487 | Magic.auto_status[self.shell.automagic] ) ) | |
487 |
|
488 | |||
488 |
page(outmsg,screen_lines=self.shell. |
|
489 | page(outmsg,screen_lines=self.shell.usable_screen_length) | |
489 |
|
490 | |||
490 |
|
491 | |||
491 | def magic_autoindent(self, parameter_s = ''): |
|
492 | def magic_autoindent(self, parameter_s = ''): | |
492 | """Toggle autoindent on/off (if available).""" |
|
493 | """Toggle autoindent on/off (if available).""" | |
493 |
|
494 | |||
494 | self.shell.set_autoindent() |
|
495 | self.shell.set_autoindent() | |
495 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
496 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
496 |
|
497 | |||
497 |
|
498 | |||
498 | def magic_automagic(self, parameter_s = ''): |
|
499 | def magic_automagic(self, parameter_s = ''): | |
499 | """Make magic functions callable without having to type the initial %. |
|
500 | """Make magic functions callable without having to type the initial %. | |
500 |
|
501 | |||
501 | Without argumentsl toggles on/off (when off, you must call it as |
|
502 | Without argumentsl toggles on/off (when off, you must call it as | |
502 | %automagic, of course). With arguments it sets the value, and you can |
|
503 | %automagic, of course). With arguments it sets the value, and you can | |
503 | use any of (case insensitive): |
|
504 | use any of (case insensitive): | |
504 |
|
505 | |||
505 | - on,1,True: to activate |
|
506 | - on,1,True: to activate | |
506 |
|
507 | |||
507 | - off,0,False: to deactivate. |
|
508 | - off,0,False: to deactivate. | |
508 |
|
509 | |||
509 | Note that magic functions have lowest priority, so if there's a |
|
510 | Note that magic functions have lowest priority, so if there's a | |
510 | variable whose name collides with that of a magic fn, automagic won't |
|
511 | variable whose name collides with that of a magic fn, automagic won't | |
511 | work for that function (you get the variable instead). However, if you |
|
512 | work for that function (you get the variable instead). However, if you | |
512 | delete the variable (del var), the previously shadowed magic function |
|
513 | delete the variable (del var), the previously shadowed magic function | |
513 | becomes visible to automagic again.""" |
|
514 | becomes visible to automagic again.""" | |
514 |
|
515 | |||
515 | rc = self.shell.rc |
|
|||
516 | arg = parameter_s.lower() |
|
516 | arg = parameter_s.lower() | |
517 | if parameter_s in ('on','1','true'): |
|
517 | if parameter_s in ('on','1','true'): | |
518 |
|
|
518 | self.shell.automagic = True | |
519 | elif parameter_s in ('off','0','false'): |
|
519 | elif parameter_s in ('off','0','false'): | |
520 |
|
|
520 | self.shell.automagic = False | |
521 | else: |
|
521 | else: | |
522 |
|
|
522 | self.shell.automagic = not self.shell.automagic | |
523 |
print '\n' + Magic.auto_status[ |
|
523 | print '\n' + Magic.auto_status[self.shell.automagic] | |
524 |
|
524 | |||
525 | @testdec.skip_doctest |
|
525 | @testdec.skip_doctest | |
526 | def magic_autocall(self, parameter_s = ''): |
|
526 | def magic_autocall(self, parameter_s = ''): | |
527 | """Make functions callable without having to type parentheses. |
|
527 | """Make functions callable without having to type parentheses. | |
528 |
|
528 | |||
529 | Usage: |
|
529 | Usage: | |
530 |
|
530 | |||
531 | %autocall [mode] |
|
531 | %autocall [mode] | |
532 |
|
532 | |||
533 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
533 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
534 | value is toggled on and off (remembering the previous state). |
|
534 | value is toggled on and off (remembering the previous state). | |
535 |
|
535 | |||
536 | In more detail, these values mean: |
|
536 | In more detail, these values mean: | |
537 |
|
537 | |||
538 | 0 -> fully disabled |
|
538 | 0 -> fully disabled | |
539 |
|
539 | |||
540 | 1 -> active, but do not apply if there are no arguments on the line. |
|
540 | 1 -> active, but do not apply if there are no arguments on the line. | |
541 |
|
541 | |||
542 | In this mode, you get: |
|
542 | In this mode, you get: | |
543 |
|
543 | |||
544 | In [1]: callable |
|
544 | In [1]: callable | |
545 | Out[1]: <built-in function callable> |
|
545 | Out[1]: <built-in function callable> | |
546 |
|
546 | |||
547 | In [2]: callable 'hello' |
|
547 | In [2]: callable 'hello' | |
548 | ------> callable('hello') |
|
548 | ------> callable('hello') | |
549 | Out[2]: False |
|
549 | Out[2]: False | |
550 |
|
550 | |||
551 | 2 -> Active always. Even if no arguments are present, the callable |
|
551 | 2 -> Active always. Even if no arguments are present, the callable | |
552 | object is called: |
|
552 | object is called: | |
553 |
|
553 | |||
554 | In [2]: float |
|
554 | In [2]: float | |
555 | ------> float() |
|
555 | ------> float() | |
556 | Out[2]: 0.0 |
|
556 | Out[2]: 0.0 | |
557 |
|
557 | |||
558 | Note that even with autocall off, you can still use '/' at the start of |
|
558 | Note that even with autocall off, you can still use '/' at the start of | |
559 | a line to treat the first argument on the command line as a function |
|
559 | a line to treat the first argument on the command line as a function | |
560 | and add parentheses to it: |
|
560 | and add parentheses to it: | |
561 |
|
561 | |||
562 | In [8]: /str 43 |
|
562 | In [8]: /str 43 | |
563 | ------> str(43) |
|
563 | ------> str(43) | |
564 | Out[8]: '43' |
|
564 | Out[8]: '43' | |
565 |
|
565 | |||
566 | # all-random (note for auto-testing) |
|
566 | # all-random (note for auto-testing) | |
567 | """ |
|
567 | """ | |
568 |
|
568 | |||
569 | rc = self.shell.rc |
|
|||
570 |
|
||||
571 | if parameter_s: |
|
569 | if parameter_s: | |
572 | arg = int(parameter_s) |
|
570 | arg = int(parameter_s) | |
573 | else: |
|
571 | else: | |
574 | arg = 'toggle' |
|
572 | arg = 'toggle' | |
575 |
|
573 | |||
576 | if not arg in (0,1,2,'toggle'): |
|
574 | if not arg in (0,1,2,'toggle'): | |
577 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
575 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
578 | return |
|
576 | return | |
579 |
|
577 | |||
580 | if arg in (0,1,2): |
|
578 | if arg in (0,1,2): | |
581 |
|
|
579 | self.shell.autocall = arg | |
582 | else: # toggle |
|
580 | else: # toggle | |
583 |
if |
|
581 | if self.shell.autocall: | |
584 |
self._magic_state.autocall_save = |
|
582 | self._magic_state.autocall_save = self.shell.autocall | |
585 |
|
|
583 | self.shell.autocall = 0 | |
586 | else: |
|
584 | else: | |
587 | try: |
|
585 | try: | |
588 |
|
|
586 | self.shell.autocall = self._magic_state.autocall_save | |
589 | except AttributeError: |
|
587 | except AttributeError: | |
590 |
|
|
588 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
591 |
|
589 | |||
592 |
print "Automatic calling is:",['OFF','Smart','Full'][ |
|
590 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
593 |
|
591 | |||
594 | def magic_system_verbose(self, parameter_s = ''): |
|
592 | def magic_system_verbose(self, parameter_s = ''): | |
595 | """Set verbose printing of system calls. |
|
593 | """Set verbose printing of system calls. | |
596 |
|
594 | |||
597 | If called without an argument, act as a toggle""" |
|
595 | If called without an argument, act as a toggle""" | |
598 |
|
596 | |||
599 | if parameter_s: |
|
597 | if parameter_s: | |
600 | val = bool(eval(parameter_s)) |
|
598 | val = bool(eval(parameter_s)) | |
601 | else: |
|
599 | else: | |
602 | val = None |
|
600 | val = None | |
603 |
|
601 | |||
604 |
self.shell. |
|
602 | if self.shell.system_verbose: | |
|
603 | self.shell.system_verbose = False | |||
|
604 | else: | |||
|
605 | self.shell.system_verbose = True | |||
605 | print "System verbose printing is:",\ |
|
606 | print "System verbose printing is:",\ | |
606 |
['OFF','ON'][self.shell. |
|
607 | ['OFF','ON'][self.shell.system_verbose] | |
607 |
|
608 | |||
608 |
|
609 | |||
609 | def magic_page(self, parameter_s=''): |
|
610 | def magic_page(self, parameter_s=''): | |
610 | """Pretty print the object and display it through a pager. |
|
611 | """Pretty print the object and display it through a pager. | |
611 |
|
612 | |||
612 | %page [options] OBJECT |
|
613 | %page [options] OBJECT | |
613 |
|
614 | |||
614 | If no object is given, use _ (last output). |
|
615 | If no object is given, use _ (last output). | |
615 |
|
616 | |||
616 | Options: |
|
617 | Options: | |
617 |
|
618 | |||
618 | -r: page str(object), don't pretty-print it.""" |
|
619 | -r: page str(object), don't pretty-print it.""" | |
619 |
|
620 | |||
620 | # After a function contributed by Olivier Aubert, slightly modified. |
|
621 | # After a function contributed by Olivier Aubert, slightly modified. | |
621 |
|
622 | |||
622 | # Process options/args |
|
623 | # Process options/args | |
623 | opts,args = self.parse_options(parameter_s,'r') |
|
624 | opts,args = self.parse_options(parameter_s,'r') | |
624 | raw = 'r' in opts |
|
625 | raw = 'r' in opts | |
625 |
|
626 | |||
626 | oname = args and args or '_' |
|
627 | oname = args and args or '_' | |
627 | info = self._ofind(oname) |
|
628 | info = self._ofind(oname) | |
628 | if info['found']: |
|
629 | if info['found']: | |
629 | txt = (raw and str or pformat)( info['obj'] ) |
|
630 | txt = (raw and str or pformat)( info['obj'] ) | |
630 | page(txt) |
|
631 | page(txt) | |
631 | else: |
|
632 | else: | |
632 | print 'Object `%s` not found' % oname |
|
633 | print 'Object `%s` not found' % oname | |
633 |
|
634 | |||
634 | def magic_profile(self, parameter_s=''): |
|
635 | def magic_profile(self, parameter_s=''): | |
635 | """Print your currently active IPyhton profile.""" |
|
636 | """Print your currently active IPyhton profile.""" | |
636 |
if self.shell. |
|
637 | if self.shell.profile: | |
637 |
printpl('Current IPython profile: $self.shell. |
|
638 | printpl('Current IPython profile: $self.shell.profile.') | |
638 | else: |
|
639 | else: | |
639 | print 'No profile active.' |
|
640 | print 'No profile active.' | |
640 |
|
641 | |||
641 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
642 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
642 | """Provide detailed information about an object. |
|
643 | """Provide detailed information about an object. | |
643 |
|
644 | |||
644 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
645 | '%pinfo object' is just a synonym for object? or ?object.""" | |
645 |
|
646 | |||
646 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
647 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
647 |
|
648 | |||
648 |
|
649 | |||
649 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
650 | # detail_level: 0 -> obj? , 1 -> obj?? | |
650 | detail_level = 0 |
|
651 | detail_level = 0 | |
651 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
652 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
652 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
653 | # happen if the user types 'pinfo foo?' at the cmd line. | |
653 | pinfo,qmark1,oname,qmark2 = \ |
|
654 | pinfo,qmark1,oname,qmark2 = \ | |
654 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
655 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
655 | if pinfo or qmark1 or qmark2: |
|
656 | if pinfo or qmark1 or qmark2: | |
656 | detail_level = 1 |
|
657 | detail_level = 1 | |
657 | if "*" in oname: |
|
658 | if "*" in oname: | |
658 | self.magic_psearch(oname) |
|
659 | self.magic_psearch(oname) | |
659 | else: |
|
660 | else: | |
660 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
661 | self._inspect('pinfo', oname, detail_level=detail_level, | |
661 | namespaces=namespaces) |
|
662 | namespaces=namespaces) | |
662 |
|
663 | |||
663 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
664 | def magic_pdef(self, parameter_s='', namespaces=None): | |
664 | """Print the definition header for any callable object. |
|
665 | """Print the definition header for any callable object. | |
665 |
|
666 | |||
666 | If the object is a class, print the constructor information.""" |
|
667 | If the object is a class, print the constructor information.""" | |
667 | self._inspect('pdef',parameter_s, namespaces) |
|
668 | self._inspect('pdef',parameter_s, namespaces) | |
668 |
|
669 | |||
669 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
670 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
670 | """Print the docstring for an object. |
|
671 | """Print the docstring for an object. | |
671 |
|
672 | |||
672 | If the given object is a class, it will print both the class and the |
|
673 | If the given object is a class, it will print both the class and the | |
673 | constructor docstrings.""" |
|
674 | constructor docstrings.""" | |
674 | self._inspect('pdoc',parameter_s, namespaces) |
|
675 | self._inspect('pdoc',parameter_s, namespaces) | |
675 |
|
676 | |||
676 | def magic_psource(self, parameter_s='', namespaces=None): |
|
677 | def magic_psource(self, parameter_s='', namespaces=None): | |
677 | """Print (or run through pager) the source code for an object.""" |
|
678 | """Print (or run through pager) the source code for an object.""" | |
678 | self._inspect('psource',parameter_s, namespaces) |
|
679 | self._inspect('psource',parameter_s, namespaces) | |
679 |
|
680 | |||
680 | def magic_pfile(self, parameter_s=''): |
|
681 | def magic_pfile(self, parameter_s=''): | |
681 | """Print (or run through pager) the file where an object is defined. |
|
682 | """Print (or run through pager) the file where an object is defined. | |
682 |
|
683 | |||
683 | The file opens at the line where the object definition begins. IPython |
|
684 | The file opens at the line where the object definition begins. IPython | |
684 | will honor the environment variable PAGER if set, and otherwise will |
|
685 | will honor the environment variable PAGER if set, and otherwise will | |
685 | do its best to print the file in a convenient form. |
|
686 | do its best to print the file in a convenient form. | |
686 |
|
687 | |||
687 | If the given argument is not an object currently defined, IPython will |
|
688 | If the given argument is not an object currently defined, IPython will | |
688 | try to interpret it as a filename (automatically adding a .py extension |
|
689 | try to interpret it as a filename (automatically adding a .py extension | |
689 | if needed). You can thus use %pfile as a syntax highlighting code |
|
690 | if needed). You can thus use %pfile as a syntax highlighting code | |
690 | viewer.""" |
|
691 | viewer.""" | |
691 |
|
692 | |||
692 | # first interpret argument as an object name |
|
693 | # first interpret argument as an object name | |
693 | out = self._inspect('pfile',parameter_s) |
|
694 | out = self._inspect('pfile',parameter_s) | |
694 | # if not, try the input as a filename |
|
695 | # if not, try the input as a filename | |
695 | if out == 'not found': |
|
696 | if out == 'not found': | |
696 | try: |
|
697 | try: | |
697 | filename = get_py_filename(parameter_s) |
|
698 | filename = get_py_filename(parameter_s) | |
698 | except IOError,msg: |
|
699 | except IOError,msg: | |
699 | print msg |
|
700 | print msg | |
700 | return |
|
701 | return | |
701 | page(self.shell.inspector.format(file(filename).read())) |
|
702 | page(self.shell.inspector.format(file(filename).read())) | |
702 |
|
703 | |||
703 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
704 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
704 | """Generic interface to the inspector system. |
|
705 | """Generic interface to the inspector system. | |
705 |
|
706 | |||
706 | This function is meant to be called by pdef, pdoc & friends.""" |
|
707 | This function is meant to be called by pdef, pdoc & friends.""" | |
707 |
|
708 | |||
708 | #oname = oname.strip() |
|
709 | #oname = oname.strip() | |
709 | #print '1- oname: <%r>' % oname # dbg |
|
710 | #print '1- oname: <%r>' % oname # dbg | |
710 | try: |
|
711 | try: | |
711 | oname = oname.strip().encode('ascii') |
|
712 | oname = oname.strip().encode('ascii') | |
712 | #print '2- oname: <%r>' % oname # dbg |
|
713 | #print '2- oname: <%r>' % oname # dbg | |
713 | except UnicodeEncodeError: |
|
714 | except UnicodeEncodeError: | |
714 | print 'Python identifiers can only contain ascii characters.' |
|
715 | print 'Python identifiers can only contain ascii characters.' | |
715 | return 'not found' |
|
716 | return 'not found' | |
716 |
|
717 | |||
717 | info = Struct(self._ofind(oname, namespaces)) |
|
718 | info = Struct(self._ofind(oname, namespaces)) | |
718 |
|
719 | |||
719 | if info.found: |
|
720 | if info.found: | |
720 | try: |
|
721 | try: | |
721 | IPython.utils.generics.inspect_object(info.obj) |
|
722 | IPython.utils.generics.inspect_object(info.obj) | |
722 | return |
|
723 | return | |
723 |
except |
|
724 | except TryNext: | |
724 | pass |
|
725 | pass | |
725 | # Get the docstring of the class property if it exists. |
|
726 | # Get the docstring of the class property if it exists. | |
726 | path = oname.split('.') |
|
727 | path = oname.split('.') | |
727 | root = '.'.join(path[:-1]) |
|
728 | root = '.'.join(path[:-1]) | |
728 | if info.parent is not None: |
|
729 | if info.parent is not None: | |
729 | try: |
|
730 | try: | |
730 | target = getattr(info.parent, '__class__') |
|
731 | target = getattr(info.parent, '__class__') | |
731 | # The object belongs to a class instance. |
|
732 | # The object belongs to a class instance. | |
732 | try: |
|
733 | try: | |
733 | target = getattr(target, path[-1]) |
|
734 | target = getattr(target, path[-1]) | |
734 | # The class defines the object. |
|
735 | # The class defines the object. | |
735 | if isinstance(target, property): |
|
736 | if isinstance(target, property): | |
736 | oname = root + '.__class__.' + path[-1] |
|
737 | oname = root + '.__class__.' + path[-1] | |
737 | info = Struct(self._ofind(oname)) |
|
738 | info = Struct(self._ofind(oname)) | |
738 | except AttributeError: pass |
|
739 | except AttributeError: pass | |
739 | except AttributeError: pass |
|
740 | except AttributeError: pass | |
740 |
|
741 | |||
741 | pmethod = getattr(self.shell.inspector,meth) |
|
742 | pmethod = getattr(self.shell.inspector,meth) | |
742 | formatter = info.ismagic and self.format_screen or None |
|
743 | formatter = info.ismagic and self.format_screen or None | |
743 | if meth == 'pdoc': |
|
744 | if meth == 'pdoc': | |
744 | pmethod(info.obj,oname,formatter) |
|
745 | pmethod(info.obj,oname,formatter) | |
745 | elif meth == 'pinfo': |
|
746 | elif meth == 'pinfo': | |
746 | pmethod(info.obj,oname,formatter,info,**kw) |
|
747 | pmethod(info.obj,oname,formatter,info,**kw) | |
747 | else: |
|
748 | else: | |
748 | pmethod(info.obj,oname) |
|
749 | pmethod(info.obj,oname) | |
749 | else: |
|
750 | else: | |
750 | print 'Object `%s` not found.' % oname |
|
751 | print 'Object `%s` not found.' % oname | |
751 | return 'not found' # so callers can take other action |
|
752 | return 'not found' # so callers can take other action | |
752 |
|
753 | |||
753 | def magic_psearch(self, parameter_s=''): |
|
754 | def magic_psearch(self, parameter_s=''): | |
754 | """Search for object in namespaces by wildcard. |
|
755 | """Search for object in namespaces by wildcard. | |
755 |
|
756 | |||
756 | %psearch [options] PATTERN [OBJECT TYPE] |
|
757 | %psearch [options] PATTERN [OBJECT TYPE] | |
757 |
|
758 | |||
758 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
759 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
759 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
760 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
760 | rest of the command line must be unchanged (options come first), so |
|
761 | rest of the command line must be unchanged (options come first), so | |
761 | for example the following forms are equivalent |
|
762 | for example the following forms are equivalent | |
762 |
|
763 | |||
763 | %psearch -i a* function |
|
764 | %psearch -i a* function | |
764 | -i a* function? |
|
765 | -i a* function? | |
765 | ?-i a* function |
|
766 | ?-i a* function | |
766 |
|
767 | |||
767 | Arguments: |
|
768 | Arguments: | |
768 |
|
769 | |||
769 | PATTERN |
|
770 | PATTERN | |
770 |
|
771 | |||
771 | where PATTERN is a string containing * as a wildcard similar to its |
|
772 | where PATTERN is a string containing * as a wildcard similar to its | |
772 | use in a shell. The pattern is matched in all namespaces on the |
|
773 | use in a shell. The pattern is matched in all namespaces on the | |
773 | search path. By default objects starting with a single _ are not |
|
774 | search path. By default objects starting with a single _ are not | |
774 | matched, many IPython generated objects have a single |
|
775 | matched, many IPython generated objects have a single | |
775 | underscore. The default is case insensitive matching. Matching is |
|
776 | underscore. The default is case insensitive matching. Matching is | |
776 | also done on the attributes of objects and not only on the objects |
|
777 | also done on the attributes of objects and not only on the objects | |
777 | in a module. |
|
778 | in a module. | |
778 |
|
779 | |||
779 | [OBJECT TYPE] |
|
780 | [OBJECT TYPE] | |
780 |
|
781 | |||
781 | Is the name of a python type from the types module. The name is |
|
782 | Is the name of a python type from the types module. The name is | |
782 | given in lowercase without the ending type, ex. StringType is |
|
783 | given in lowercase without the ending type, ex. StringType is | |
783 | written string. By adding a type here only objects matching the |
|
784 | written string. By adding a type here only objects matching the | |
784 | given type are matched. Using all here makes the pattern match all |
|
785 | given type are matched. Using all here makes the pattern match all | |
785 | types (this is the default). |
|
786 | types (this is the default). | |
786 |
|
787 | |||
787 | Options: |
|
788 | Options: | |
788 |
|
789 | |||
789 | -a: makes the pattern match even objects whose names start with a |
|
790 | -a: makes the pattern match even objects whose names start with a | |
790 | single underscore. These names are normally ommitted from the |
|
791 | single underscore. These names are normally ommitted from the | |
791 | search. |
|
792 | search. | |
792 |
|
793 | |||
793 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
794 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
794 | these options is given, the default is read from your ipythonrc |
|
795 | these options is given, the default is read from your ipythonrc | |
795 | file. The option name which sets this value is |
|
796 | file. The option name which sets this value is | |
796 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
797 | 'wildcards_case_sensitive'. If this option is not specified in your | |
797 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
798 | ipythonrc file, IPython's internal default is to do a case sensitive | |
798 | search. |
|
799 | search. | |
799 |
|
800 | |||
800 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
801 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
801 | specifiy can be searched in any of the following namespaces: |
|
802 | specifiy can be searched in any of the following namespaces: | |
802 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
803 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
803 | 'builtin' and 'user' are the search defaults. Note that you should |
|
804 | 'builtin' and 'user' are the search defaults. Note that you should | |
804 | not use quotes when specifying namespaces. |
|
805 | not use quotes when specifying namespaces. | |
805 |
|
806 | |||
806 | 'Builtin' contains the python module builtin, 'user' contains all |
|
807 | 'Builtin' contains the python module builtin, 'user' contains all | |
807 | user data, 'alias' only contain the shell aliases and no python |
|
808 | user data, 'alias' only contain the shell aliases and no python | |
808 | objects, 'internal' contains objects used by IPython. The |
|
809 | objects, 'internal' contains objects used by IPython. The | |
809 | 'user_global' namespace is only used by embedded IPython instances, |
|
810 | 'user_global' namespace is only used by embedded IPython instances, | |
810 | and it contains module-level globals. You can add namespaces to the |
|
811 | and it contains module-level globals. You can add namespaces to the | |
811 | search with -s or exclude them with -e (these options can be given |
|
812 | search with -s or exclude them with -e (these options can be given | |
812 | more than once). |
|
813 | more than once). | |
813 |
|
814 | |||
814 | Examples: |
|
815 | Examples: | |
815 |
|
816 | |||
816 | %psearch a* -> objects beginning with an a |
|
817 | %psearch a* -> objects beginning with an a | |
817 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
818 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
818 | %psearch a* function -> all functions beginning with an a |
|
819 | %psearch a* function -> all functions beginning with an a | |
819 | %psearch re.e* -> objects beginning with an e in module re |
|
820 | %psearch re.e* -> objects beginning with an e in module re | |
820 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
821 | %psearch r*.e* -> objects that start with e in modules starting in r | |
821 | %psearch r*.* string -> all strings in modules beginning with r |
|
822 | %psearch r*.* string -> all strings in modules beginning with r | |
822 |
|
823 | |||
823 | Case sensitve search: |
|
824 | Case sensitve search: | |
824 |
|
825 | |||
825 | %psearch -c a* list all object beginning with lower case a |
|
826 | %psearch -c a* list all object beginning with lower case a | |
826 |
|
827 | |||
827 | Show objects beginning with a single _: |
|
828 | Show objects beginning with a single _: | |
828 |
|
829 | |||
829 | %psearch -a _* list objects beginning with a single underscore""" |
|
830 | %psearch -a _* list objects beginning with a single underscore""" | |
830 | try: |
|
831 | try: | |
831 | parameter_s = parameter_s.encode('ascii') |
|
832 | parameter_s = parameter_s.encode('ascii') | |
832 | except UnicodeEncodeError: |
|
833 | except UnicodeEncodeError: | |
833 | print 'Python identifiers can only contain ascii characters.' |
|
834 | print 'Python identifiers can only contain ascii characters.' | |
834 | return |
|
835 | return | |
835 |
|
836 | |||
836 | # default namespaces to be searched |
|
837 | # default namespaces to be searched | |
837 | def_search = ['user','builtin'] |
|
838 | def_search = ['user','builtin'] | |
838 |
|
839 | |||
839 | # Process options/args |
|
840 | # Process options/args | |
840 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
841 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
841 | opt = opts.get |
|
842 | opt = opts.get | |
842 | shell = self.shell |
|
843 | shell = self.shell | |
843 | psearch = shell.inspector.psearch |
|
844 | psearch = shell.inspector.psearch | |
844 |
|
845 | |||
845 | # select case options |
|
846 | # select case options | |
846 | if opts.has_key('i'): |
|
847 | if opts.has_key('i'): | |
847 | ignore_case = True |
|
848 | ignore_case = True | |
848 | elif opts.has_key('c'): |
|
849 | elif opts.has_key('c'): | |
849 | ignore_case = False |
|
850 | ignore_case = False | |
850 | else: |
|
851 | else: | |
851 |
ignore_case = not shell. |
|
852 | ignore_case = not shell.wildcards_case_sensitive | |
852 |
|
853 | |||
853 | # Build list of namespaces to search from user options |
|
854 | # Build list of namespaces to search from user options | |
854 | def_search.extend(opt('s',[])) |
|
855 | def_search.extend(opt('s',[])) | |
855 | ns_exclude = ns_exclude=opt('e',[]) |
|
856 | ns_exclude = ns_exclude=opt('e',[]) | |
856 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
857 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
857 |
|
858 | |||
858 | # Call the actual search |
|
859 | # Call the actual search | |
859 | try: |
|
860 | try: | |
860 | psearch(args,shell.ns_table,ns_search, |
|
861 | psearch(args,shell.ns_table,ns_search, | |
861 | show_all=opt('a'),ignore_case=ignore_case) |
|
862 | show_all=opt('a'),ignore_case=ignore_case) | |
862 | except: |
|
863 | except: | |
863 | shell.showtraceback() |
|
864 | shell.showtraceback() | |
864 |
|
865 | |||
865 | def magic_who_ls(self, parameter_s=''): |
|
866 | def magic_who_ls(self, parameter_s=''): | |
866 | """Return a sorted list of all interactive variables. |
|
867 | """Return a sorted list of all interactive variables. | |
867 |
|
868 | |||
868 | If arguments are given, only variables of types matching these |
|
869 | If arguments are given, only variables of types matching these | |
869 | arguments are returned.""" |
|
870 | arguments are returned.""" | |
870 |
|
871 | |||
871 | user_ns = self.shell.user_ns |
|
872 | user_ns = self.shell.user_ns | |
872 | internal_ns = self.shell.internal_ns |
|
873 | internal_ns = self.shell.internal_ns | |
873 | user_config_ns = self.shell.user_config_ns |
|
874 | user_config_ns = self.shell.user_config_ns | |
874 | out = [] |
|
875 | out = [] | |
875 | typelist = parameter_s.split() |
|
876 | typelist = parameter_s.split() | |
876 |
|
877 | |||
877 | for i in user_ns: |
|
878 | for i in user_ns: | |
878 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
879 | if not (i.startswith('_') or i.startswith('_i')) \ | |
879 | and not (i in internal_ns or i in user_config_ns): |
|
880 | and not (i in internal_ns or i in user_config_ns): | |
880 | if typelist: |
|
881 | if typelist: | |
881 | if type(user_ns[i]).__name__ in typelist: |
|
882 | if type(user_ns[i]).__name__ in typelist: | |
882 | out.append(i) |
|
883 | out.append(i) | |
883 | else: |
|
884 | else: | |
884 | out.append(i) |
|
885 | out.append(i) | |
885 | out.sort() |
|
886 | out.sort() | |
886 | return out |
|
887 | return out | |
887 |
|
888 | |||
888 | def magic_who(self, parameter_s=''): |
|
889 | def magic_who(self, parameter_s=''): | |
889 | """Print all interactive variables, with some minimal formatting. |
|
890 | """Print all interactive variables, with some minimal formatting. | |
890 |
|
891 | |||
891 | If any arguments are given, only variables whose type matches one of |
|
892 | If any arguments are given, only variables whose type matches one of | |
892 | these are printed. For example: |
|
893 | these are printed. For example: | |
893 |
|
894 | |||
894 | %who function str |
|
895 | %who function str | |
895 |
|
896 | |||
896 | will only list functions and strings, excluding all other types of |
|
897 | will only list functions and strings, excluding all other types of | |
897 | variables. To find the proper type names, simply use type(var) at a |
|
898 | variables. To find the proper type names, simply use type(var) at a | |
898 | command line to see how python prints type names. For example: |
|
899 | command line to see how python prints type names. For example: | |
899 |
|
900 | |||
900 | In [1]: type('hello')\\ |
|
901 | In [1]: type('hello')\\ | |
901 | Out[1]: <type 'str'> |
|
902 | Out[1]: <type 'str'> | |
902 |
|
903 | |||
903 | indicates that the type name for strings is 'str'. |
|
904 | indicates that the type name for strings is 'str'. | |
904 |
|
905 | |||
905 | %who always excludes executed names loaded through your configuration |
|
906 | %who always excludes executed names loaded through your configuration | |
906 | file and things which are internal to IPython. |
|
907 | file and things which are internal to IPython. | |
907 |
|
908 | |||
908 | This is deliberate, as typically you may load many modules and the |
|
909 | This is deliberate, as typically you may load many modules and the | |
909 | purpose of %who is to show you only what you've manually defined.""" |
|
910 | purpose of %who is to show you only what you've manually defined.""" | |
910 |
|
911 | |||
911 | varlist = self.magic_who_ls(parameter_s) |
|
912 | varlist = self.magic_who_ls(parameter_s) | |
912 | if not varlist: |
|
913 | if not varlist: | |
913 | if parameter_s: |
|
914 | if parameter_s: | |
914 | print 'No variables match your requested type.' |
|
915 | print 'No variables match your requested type.' | |
915 | else: |
|
916 | else: | |
916 | print 'Interactive namespace is empty.' |
|
917 | print 'Interactive namespace is empty.' | |
917 | return |
|
918 | return | |
918 |
|
919 | |||
919 | # if we have variables, move on... |
|
920 | # if we have variables, move on... | |
920 | count = 0 |
|
921 | count = 0 | |
921 | for i in varlist: |
|
922 | for i in varlist: | |
922 | print i+'\t', |
|
923 | print i+'\t', | |
923 | count += 1 |
|
924 | count += 1 | |
924 | if count > 8: |
|
925 | if count > 8: | |
925 | count = 0 |
|
926 | count = 0 | |
926 |
|
927 | |||
927 |
|
928 | |||
928 |
|
929 | |||
929 | def magic_whos(self, parameter_s=''): |
|
930 | def magic_whos(self, parameter_s=''): | |
930 | """Like %who, but gives some extra information about each variable. |
|
931 | """Like %who, but gives some extra information about each variable. | |
931 |
|
932 | |||
932 | The same type filtering of %who can be applied here. |
|
933 | The same type filtering of %who can be applied here. | |
933 |
|
934 | |||
934 | For all variables, the type is printed. Additionally it prints: |
|
935 | For all variables, the type is printed. Additionally it prints: | |
935 |
|
936 | |||
936 | - For {},[],(): their length. |
|
937 | - For {},[],(): their length. | |
937 |
|
938 | |||
938 | - For numpy and Numeric arrays, a summary with shape, number of |
|
939 | - For numpy and Numeric arrays, a summary with shape, number of | |
939 | elements, typecode and size in memory. |
|
940 | elements, typecode and size in memory. | |
940 |
|
941 | |||
941 | - Everything else: a string representation, snipping their middle if |
|
942 | - Everything else: a string representation, snipping their middle if | |
942 | too long.""" |
|
943 | too long.""" | |
943 |
|
944 | |||
944 | varnames = self.magic_who_ls(parameter_s) |
|
945 | varnames = self.magic_who_ls(parameter_s) | |
945 | if not varnames: |
|
946 | if not varnames: | |
946 | if parameter_s: |
|
947 | if parameter_s: | |
947 | print 'No variables match your requested type.' |
|
948 | print 'No variables match your requested type.' | |
948 | else: |
|
949 | else: | |
949 | print 'Interactive namespace is empty.' |
|
950 | print 'Interactive namespace is empty.' | |
950 | return |
|
951 | return | |
951 |
|
952 | |||
952 | # if we have variables, move on... |
|
953 | # if we have variables, move on... | |
953 |
|
954 | |||
954 | # for these types, show len() instead of data: |
|
955 | # for these types, show len() instead of data: | |
955 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
956 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
956 |
|
957 | |||
957 | # for numpy/Numeric arrays, display summary info |
|
958 | # for numpy/Numeric arrays, display summary info | |
958 | try: |
|
959 | try: | |
959 | import numpy |
|
960 | import numpy | |
960 | except ImportError: |
|
961 | except ImportError: | |
961 | ndarray_type = None |
|
962 | ndarray_type = None | |
962 | else: |
|
963 | else: | |
963 | ndarray_type = numpy.ndarray.__name__ |
|
964 | ndarray_type = numpy.ndarray.__name__ | |
964 | try: |
|
965 | try: | |
965 | import Numeric |
|
966 | import Numeric | |
966 | except ImportError: |
|
967 | except ImportError: | |
967 | array_type = None |
|
968 | array_type = None | |
968 | else: |
|
969 | else: | |
969 | array_type = Numeric.ArrayType.__name__ |
|
970 | array_type = Numeric.ArrayType.__name__ | |
970 |
|
971 | |||
971 | # Find all variable names and types so we can figure out column sizes |
|
972 | # Find all variable names and types so we can figure out column sizes | |
972 | def get_vars(i): |
|
973 | def get_vars(i): | |
973 | return self.shell.user_ns[i] |
|
974 | return self.shell.user_ns[i] | |
974 |
|
975 | |||
975 | # some types are well known and can be shorter |
|
976 | # some types are well known and can be shorter | |
976 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
977 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
977 | def type_name(v): |
|
978 | def type_name(v): | |
978 | tn = type(v).__name__ |
|
979 | tn = type(v).__name__ | |
979 | return abbrevs.get(tn,tn) |
|
980 | return abbrevs.get(tn,tn) | |
980 |
|
981 | |||
981 | varlist = map(get_vars,varnames) |
|
982 | varlist = map(get_vars,varnames) | |
982 |
|
983 | |||
983 | typelist = [] |
|
984 | typelist = [] | |
984 | for vv in varlist: |
|
985 | for vv in varlist: | |
985 | tt = type_name(vv) |
|
986 | tt = type_name(vv) | |
986 |
|
987 | |||
987 | if tt=='instance': |
|
988 | if tt=='instance': | |
988 | typelist.append( abbrevs.get(str(vv.__class__), |
|
989 | typelist.append( abbrevs.get(str(vv.__class__), | |
989 | str(vv.__class__))) |
|
990 | str(vv.__class__))) | |
990 | else: |
|
991 | else: | |
991 | typelist.append(tt) |
|
992 | typelist.append(tt) | |
992 |
|
993 | |||
993 | # column labels and # of spaces as separator |
|
994 | # column labels and # of spaces as separator | |
994 | varlabel = 'Variable' |
|
995 | varlabel = 'Variable' | |
995 | typelabel = 'Type' |
|
996 | typelabel = 'Type' | |
996 | datalabel = 'Data/Info' |
|
997 | datalabel = 'Data/Info' | |
997 | colsep = 3 |
|
998 | colsep = 3 | |
998 | # variable format strings |
|
999 | # variable format strings | |
999 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1000 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
1000 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1001 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
1001 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1002 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
1002 | # find the size of the columns to format the output nicely |
|
1003 | # find the size of the columns to format the output nicely | |
1003 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1004 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1004 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1005 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1005 | # table header |
|
1006 | # table header | |
1006 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1007 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1007 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1008 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1008 | # and the table itself |
|
1009 | # and the table itself | |
1009 | kb = 1024 |
|
1010 | kb = 1024 | |
1010 | Mb = 1048576 # kb**2 |
|
1011 | Mb = 1048576 # kb**2 | |
1011 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1012 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1012 | print itpl(vformat), |
|
1013 | print itpl(vformat), | |
1013 | if vtype in seq_types: |
|
1014 | if vtype in seq_types: | |
1014 | print len(var) |
|
1015 | print len(var) | |
1015 | elif vtype in [array_type,ndarray_type]: |
|
1016 | elif vtype in [array_type,ndarray_type]: | |
1016 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1017 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1017 | if vtype==ndarray_type: |
|
1018 | if vtype==ndarray_type: | |
1018 | # numpy |
|
1019 | # numpy | |
1019 | vsize = var.size |
|
1020 | vsize = var.size | |
1020 | vbytes = vsize*var.itemsize |
|
1021 | vbytes = vsize*var.itemsize | |
1021 | vdtype = var.dtype |
|
1022 | vdtype = var.dtype | |
1022 | else: |
|
1023 | else: | |
1023 | # Numeric |
|
1024 | # Numeric | |
1024 | vsize = Numeric.size(var) |
|
1025 | vsize = Numeric.size(var) | |
1025 | vbytes = vsize*var.itemsize() |
|
1026 | vbytes = vsize*var.itemsize() | |
1026 | vdtype = var.typecode() |
|
1027 | vdtype = var.typecode() | |
1027 |
|
1028 | |||
1028 | if vbytes < 100000: |
|
1029 | if vbytes < 100000: | |
1029 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1030 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1030 | else: |
|
1031 | else: | |
1031 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1032 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1032 | if vbytes < Mb: |
|
1033 | if vbytes < Mb: | |
1033 | print '(%s kb)' % (vbytes/kb,) |
|
1034 | print '(%s kb)' % (vbytes/kb,) | |
1034 | else: |
|
1035 | else: | |
1035 | print '(%s Mb)' % (vbytes/Mb,) |
|
1036 | print '(%s Mb)' % (vbytes/Mb,) | |
1036 | else: |
|
1037 | else: | |
1037 | try: |
|
1038 | try: | |
1038 | vstr = str(var) |
|
1039 | vstr = str(var) | |
1039 | except UnicodeEncodeError: |
|
1040 | except UnicodeEncodeError: | |
1040 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1041 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
1041 | 'backslashreplace') |
|
1042 | 'backslashreplace') | |
1042 | vstr = vstr.replace('\n','\\n') |
|
1043 | vstr = vstr.replace('\n','\\n') | |
1043 | if len(vstr) < 50: |
|
1044 | if len(vstr) < 50: | |
1044 | print vstr |
|
1045 | print vstr | |
1045 | else: |
|
1046 | else: | |
1046 | printpl(vfmt_short) |
|
1047 | printpl(vfmt_short) | |
1047 |
|
1048 | |||
1048 | def magic_reset(self, parameter_s=''): |
|
1049 | def magic_reset(self, parameter_s=''): | |
1049 | """Resets the namespace by removing all names defined by the user. |
|
1050 | """Resets the namespace by removing all names defined by the user. | |
1050 |
|
1051 | |||
1051 | Input/Output history are left around in case you need them. |
|
1052 | Input/Output history are left around in case you need them. | |
1052 |
|
1053 | |||
1053 | Parameters |
|
1054 | Parameters | |
1054 | ---------- |
|
1055 | ---------- | |
1055 | -y : force reset without asking for confirmation. |
|
1056 | -y : force reset without asking for confirmation. | |
1056 |
|
1057 | |||
1057 | Examples |
|
1058 | Examples | |
1058 | -------- |
|
1059 | -------- | |
1059 | In [6]: a = 1 |
|
1060 | In [6]: a = 1 | |
1060 |
|
1061 | |||
1061 | In [7]: a |
|
1062 | In [7]: a | |
1062 | Out[7]: 1 |
|
1063 | Out[7]: 1 | |
1063 |
|
1064 | |||
1064 | In [8]: 'a' in _ip.user_ns |
|
1065 | In [8]: 'a' in _ip.user_ns | |
1065 | Out[8]: True |
|
1066 | Out[8]: True | |
1066 |
|
1067 | |||
1067 | In [9]: %reset -f |
|
1068 | In [9]: %reset -f | |
1068 |
|
1069 | |||
1069 | In [10]: 'a' in _ip.user_ns |
|
1070 | In [10]: 'a' in _ip.user_ns | |
1070 | Out[10]: False |
|
1071 | Out[10]: False | |
1071 | """ |
|
1072 | """ | |
1072 |
|
1073 | |||
1073 | if parameter_s == '-f': |
|
1074 | if parameter_s == '-f': | |
1074 | ans = True |
|
1075 | ans = True | |
1075 | else: |
|
1076 | else: | |
1076 | ans = self.shell.ask_yes_no( |
|
1077 | ans = self.shell.ask_yes_no( | |
1077 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1078 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1078 | if not ans: |
|
1079 | if not ans: | |
1079 | print 'Nothing done.' |
|
1080 | print 'Nothing done.' | |
1080 | return |
|
1081 | return | |
1081 | user_ns = self.shell.user_ns |
|
1082 | user_ns = self.shell.user_ns | |
1082 | for i in self.magic_who_ls(): |
|
1083 | for i in self.magic_who_ls(): | |
1083 | del(user_ns[i]) |
|
1084 | del(user_ns[i]) | |
1084 |
|
1085 | |||
1085 | # Also flush the private list of module references kept for script |
|
1086 | # Also flush the private list of module references kept for script | |
1086 | # execution protection |
|
1087 | # execution protection | |
1087 | self.shell.clear_main_mod_cache() |
|
1088 | self.shell.clear_main_mod_cache() | |
1088 |
|
1089 | |||
1089 | def magic_logstart(self,parameter_s=''): |
|
1090 | def magic_logstart(self,parameter_s=''): | |
1090 | """Start logging anywhere in a session. |
|
1091 | """Start logging anywhere in a session. | |
1091 |
|
1092 | |||
1092 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1093 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1093 |
|
1094 | |||
1094 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1095 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1095 | current directory, in 'rotate' mode (see below). |
|
1096 | current directory, in 'rotate' mode (see below). | |
1096 |
|
1097 | |||
1097 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1098 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1098 | history up to that point and then continues logging. |
|
1099 | history up to that point and then continues logging. | |
1099 |
|
1100 | |||
1100 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1101 | %logstart takes a second optional parameter: logging mode. This can be one | |
1101 | of (note that the modes are given unquoted):\\ |
|
1102 | of (note that the modes are given unquoted):\\ | |
1102 | append: well, that says it.\\ |
|
1103 | append: well, that says it.\\ | |
1103 | backup: rename (if exists) to name~ and start name.\\ |
|
1104 | backup: rename (if exists) to name~ and start name.\\ | |
1104 | global: single logfile in your home dir, appended to.\\ |
|
1105 | global: single logfile in your home dir, appended to.\\ | |
1105 | over : overwrite existing log.\\ |
|
1106 | over : overwrite existing log.\\ | |
1106 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1107 | rotate: create rotating logs name.1~, name.2~, etc. | |
1107 |
|
1108 | |||
1108 | Options: |
|
1109 | Options: | |
1109 |
|
1110 | |||
1110 | -o: log also IPython's output. In this mode, all commands which |
|
1111 | -o: log also IPython's output. In this mode, all commands which | |
1111 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1112 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1112 | their corresponding input line. The output lines are always |
|
1113 | their corresponding input line. The output lines are always | |
1113 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1114 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1114 | Python code. |
|
1115 | Python code. | |
1115 |
|
1116 | |||
1116 | Since this marker is always the same, filtering only the output from |
|
1117 | Since this marker is always the same, filtering only the output from | |
1117 | a log is very easy, using for example a simple awk call: |
|
1118 | a log is very easy, using for example a simple awk call: | |
1118 |
|
1119 | |||
1119 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1120 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1120 |
|
1121 | |||
1121 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1122 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1122 | input, so that user lines are logged in their final form, converted |
|
1123 | input, so that user lines are logged in their final form, converted | |
1123 | into valid Python. For example, %Exit is logged as |
|
1124 | into valid Python. For example, %Exit is logged as | |
1124 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1125 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1125 | exactly as typed, with no transformations applied. |
|
1126 | exactly as typed, with no transformations applied. | |
1126 |
|
1127 | |||
1127 | -t: put timestamps before each input line logged (these are put in |
|
1128 | -t: put timestamps before each input line logged (these are put in | |
1128 | comments).""" |
|
1129 | comments).""" | |
1129 |
|
1130 | |||
1130 | opts,par = self.parse_options(parameter_s,'ort') |
|
1131 | opts,par = self.parse_options(parameter_s,'ort') | |
1131 | log_output = 'o' in opts |
|
1132 | log_output = 'o' in opts | |
1132 | log_raw_input = 'r' in opts |
|
1133 | log_raw_input = 'r' in opts | |
1133 | timestamp = 't' in opts |
|
1134 | timestamp = 't' in opts | |
1134 |
|
1135 | |||
1135 | rc = self.shell.rc |
|
|||
1136 | logger = self.shell.logger |
|
1136 | logger = self.shell.logger | |
1137 |
|
1137 | |||
1138 | # if no args are given, the defaults set in the logger constructor by |
|
1138 | # if no args are given, the defaults set in the logger constructor by | |
1139 | # ipytohn remain valid |
|
1139 | # ipytohn remain valid | |
1140 | if par: |
|
1140 | if par: | |
1141 | try: |
|
1141 | try: | |
1142 | logfname,logmode = par.split() |
|
1142 | logfname,logmode = par.split() | |
1143 | except: |
|
1143 | except: | |
1144 | logfname = par |
|
1144 | logfname = par | |
1145 | logmode = 'backup' |
|
1145 | logmode = 'backup' | |
1146 | else: |
|
1146 | else: | |
1147 | logfname = logger.logfname |
|
1147 | logfname = logger.logfname | |
1148 | logmode = logger.logmode |
|
1148 | logmode = logger.logmode | |
1149 | # put logfname into rc struct as if it had been called on the command |
|
1149 | # put logfname into rc struct as if it had been called on the command | |
1150 | # line, so it ends up saved in the log header Save it in case we need |
|
1150 | # line, so it ends up saved in the log header Save it in case we need | |
1151 | # to restore it... |
|
1151 | # to restore it... | |
1152 |
old_logfile = |
|
1152 | old_logfile = self.shell.logfile | |
1153 | if logfname: |
|
1153 | if logfname: | |
1154 | logfname = os.path.expanduser(logfname) |
|
1154 | logfname = os.path.expanduser(logfname) | |
1155 |
|
|
1155 | self.shell.logfile = logfname | |
1156 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
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 | try: |
|
1160 | try: | |
1158 | started = logger.logstart(logfname,loghead,logmode, |
|
1161 | started = logger.logstart(logfname,loghead,logmode, | |
1159 | log_output,timestamp,log_raw_input) |
|
1162 | log_output,timestamp,log_raw_input) | |
1160 | except: |
|
1163 | except: | |
1161 | rc.opts.logfile = old_logfile |
|
1164 | rc.opts.logfile = old_logfile | |
1162 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1165 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1163 | else: |
|
1166 | else: | |
1164 | # log input history up to this point, optionally interleaving |
|
1167 | # log input history up to this point, optionally interleaving | |
1165 | # output if requested |
|
1168 | # output if requested | |
1166 |
|
1169 | |||
1167 | if timestamp: |
|
1170 | if timestamp: | |
1168 | # disable timestamping for the previous history, since we've |
|
1171 | # disable timestamping for the previous history, since we've | |
1169 | # lost those already (no time machine here). |
|
1172 | # lost those already (no time machine here). | |
1170 | logger.timestamp = False |
|
1173 | logger.timestamp = False | |
1171 |
|
1174 | |||
1172 | if log_raw_input: |
|
1175 | if log_raw_input: | |
1173 | input_hist = self.shell.input_hist_raw |
|
1176 | input_hist = self.shell.input_hist_raw | |
1174 | else: |
|
1177 | else: | |
1175 | input_hist = self.shell.input_hist |
|
1178 | input_hist = self.shell.input_hist | |
1176 |
|
1179 | |||
1177 | if log_output: |
|
1180 | if log_output: | |
1178 | log_write = logger.log_write |
|
1181 | log_write = logger.log_write | |
1179 | output_hist = self.shell.output_hist |
|
1182 | output_hist = self.shell.output_hist | |
1180 | for n in range(1,len(input_hist)-1): |
|
1183 | for n in range(1,len(input_hist)-1): | |
1181 | log_write(input_hist[n].rstrip()) |
|
1184 | log_write(input_hist[n].rstrip()) | |
1182 | if n in output_hist: |
|
1185 | if n in output_hist: | |
1183 | log_write(repr(output_hist[n]),'output') |
|
1186 | log_write(repr(output_hist[n]),'output') | |
1184 | else: |
|
1187 | else: | |
1185 | logger.log_write(input_hist[1:]) |
|
1188 | logger.log_write(input_hist[1:]) | |
1186 | if timestamp: |
|
1189 | if timestamp: | |
1187 | # re-enable timestamping |
|
1190 | # re-enable timestamping | |
1188 | logger.timestamp = True |
|
1191 | logger.timestamp = True | |
1189 |
|
1192 | |||
1190 | print ('Activating auto-logging. ' |
|
1193 | print ('Activating auto-logging. ' | |
1191 | 'Current session state plus future input saved.') |
|
1194 | 'Current session state plus future input saved.') | |
1192 | logger.logstate() |
|
1195 | logger.logstate() | |
1193 |
|
1196 | |||
1194 | def magic_logstop(self,parameter_s=''): |
|
1197 | def magic_logstop(self,parameter_s=''): | |
1195 | """Fully stop logging and close log file. |
|
1198 | """Fully stop logging and close log file. | |
1196 |
|
1199 | |||
1197 | In order to start logging again, a new %logstart call needs to be made, |
|
1200 | In order to start logging again, a new %logstart call needs to be made, | |
1198 | possibly (though not necessarily) with a new filename, mode and other |
|
1201 | possibly (though not necessarily) with a new filename, mode and other | |
1199 | options.""" |
|
1202 | options.""" | |
1200 | self.logger.logstop() |
|
1203 | self.logger.logstop() | |
1201 |
|
1204 | |||
1202 | def magic_logoff(self,parameter_s=''): |
|
1205 | def magic_logoff(self,parameter_s=''): | |
1203 | """Temporarily stop logging. |
|
1206 | """Temporarily stop logging. | |
1204 |
|
1207 | |||
1205 | You must have previously started logging.""" |
|
1208 | You must have previously started logging.""" | |
1206 | self.shell.logger.switch_log(0) |
|
1209 | self.shell.logger.switch_log(0) | |
1207 |
|
1210 | |||
1208 | def magic_logon(self,parameter_s=''): |
|
1211 | def magic_logon(self,parameter_s=''): | |
1209 | """Restart logging. |
|
1212 | """Restart logging. | |
1210 |
|
1213 | |||
1211 | This function is for restarting logging which you've temporarily |
|
1214 | This function is for restarting logging which you've temporarily | |
1212 | stopped with %logoff. For starting logging for the first time, you |
|
1215 | stopped with %logoff. For starting logging for the first time, you | |
1213 | must use the %logstart function, which allows you to specify an |
|
1216 | must use the %logstart function, which allows you to specify an | |
1214 | optional log filename.""" |
|
1217 | optional log filename.""" | |
1215 |
|
1218 | |||
1216 | self.shell.logger.switch_log(1) |
|
1219 | self.shell.logger.switch_log(1) | |
1217 |
|
1220 | |||
1218 | def magic_logstate(self,parameter_s=''): |
|
1221 | def magic_logstate(self,parameter_s=''): | |
1219 | """Print the status of the logging system.""" |
|
1222 | """Print the status of the logging system.""" | |
1220 |
|
1223 | |||
1221 | self.shell.logger.logstate() |
|
1224 | self.shell.logger.logstate() | |
1222 |
|
1225 | |||
1223 | def magic_pdb(self, parameter_s=''): |
|
1226 | def magic_pdb(self, parameter_s=''): | |
1224 | """Control the automatic calling of the pdb interactive debugger. |
|
1227 | """Control the automatic calling of the pdb interactive debugger. | |
1225 |
|
1228 | |||
1226 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1229 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1227 | argument it works as a toggle. |
|
1230 | argument it works as a toggle. | |
1228 |
|
1231 | |||
1229 | When an exception is triggered, IPython can optionally call the |
|
1232 | When an exception is triggered, IPython can optionally call the | |
1230 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1233 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1231 | this feature on and off. |
|
1234 | this feature on and off. | |
1232 |
|
1235 | |||
1233 | The initial state of this feature is set in your ipythonrc |
|
1236 | The initial state of this feature is set in your ipythonrc | |
1234 | configuration file (the variable is called 'pdb'). |
|
1237 | configuration file (the variable is called 'pdb'). | |
1235 |
|
1238 | |||
1236 | If you want to just activate the debugger AFTER an exception has fired, |
|
1239 | If you want to just activate the debugger AFTER an exception has fired, | |
1237 | without having to type '%pdb on' and rerunning your code, you can use |
|
1240 | without having to type '%pdb on' and rerunning your code, you can use | |
1238 | the %debug magic.""" |
|
1241 | the %debug magic.""" | |
1239 |
|
1242 | |||
1240 | par = parameter_s.strip().lower() |
|
1243 | par = parameter_s.strip().lower() | |
1241 |
|
1244 | |||
1242 | if par: |
|
1245 | if par: | |
1243 | try: |
|
1246 | try: | |
1244 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1247 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1245 | except KeyError: |
|
1248 | except KeyError: | |
1246 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1249 | print ('Incorrect argument. Use on/1, off/0, ' | |
1247 | 'or nothing for a toggle.') |
|
1250 | 'or nothing for a toggle.') | |
1248 | return |
|
1251 | return | |
1249 | else: |
|
1252 | else: | |
1250 | # toggle |
|
1253 | # toggle | |
1251 | new_pdb = not self.shell.call_pdb |
|
1254 | new_pdb = not self.shell.call_pdb | |
1252 |
|
1255 | |||
1253 | # set on the shell |
|
1256 | # set on the shell | |
1254 | self.shell.call_pdb = new_pdb |
|
1257 | self.shell.call_pdb = new_pdb | |
1255 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1258 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1256 |
|
1259 | |||
1257 | def magic_debug(self, parameter_s=''): |
|
1260 | def magic_debug(self, parameter_s=''): | |
1258 | """Activate the interactive debugger in post-mortem mode. |
|
1261 | """Activate the interactive debugger in post-mortem mode. | |
1259 |
|
1262 | |||
1260 | If an exception has just occurred, this lets you inspect its stack |
|
1263 | If an exception has just occurred, this lets you inspect its stack | |
1261 | frames interactively. Note that this will always work only on the last |
|
1264 | frames interactively. Note that this will always work only on the last | |
1262 | traceback that occurred, so you must call this quickly after an |
|
1265 | traceback that occurred, so you must call this quickly after an | |
1263 | exception that you wish to inspect has fired, because if another one |
|
1266 | exception that you wish to inspect has fired, because if another one | |
1264 | occurs, it clobbers the previous one. |
|
1267 | occurs, it clobbers the previous one. | |
1265 |
|
1268 | |||
1266 | If you want IPython to automatically do this on every exception, see |
|
1269 | If you want IPython to automatically do this on every exception, see | |
1267 | the %pdb magic for more details. |
|
1270 | the %pdb magic for more details. | |
1268 | """ |
|
1271 | """ | |
1269 |
|
1272 | |||
1270 | self.shell.debugger(force=True) |
|
1273 | self.shell.debugger(force=True) | |
1271 |
|
1274 | |||
1272 | @testdec.skip_doctest |
|
1275 | @testdec.skip_doctest | |
1273 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1276 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1274 | opts=None,arg_lst=None,prog_ns=None): |
|
1277 | opts=None,arg_lst=None,prog_ns=None): | |
1275 |
|
1278 | |||
1276 | """Run a statement through the python code profiler. |
|
1279 | """Run a statement through the python code profiler. | |
1277 |
|
1280 | |||
1278 | Usage: |
|
1281 | Usage: | |
1279 | %prun [options] statement |
|
1282 | %prun [options] statement | |
1280 |
|
1283 | |||
1281 | The given statement (which doesn't require quote marks) is run via the |
|
1284 | The given statement (which doesn't require quote marks) is run via the | |
1282 | python profiler in a manner similar to the profile.run() function. |
|
1285 | python profiler in a manner similar to the profile.run() function. | |
1283 | Namespaces are internally managed to work correctly; profile.run |
|
1286 | Namespaces are internally managed to work correctly; profile.run | |
1284 | cannot be used in IPython because it makes certain assumptions about |
|
1287 | cannot be used in IPython because it makes certain assumptions about | |
1285 | namespaces which do not hold under IPython. |
|
1288 | namespaces which do not hold under IPython. | |
1286 |
|
1289 | |||
1287 | Options: |
|
1290 | Options: | |
1288 |
|
1291 | |||
1289 | -l <limit>: you can place restrictions on what or how much of the |
|
1292 | -l <limit>: you can place restrictions on what or how much of the | |
1290 | profile gets printed. The limit value can be: |
|
1293 | profile gets printed. The limit value can be: | |
1291 |
|
1294 | |||
1292 | * A string: only information for function names containing this string |
|
1295 | * A string: only information for function names containing this string | |
1293 | is printed. |
|
1296 | is printed. | |
1294 |
|
1297 | |||
1295 | * An integer: only these many lines are printed. |
|
1298 | * An integer: only these many lines are printed. | |
1296 |
|
1299 | |||
1297 | * A float (between 0 and 1): this fraction of the report is printed |
|
1300 | * A float (between 0 and 1): this fraction of the report is printed | |
1298 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1301 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1299 |
|
1302 | |||
1300 | You can combine several limits with repeated use of the option. For |
|
1303 | You can combine several limits with repeated use of the option. For | |
1301 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1304 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1302 | information about class constructors. |
|
1305 | information about class constructors. | |
1303 |
|
1306 | |||
1304 | -r: return the pstats.Stats object generated by the profiling. This |
|
1307 | -r: return the pstats.Stats object generated by the profiling. This | |
1305 | object has all the information about the profile in it, and you can |
|
1308 | object has all the information about the profile in it, and you can | |
1306 | later use it for further analysis or in other functions. |
|
1309 | later use it for further analysis or in other functions. | |
1307 |
|
1310 | |||
1308 | -s <key>: sort profile by given key. You can provide more than one key |
|
1311 | -s <key>: sort profile by given key. You can provide more than one key | |
1309 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1312 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1310 | default sorting key is 'time'. |
|
1313 | default sorting key is 'time'. | |
1311 |
|
1314 | |||
1312 | The following is copied verbatim from the profile documentation |
|
1315 | The following is copied verbatim from the profile documentation | |
1313 | referenced below: |
|
1316 | referenced below: | |
1314 |
|
1317 | |||
1315 | When more than one key is provided, additional keys are used as |
|
1318 | When more than one key is provided, additional keys are used as | |
1316 | secondary criteria when the there is equality in all keys selected |
|
1319 | secondary criteria when the there is equality in all keys selected | |
1317 | before them. |
|
1320 | before them. | |
1318 |
|
1321 | |||
1319 | Abbreviations can be used for any key names, as long as the |
|
1322 | Abbreviations can be used for any key names, as long as the | |
1320 | abbreviation is unambiguous. The following are the keys currently |
|
1323 | abbreviation is unambiguous. The following are the keys currently | |
1321 | defined: |
|
1324 | defined: | |
1322 |
|
1325 | |||
1323 | Valid Arg Meaning |
|
1326 | Valid Arg Meaning | |
1324 | "calls" call count |
|
1327 | "calls" call count | |
1325 | "cumulative" cumulative time |
|
1328 | "cumulative" cumulative time | |
1326 | "file" file name |
|
1329 | "file" file name | |
1327 | "module" file name |
|
1330 | "module" file name | |
1328 | "pcalls" primitive call count |
|
1331 | "pcalls" primitive call count | |
1329 | "line" line number |
|
1332 | "line" line number | |
1330 | "name" function name |
|
1333 | "name" function name | |
1331 | "nfl" name/file/line |
|
1334 | "nfl" name/file/line | |
1332 | "stdname" standard name |
|
1335 | "stdname" standard name | |
1333 | "time" internal time |
|
1336 | "time" internal time | |
1334 |
|
1337 | |||
1335 | Note that all sorts on statistics are in descending order (placing |
|
1338 | Note that all sorts on statistics are in descending order (placing | |
1336 | most time consuming items first), where as name, file, and line number |
|
1339 | most time consuming items first), where as name, file, and line number | |
1337 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1340 | searches are in ascending order (i.e., alphabetical). The subtle | |
1338 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1341 | distinction between "nfl" and "stdname" is that the standard name is a | |
1339 | sort of the name as printed, which means that the embedded line |
|
1342 | sort of the name as printed, which means that the embedded line | |
1340 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1343 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1341 | would (if the file names were the same) appear in the string order |
|
1344 | would (if the file names were the same) appear in the string order | |
1342 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1345 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1343 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1346 | line numbers. In fact, sort_stats("nfl") is the same as | |
1344 | sort_stats("name", "file", "line"). |
|
1347 | sort_stats("name", "file", "line"). | |
1345 |
|
1348 | |||
1346 | -T <filename>: save profile results as shown on screen to a text |
|
1349 | -T <filename>: save profile results as shown on screen to a text | |
1347 | file. The profile is still shown on screen. |
|
1350 | file. The profile is still shown on screen. | |
1348 |
|
1351 | |||
1349 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1352 | -D <filename>: save (via dump_stats) profile statistics to given | |
1350 | filename. This data is in a format understod by the pstats module, and |
|
1353 | filename. This data is in a format understod by the pstats module, and | |
1351 | is generated by a call to the dump_stats() method of profile |
|
1354 | is generated by a call to the dump_stats() method of profile | |
1352 | objects. The profile is still shown on screen. |
|
1355 | objects. The profile is still shown on screen. | |
1353 |
|
1356 | |||
1354 | If you want to run complete programs under the profiler's control, use |
|
1357 | If you want to run complete programs under the profiler's control, use | |
1355 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1358 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1356 | contains profiler specific options as described here. |
|
1359 | contains profiler specific options as described here. | |
1357 |
|
1360 | |||
1358 | You can read the complete documentation for the profile module with:: |
|
1361 | You can read the complete documentation for the profile module with:: | |
1359 |
|
1362 | |||
1360 | In [1]: import profile; profile.help() |
|
1363 | In [1]: import profile; profile.help() | |
1361 | """ |
|
1364 | """ | |
1362 |
|
1365 | |||
1363 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1366 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1364 | # protect user quote marks |
|
1367 | # protect user quote marks | |
1365 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1368 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1366 |
|
1369 | |||
1367 | if user_mode: # regular user call |
|
1370 | if user_mode: # regular user call | |
1368 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1371 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1369 | list_all=1) |
|
1372 | list_all=1) | |
1370 | namespace = self.shell.user_ns |
|
1373 | namespace = self.shell.user_ns | |
1371 | else: # called to run a program by %run -p |
|
1374 | else: # called to run a program by %run -p | |
1372 | try: |
|
1375 | try: | |
1373 | filename = get_py_filename(arg_lst[0]) |
|
1376 | filename = get_py_filename(arg_lst[0]) | |
1374 | except IOError,msg: |
|
1377 | except IOError,msg: | |
1375 | error(msg) |
|
1378 | error(msg) | |
1376 | return |
|
1379 | return | |
1377 |
|
1380 | |||
1378 | arg_str = 'execfile(filename,prog_ns)' |
|
1381 | arg_str = 'execfile(filename,prog_ns)' | |
1379 | namespace = locals() |
|
1382 | namespace = locals() | |
1380 |
|
1383 | |||
1381 | opts.merge(opts_def) |
|
1384 | opts.merge(opts_def) | |
1382 |
|
1385 | |||
1383 | prof = profile.Profile() |
|
1386 | prof = profile.Profile() | |
1384 | try: |
|
1387 | try: | |
1385 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1388 | prof = prof.runctx(arg_str,namespace,namespace) | |
1386 | sys_exit = '' |
|
1389 | sys_exit = '' | |
1387 | except SystemExit: |
|
1390 | except SystemExit: | |
1388 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1391 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1389 |
|
1392 | |||
1390 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1393 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1391 |
|
1394 | |||
1392 | lims = opts.l |
|
1395 | lims = opts.l | |
1393 | if lims: |
|
1396 | if lims: | |
1394 | lims = [] # rebuild lims with ints/floats/strings |
|
1397 | lims = [] # rebuild lims with ints/floats/strings | |
1395 | for lim in opts.l: |
|
1398 | for lim in opts.l: | |
1396 | try: |
|
1399 | try: | |
1397 | lims.append(int(lim)) |
|
1400 | lims.append(int(lim)) | |
1398 | except ValueError: |
|
1401 | except ValueError: | |
1399 | try: |
|
1402 | try: | |
1400 | lims.append(float(lim)) |
|
1403 | lims.append(float(lim)) | |
1401 | except ValueError: |
|
1404 | except ValueError: | |
1402 | lims.append(lim) |
|
1405 | lims.append(lim) | |
1403 |
|
1406 | |||
1404 | # Trap output. |
|
1407 | # Trap output. | |
1405 | stdout_trap = StringIO() |
|
1408 | stdout_trap = StringIO() | |
1406 |
|
1409 | |||
1407 | if hasattr(stats,'stream'): |
|
1410 | if hasattr(stats,'stream'): | |
1408 | # In newer versions of python, the stats object has a 'stream' |
|
1411 | # In newer versions of python, the stats object has a 'stream' | |
1409 | # attribute to write into. |
|
1412 | # attribute to write into. | |
1410 | stats.stream = stdout_trap |
|
1413 | stats.stream = stdout_trap | |
1411 | stats.print_stats(*lims) |
|
1414 | stats.print_stats(*lims) | |
1412 | else: |
|
1415 | else: | |
1413 | # For older versions, we manually redirect stdout during printing |
|
1416 | # For older versions, we manually redirect stdout during printing | |
1414 | sys_stdout = sys.stdout |
|
1417 | sys_stdout = sys.stdout | |
1415 | try: |
|
1418 | try: | |
1416 | sys.stdout = stdout_trap |
|
1419 | sys.stdout = stdout_trap | |
1417 | stats.print_stats(*lims) |
|
1420 | stats.print_stats(*lims) | |
1418 | finally: |
|
1421 | finally: | |
1419 | sys.stdout = sys_stdout |
|
1422 | sys.stdout = sys_stdout | |
1420 |
|
1423 | |||
1421 | output = stdout_trap.getvalue() |
|
1424 | output = stdout_trap.getvalue() | |
1422 | output = output.rstrip() |
|
1425 | output = output.rstrip() | |
1423 |
|
1426 | |||
1424 |
page(output,screen_lines=self.shell. |
|
1427 | page(output,screen_lines=self.shell.usable_screen_length) | |
1425 | print sys_exit, |
|
1428 | print sys_exit, | |
1426 |
|
1429 | |||
1427 | dump_file = opts.D[0] |
|
1430 | dump_file = opts.D[0] | |
1428 | text_file = opts.T[0] |
|
1431 | text_file = opts.T[0] | |
1429 | if dump_file: |
|
1432 | if dump_file: | |
1430 | prof.dump_stats(dump_file) |
|
1433 | prof.dump_stats(dump_file) | |
1431 | print '\n*** Profile stats marshalled to file',\ |
|
1434 | print '\n*** Profile stats marshalled to file',\ | |
1432 | `dump_file`+'.',sys_exit |
|
1435 | `dump_file`+'.',sys_exit | |
1433 | if text_file: |
|
1436 | if text_file: | |
1434 | pfile = file(text_file,'w') |
|
1437 | pfile = file(text_file,'w') | |
1435 | pfile.write(output) |
|
1438 | pfile.write(output) | |
1436 | pfile.close() |
|
1439 | pfile.close() | |
1437 | print '\n*** Profile printout saved to text file',\ |
|
1440 | print '\n*** Profile printout saved to text file',\ | |
1438 | `text_file`+'.',sys_exit |
|
1441 | `text_file`+'.',sys_exit | |
1439 |
|
1442 | |||
1440 | if opts.has_key('r'): |
|
1443 | if opts.has_key('r'): | |
1441 | return stats |
|
1444 | return stats | |
1442 | else: |
|
1445 | else: | |
1443 | return None |
|
1446 | return None | |
1444 |
|
1447 | |||
1445 | @testdec.skip_doctest |
|
1448 | @testdec.skip_doctest | |
1446 | def magic_run(self, parameter_s ='',runner=None, |
|
1449 | def magic_run(self, parameter_s ='',runner=None, | |
1447 | file_finder=get_py_filename): |
|
1450 | file_finder=get_py_filename): | |
1448 | """Run the named file inside IPython as a program. |
|
1451 | """Run the named file inside IPython as a program. | |
1449 |
|
1452 | |||
1450 | Usage:\\ |
|
1453 | Usage:\\ | |
1451 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1454 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1452 |
|
1455 | |||
1453 | Parameters after the filename are passed as command-line arguments to |
|
1456 | Parameters after the filename are passed as command-line arguments to | |
1454 | the program (put in sys.argv). Then, control returns to IPython's |
|
1457 | the program (put in sys.argv). Then, control returns to IPython's | |
1455 | prompt. |
|
1458 | prompt. | |
1456 |
|
1459 | |||
1457 | This is similar to running at a system prompt:\\ |
|
1460 | This is similar to running at a system prompt:\\ | |
1458 | $ python file args\\ |
|
1461 | $ python file args\\ | |
1459 | but with the advantage of giving you IPython's tracebacks, and of |
|
1462 | but with the advantage of giving you IPython's tracebacks, and of | |
1460 | loading all variables into your interactive namespace for further use |
|
1463 | loading all variables into your interactive namespace for further use | |
1461 | (unless -p is used, see below). |
|
1464 | (unless -p is used, see below). | |
1462 |
|
1465 | |||
1463 | The file is executed in a namespace initially consisting only of |
|
1466 | The file is executed in a namespace initially consisting only of | |
1464 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1467 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1465 | sees its environment as if it were being run as a stand-alone program |
|
1468 | sees its environment as if it were being run as a stand-alone program | |
1466 | (except for sharing global objects such as previously imported |
|
1469 | (except for sharing global objects such as previously imported | |
1467 | modules). But after execution, the IPython interactive namespace gets |
|
1470 | modules). But after execution, the IPython interactive namespace gets | |
1468 | updated with all variables defined in the program (except for __name__ |
|
1471 | updated with all variables defined in the program (except for __name__ | |
1469 | and sys.argv). This allows for very convenient loading of code for |
|
1472 | and sys.argv). This allows for very convenient loading of code for | |
1470 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1473 | interactive work, while giving each program a 'clean sheet' to run in. | |
1471 |
|
1474 | |||
1472 | Options: |
|
1475 | Options: | |
1473 |
|
1476 | |||
1474 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1477 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1475 | without extension (as python does under import). This allows running |
|
1478 | without extension (as python does under import). This allows running | |
1476 | scripts and reloading the definitions in them without calling code |
|
1479 | scripts and reloading the definitions in them without calling code | |
1477 | protected by an ' if __name__ == "__main__" ' clause. |
|
1480 | protected by an ' if __name__ == "__main__" ' clause. | |
1478 |
|
1481 | |||
1479 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1482 | -i: run the file in IPython's namespace instead of an empty one. This | |
1480 | is useful if you are experimenting with code written in a text editor |
|
1483 | is useful if you are experimenting with code written in a text editor | |
1481 | which depends on variables defined interactively. |
|
1484 | which depends on variables defined interactively. | |
1482 |
|
1485 | |||
1483 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1486 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1484 | being run. This is particularly useful if IPython is being used to |
|
1487 | being run. This is particularly useful if IPython is being used to | |
1485 | run unittests, which always exit with a sys.exit() call. In such |
|
1488 | run unittests, which always exit with a sys.exit() call. In such | |
1486 | cases you are interested in the output of the test results, not in |
|
1489 | cases you are interested in the output of the test results, not in | |
1487 | seeing a traceback of the unittest module. |
|
1490 | seeing a traceback of the unittest module. | |
1488 |
|
1491 | |||
1489 | -t: print timing information at the end of the run. IPython will give |
|
1492 | -t: print timing information at the end of the run. IPython will give | |
1490 | you an estimated CPU time consumption for your script, which under |
|
1493 | you an estimated CPU time consumption for your script, which under | |
1491 | Unix uses the resource module to avoid the wraparound problems of |
|
1494 | Unix uses the resource module to avoid the wraparound problems of | |
1492 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1495 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1493 | is also given (for Windows platforms this is reported as 0.0). |
|
1496 | is also given (for Windows platforms this is reported as 0.0). | |
1494 |
|
1497 | |||
1495 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1498 | If -t is given, an additional -N<N> option can be given, where <N> | |
1496 | must be an integer indicating how many times you want the script to |
|
1499 | must be an integer indicating how many times you want the script to | |
1497 | run. The final timing report will include total and per run results. |
|
1500 | run. The final timing report will include total and per run results. | |
1498 |
|
1501 | |||
1499 | For example (testing the script uniq_stable.py): |
|
1502 | For example (testing the script uniq_stable.py): | |
1500 |
|
1503 | |||
1501 | In [1]: run -t uniq_stable |
|
1504 | In [1]: run -t uniq_stable | |
1502 |
|
1505 | |||
1503 | IPython CPU timings (estimated):\\ |
|
1506 | IPython CPU timings (estimated):\\ | |
1504 | User : 0.19597 s.\\ |
|
1507 | User : 0.19597 s.\\ | |
1505 | System: 0.0 s.\\ |
|
1508 | System: 0.0 s.\\ | |
1506 |
|
1509 | |||
1507 | In [2]: run -t -N5 uniq_stable |
|
1510 | In [2]: run -t -N5 uniq_stable | |
1508 |
|
1511 | |||
1509 | IPython CPU timings (estimated):\\ |
|
1512 | IPython CPU timings (estimated):\\ | |
1510 | Total runs performed: 5\\ |
|
1513 | Total runs performed: 5\\ | |
1511 | Times : Total Per run\\ |
|
1514 | Times : Total Per run\\ | |
1512 | User : 0.910862 s, 0.1821724 s.\\ |
|
1515 | User : 0.910862 s, 0.1821724 s.\\ | |
1513 | System: 0.0 s, 0.0 s. |
|
1516 | System: 0.0 s, 0.0 s. | |
1514 |
|
1517 | |||
1515 | -d: run your program under the control of pdb, the Python debugger. |
|
1518 | -d: run your program under the control of pdb, the Python debugger. | |
1516 | This allows you to execute your program step by step, watch variables, |
|
1519 | This allows you to execute your program step by step, watch variables, | |
1517 | etc. Internally, what IPython does is similar to calling: |
|
1520 | etc. Internally, what IPython does is similar to calling: | |
1518 |
|
1521 | |||
1519 | pdb.run('execfile("YOURFILENAME")') |
|
1522 | pdb.run('execfile("YOURFILENAME")') | |
1520 |
|
1523 | |||
1521 | with a breakpoint set on line 1 of your file. You can change the line |
|
1524 | with a breakpoint set on line 1 of your file. You can change the line | |
1522 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1525 | number for this automatic breakpoint to be <N> by using the -bN option | |
1523 | (where N must be an integer). For example: |
|
1526 | (where N must be an integer). For example: | |
1524 |
|
1527 | |||
1525 | %run -d -b40 myscript |
|
1528 | %run -d -b40 myscript | |
1526 |
|
1529 | |||
1527 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1530 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1528 | the first breakpoint must be set on a line which actually does |
|
1531 | the first breakpoint must be set on a line which actually does | |
1529 | something (not a comment or docstring) for it to stop execution. |
|
1532 | something (not a comment or docstring) for it to stop execution. | |
1530 |
|
1533 | |||
1531 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1534 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1532 | first enter 'c' (without qoutes) to start execution up to the first |
|
1535 | first enter 'c' (without qoutes) to start execution up to the first | |
1533 | breakpoint. |
|
1536 | breakpoint. | |
1534 |
|
1537 | |||
1535 | Entering 'help' gives information about the use of the debugger. You |
|
1538 | Entering 'help' gives information about the use of the debugger. You | |
1536 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1539 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1537 | at a prompt. |
|
1540 | at a prompt. | |
1538 |
|
1541 | |||
1539 | -p: run program under the control of the Python profiler module (which |
|
1542 | -p: run program under the control of the Python profiler module (which | |
1540 | prints a detailed report of execution times, function calls, etc). |
|
1543 | prints a detailed report of execution times, function calls, etc). | |
1541 |
|
1544 | |||
1542 | You can pass other options after -p which affect the behavior of the |
|
1545 | You can pass other options after -p which affect the behavior of the | |
1543 | profiler itself. See the docs for %prun for details. |
|
1546 | profiler itself. See the docs for %prun for details. | |
1544 |
|
1547 | |||
1545 | In this mode, the program's variables do NOT propagate back to the |
|
1548 | In this mode, the program's variables do NOT propagate back to the | |
1546 | IPython interactive namespace (because they remain in the namespace |
|
1549 | IPython interactive namespace (because they remain in the namespace | |
1547 | where the profiler executes them). |
|
1550 | where the profiler executes them). | |
1548 |
|
1551 | |||
1549 | Internally this triggers a call to %prun, see its documentation for |
|
1552 | Internally this triggers a call to %prun, see its documentation for | |
1550 | details on the options available specifically for profiling. |
|
1553 | details on the options available specifically for profiling. | |
1551 |
|
1554 | |||
1552 | There is one special usage for which the text above doesn't apply: |
|
1555 | There is one special usage for which the text above doesn't apply: | |
1553 | if the filename ends with .ipy, the file is run as ipython script, |
|
1556 | if the filename ends with .ipy, the file is run as ipython script, | |
1554 | just as if the commands were written on IPython prompt. |
|
1557 | just as if the commands were written on IPython prompt. | |
1555 | """ |
|
1558 | """ | |
1556 |
|
1559 | |||
1557 | # get arguments and set sys.argv for program to be run. |
|
1560 | # get arguments and set sys.argv for program to be run. | |
1558 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1561 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1559 | mode='list',list_all=1) |
|
1562 | mode='list',list_all=1) | |
1560 |
|
1563 | |||
1561 | try: |
|
1564 | try: | |
1562 | filename = file_finder(arg_lst[0]) |
|
1565 | filename = file_finder(arg_lst[0]) | |
1563 | except IndexError: |
|
1566 | except IndexError: | |
1564 | warn('you must provide at least a filename.') |
|
1567 | warn('you must provide at least a filename.') | |
1565 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1568 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1566 | return |
|
1569 | return | |
1567 | except IOError,msg: |
|
1570 | except IOError,msg: | |
1568 | error(msg) |
|
1571 | error(msg) | |
1569 | return |
|
1572 | return | |
1570 |
|
1573 | |||
1571 | if filename.lower().endswith('.ipy'): |
|
1574 | if filename.lower().endswith('.ipy'): | |
1572 |
self |
|
1575 | self.runlines(open(filename).read(), clean=True) | |
1573 | return |
|
1576 | return | |
1574 |
|
1577 | |||
1575 | # Control the response to exit() calls made by the script being run |
|
1578 | # Control the response to exit() calls made by the script being run | |
1576 | exit_ignore = opts.has_key('e') |
|
1579 | exit_ignore = opts.has_key('e') | |
1577 |
|
1580 | |||
1578 | # Make sure that the running script gets a proper sys.argv as if it |
|
1581 | # Make sure that the running script gets a proper sys.argv as if it | |
1579 | # were run from a system shell. |
|
1582 | # were run from a system shell. | |
1580 | save_argv = sys.argv # save it for later restoring |
|
1583 | save_argv = sys.argv # save it for later restoring | |
1581 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1584 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1582 |
|
1585 | |||
1583 | if opts.has_key('i'): |
|
1586 | if opts.has_key('i'): | |
1584 | # Run in user's interactive namespace |
|
1587 | # Run in user's interactive namespace | |
1585 | prog_ns = self.shell.user_ns |
|
1588 | prog_ns = self.shell.user_ns | |
1586 | __name__save = self.shell.user_ns['__name__'] |
|
1589 | __name__save = self.shell.user_ns['__name__'] | |
1587 | prog_ns['__name__'] = '__main__' |
|
1590 | prog_ns['__name__'] = '__main__' | |
1588 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1591 | main_mod = self.shell.new_main_mod(prog_ns) | |
1589 | else: |
|
1592 | else: | |
1590 | # Run in a fresh, empty namespace |
|
1593 | # Run in a fresh, empty namespace | |
1591 | if opts.has_key('n'): |
|
1594 | if opts.has_key('n'): | |
1592 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1595 | name = os.path.splitext(os.path.basename(filename))[0] | |
1593 | else: |
|
1596 | else: | |
1594 | name = '__main__' |
|
1597 | name = '__main__' | |
1595 |
|
1598 | |||
1596 | main_mod = self.shell.new_main_mod() |
|
1599 | main_mod = self.shell.new_main_mod() | |
1597 | prog_ns = main_mod.__dict__ |
|
1600 | prog_ns = main_mod.__dict__ | |
1598 | prog_ns['__name__'] = name |
|
1601 | prog_ns['__name__'] = name | |
1599 |
|
1602 | |||
1600 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1603 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1601 | # set the __file__ global in the script's namespace |
|
1604 | # set the __file__ global in the script's namespace | |
1602 | prog_ns['__file__'] = filename |
|
1605 | prog_ns['__file__'] = filename | |
1603 |
|
1606 | |||
1604 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1607 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1605 | # that, if we overwrite __main__, we replace it at the end |
|
1608 | # that, if we overwrite __main__, we replace it at the end | |
1606 | main_mod_name = prog_ns['__name__'] |
|
1609 | main_mod_name = prog_ns['__name__'] | |
1607 |
|
1610 | |||
1608 | if main_mod_name == '__main__': |
|
1611 | if main_mod_name == '__main__': | |
1609 | restore_main = sys.modules['__main__'] |
|
1612 | restore_main = sys.modules['__main__'] | |
1610 | else: |
|
1613 | else: | |
1611 | restore_main = False |
|
1614 | restore_main = False | |
1612 |
|
1615 | |||
1613 | # This needs to be undone at the end to prevent holding references to |
|
1616 | # This needs to be undone at the end to prevent holding references to | |
1614 | # every single object ever created. |
|
1617 | # every single object ever created. | |
1615 | sys.modules[main_mod_name] = main_mod |
|
1618 | sys.modules[main_mod_name] = main_mod | |
1616 |
|
1619 | |||
1617 | stats = None |
|
1620 | stats = None | |
1618 | try: |
|
1621 | try: | |
1619 | self.shell.savehist() |
|
1622 | self.shell.savehist() | |
1620 |
|
1623 | |||
1621 | if opts.has_key('p'): |
|
1624 | if opts.has_key('p'): | |
1622 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1625 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1623 | else: |
|
1626 | else: | |
1624 | if opts.has_key('d'): |
|
1627 | if opts.has_key('d'): | |
1625 |
deb = debugger.Pdb(self.shell. |
|
1628 | deb = debugger.Pdb(self.shell.colors) | |
1626 | # reset Breakpoint state, which is moronically kept |
|
1629 | # reset Breakpoint state, which is moronically kept | |
1627 | # in a class |
|
1630 | # in a class | |
1628 | bdb.Breakpoint.next = 1 |
|
1631 | bdb.Breakpoint.next = 1 | |
1629 | bdb.Breakpoint.bplist = {} |
|
1632 | bdb.Breakpoint.bplist = {} | |
1630 | bdb.Breakpoint.bpbynumber = [None] |
|
1633 | bdb.Breakpoint.bpbynumber = [None] | |
1631 | # Set an initial breakpoint to stop execution |
|
1634 | # Set an initial breakpoint to stop execution | |
1632 | maxtries = 10 |
|
1635 | maxtries = 10 | |
1633 | bp = int(opts.get('b',[1])[0]) |
|
1636 | bp = int(opts.get('b',[1])[0]) | |
1634 | checkline = deb.checkline(filename,bp) |
|
1637 | checkline = deb.checkline(filename,bp) | |
1635 | if not checkline: |
|
1638 | if not checkline: | |
1636 | for bp in range(bp+1,bp+maxtries+1): |
|
1639 | for bp in range(bp+1,bp+maxtries+1): | |
1637 | if deb.checkline(filename,bp): |
|
1640 | if deb.checkline(filename,bp): | |
1638 | break |
|
1641 | break | |
1639 | else: |
|
1642 | else: | |
1640 | msg = ("\nI failed to find a valid line to set " |
|
1643 | msg = ("\nI failed to find a valid line to set " | |
1641 | "a breakpoint\n" |
|
1644 | "a breakpoint\n" | |
1642 | "after trying up to line: %s.\n" |
|
1645 | "after trying up to line: %s.\n" | |
1643 | "Please set a valid breakpoint manually " |
|
1646 | "Please set a valid breakpoint manually " | |
1644 | "with the -b option." % bp) |
|
1647 | "with the -b option." % bp) | |
1645 | error(msg) |
|
1648 | error(msg) | |
1646 | return |
|
1649 | return | |
1647 | # if we find a good linenumber, set the breakpoint |
|
1650 | # if we find a good linenumber, set the breakpoint | |
1648 | deb.do_break('%s:%s' % (filename,bp)) |
|
1651 | deb.do_break('%s:%s' % (filename,bp)) | |
1649 | # Start file run |
|
1652 | # Start file run | |
1650 | print "NOTE: Enter 'c' at the", |
|
1653 | print "NOTE: Enter 'c' at the", | |
1651 | print "%s prompt to start your script." % deb.prompt |
|
1654 | print "%s prompt to start your script." % deb.prompt | |
1652 | try: |
|
1655 | try: | |
1653 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1656 | deb.run('execfile("%s")' % filename,prog_ns) | |
1654 |
|
1657 | |||
1655 | except: |
|
1658 | except: | |
1656 | etype, value, tb = sys.exc_info() |
|
1659 | etype, value, tb = sys.exc_info() | |
1657 | # Skip three frames in the traceback: the %run one, |
|
1660 | # Skip three frames in the traceback: the %run one, | |
1658 | # one inside bdb.py, and the command-line typed by the |
|
1661 | # one inside bdb.py, and the command-line typed by the | |
1659 | # user (run by exec in pdb itself). |
|
1662 | # user (run by exec in pdb itself). | |
1660 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1663 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1661 | else: |
|
1664 | else: | |
1662 | if runner is None: |
|
1665 | if runner is None: | |
1663 | runner = self.shell.safe_execfile |
|
1666 | runner = self.shell.safe_execfile | |
1664 | if opts.has_key('t'): |
|
1667 | if opts.has_key('t'): | |
1665 | # timed execution |
|
1668 | # timed execution | |
1666 | try: |
|
1669 | try: | |
1667 | nruns = int(opts['N'][0]) |
|
1670 | nruns = int(opts['N'][0]) | |
1668 | if nruns < 1: |
|
1671 | if nruns < 1: | |
1669 | error('Number of runs must be >=1') |
|
1672 | error('Number of runs must be >=1') | |
1670 | return |
|
1673 | return | |
1671 | except (KeyError): |
|
1674 | except (KeyError): | |
1672 | nruns = 1 |
|
1675 | nruns = 1 | |
1673 | if nruns == 1: |
|
1676 | if nruns == 1: | |
1674 | t0 = clock2() |
|
1677 | t0 = clock2() | |
1675 | runner(filename,prog_ns,prog_ns, |
|
1678 | runner(filename,prog_ns,prog_ns, | |
1676 | exit_ignore=exit_ignore) |
|
1679 | exit_ignore=exit_ignore) | |
1677 | t1 = clock2() |
|
1680 | t1 = clock2() | |
1678 | t_usr = t1[0]-t0[0] |
|
1681 | t_usr = t1[0]-t0[0] | |
1679 | t_sys = t1[1]-t0[1] |
|
1682 | t_sys = t1[1]-t0[1] | |
1680 | print "\nIPython CPU timings (estimated):" |
|
1683 | print "\nIPython CPU timings (estimated):" | |
1681 | print " User : %10s s." % t_usr |
|
1684 | print " User : %10s s." % t_usr | |
1682 | print " System: %10s s." % t_sys |
|
1685 | print " System: %10s s." % t_sys | |
1683 | else: |
|
1686 | else: | |
1684 | runs = range(nruns) |
|
1687 | runs = range(nruns) | |
1685 | t0 = clock2() |
|
1688 | t0 = clock2() | |
1686 | for nr in runs: |
|
1689 | for nr in runs: | |
1687 | runner(filename,prog_ns,prog_ns, |
|
1690 | runner(filename,prog_ns,prog_ns, | |
1688 | exit_ignore=exit_ignore) |
|
1691 | exit_ignore=exit_ignore) | |
1689 | t1 = clock2() |
|
1692 | t1 = clock2() | |
1690 | t_usr = t1[0]-t0[0] |
|
1693 | t_usr = t1[0]-t0[0] | |
1691 | t_sys = t1[1]-t0[1] |
|
1694 | t_sys = t1[1]-t0[1] | |
1692 | print "\nIPython CPU timings (estimated):" |
|
1695 | print "\nIPython CPU timings (estimated):" | |
1693 | print "Total runs performed:",nruns |
|
1696 | print "Total runs performed:",nruns | |
1694 | print " Times : %10s %10s" % ('Total','Per run') |
|
1697 | print " Times : %10s %10s" % ('Total','Per run') | |
1695 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1698 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1696 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1699 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1697 |
|
1700 | |||
1698 | else: |
|
1701 | else: | |
1699 | # regular execution |
|
1702 | # regular execution | |
1700 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1703 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1701 |
|
1704 | |||
1702 | if opts.has_key('i'): |
|
1705 | if opts.has_key('i'): | |
1703 | self.shell.user_ns['__name__'] = __name__save |
|
1706 | self.shell.user_ns['__name__'] = __name__save | |
1704 | else: |
|
1707 | else: | |
1705 | # The shell MUST hold a reference to prog_ns so after %run |
|
1708 | # The shell MUST hold a reference to prog_ns so after %run | |
1706 | # exits, the python deletion mechanism doesn't zero it out |
|
1709 | # exits, the python deletion mechanism doesn't zero it out | |
1707 | # (leaving dangling references). |
|
1710 | # (leaving dangling references). | |
1708 | self.shell.cache_main_mod(prog_ns,filename) |
|
1711 | self.shell.cache_main_mod(prog_ns,filename) | |
1709 | # update IPython interactive namespace |
|
1712 | # update IPython interactive namespace | |
1710 |
|
1713 | |||
1711 | # Some forms of read errors on the file may mean the |
|
1714 | # Some forms of read errors on the file may mean the | |
1712 | # __name__ key was never set; using pop we don't have to |
|
1715 | # __name__ key was never set; using pop we don't have to | |
1713 | # worry about a possible KeyError. |
|
1716 | # worry about a possible KeyError. | |
1714 | prog_ns.pop('__name__', None) |
|
1717 | prog_ns.pop('__name__', None) | |
1715 |
|
1718 | |||
1716 | self.shell.user_ns.update(prog_ns) |
|
1719 | self.shell.user_ns.update(prog_ns) | |
1717 | finally: |
|
1720 | finally: | |
1718 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1721 | # It's a bit of a mystery why, but __builtins__ can change from | |
1719 | # being a module to becoming a dict missing some key data after |
|
1722 | # being a module to becoming a dict missing some key data after | |
1720 | # %run. As best I can see, this is NOT something IPython is doing |
|
1723 | # %run. As best I can see, this is NOT something IPython is doing | |
1721 | # at all, and similar problems have been reported before: |
|
1724 | # at all, and similar problems have been reported before: | |
1722 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1725 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1723 | # Since this seems to be done by the interpreter itself, the best |
|
1726 | # Since this seems to be done by the interpreter itself, the best | |
1724 | # we can do is to at least restore __builtins__ for the user on |
|
1727 | # we can do is to at least restore __builtins__ for the user on | |
1725 | # exit. |
|
1728 | # exit. | |
1726 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1729 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1727 |
|
1730 | |||
1728 | # Ensure key global structures are restored |
|
1731 | # Ensure key global structures are restored | |
1729 | sys.argv = save_argv |
|
1732 | sys.argv = save_argv | |
1730 | if restore_main: |
|
1733 | if restore_main: | |
1731 | sys.modules['__main__'] = restore_main |
|
1734 | sys.modules['__main__'] = restore_main | |
1732 | else: |
|
1735 | else: | |
1733 | # Remove from sys.modules the reference to main_mod we'd |
|
1736 | # Remove from sys.modules the reference to main_mod we'd | |
1734 | # added. Otherwise it will trap references to objects |
|
1737 | # added. Otherwise it will trap references to objects | |
1735 | # contained therein. |
|
1738 | # contained therein. | |
1736 | del sys.modules[main_mod_name] |
|
1739 | del sys.modules[main_mod_name] | |
1737 |
|
1740 | |||
1738 | self.shell.reloadhist() |
|
1741 | self.shell.reloadhist() | |
1739 |
|
1742 | |||
1740 | return stats |
|
1743 | return stats | |
1741 |
|
1744 | |||
1742 | def magic_runlog(self, parameter_s =''): |
|
1745 | def magic_runlog(self, parameter_s =''): | |
1743 | """Run files as logs. |
|
1746 | """Run files as logs. | |
1744 |
|
1747 | |||
1745 | Usage:\\ |
|
1748 | Usage:\\ | |
1746 | %runlog file1 file2 ... |
|
1749 | %runlog file1 file2 ... | |
1747 |
|
1750 | |||
1748 | Run the named files (treating them as log files) in sequence inside |
|
1751 | Run the named files (treating them as log files) in sequence inside | |
1749 | the interpreter, and return to the prompt. This is much slower than |
|
1752 | the interpreter, and return to the prompt. This is much slower than | |
1750 | %run because each line is executed in a try/except block, but it |
|
1753 | %run because each line is executed in a try/except block, but it | |
1751 | allows running files with syntax errors in them. |
|
1754 | allows running files with syntax errors in them. | |
1752 |
|
1755 | |||
1753 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1756 | Normally IPython will guess when a file is one of its own logfiles, so | |
1754 | you can typically use %run even for logs. This shorthand allows you to |
|
1757 | you can typically use %run even for logs. This shorthand allows you to | |
1755 | force any file to be treated as a log file.""" |
|
1758 | force any file to be treated as a log file.""" | |
1756 |
|
1759 | |||
1757 | for f in parameter_s.split(): |
|
1760 | for f in parameter_s.split(): | |
1758 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1761 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1759 | self.shell.user_ns,islog=1) |
|
1762 | self.shell.user_ns,islog=1) | |
1760 |
|
1763 | |||
1761 | @testdec.skip_doctest |
|
1764 | @testdec.skip_doctest | |
1762 | def magic_timeit(self, parameter_s =''): |
|
1765 | def magic_timeit(self, parameter_s =''): | |
1763 | """Time execution of a Python statement or expression |
|
1766 | """Time execution of a Python statement or expression | |
1764 |
|
1767 | |||
1765 | Usage:\\ |
|
1768 | Usage:\\ | |
1766 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1769 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1767 |
|
1770 | |||
1768 | Time execution of a Python statement or expression using the timeit |
|
1771 | Time execution of a Python statement or expression using the timeit | |
1769 | module. |
|
1772 | module. | |
1770 |
|
1773 | |||
1771 | Options: |
|
1774 | Options: | |
1772 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1775 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1773 | is not given, a fitting value is chosen. |
|
1776 | is not given, a fitting value is chosen. | |
1774 |
|
1777 | |||
1775 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1778 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1776 | Default: 3 |
|
1779 | Default: 3 | |
1777 |
|
1780 | |||
1778 | -t: use time.time to measure the time, which is the default on Unix. |
|
1781 | -t: use time.time to measure the time, which is the default on Unix. | |
1779 | This function measures wall time. |
|
1782 | This function measures wall time. | |
1780 |
|
1783 | |||
1781 | -c: use time.clock to measure the time, which is the default on |
|
1784 | -c: use time.clock to measure the time, which is the default on | |
1782 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1785 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1783 | instead and returns the CPU user time. |
|
1786 | instead and returns the CPU user time. | |
1784 |
|
1787 | |||
1785 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1788 | -p<P>: use a precision of <P> digits to display the timing result. | |
1786 | Default: 3 |
|
1789 | Default: 3 | |
1787 |
|
1790 | |||
1788 |
|
1791 | |||
1789 | Examples: |
|
1792 | Examples: | |
1790 |
|
1793 | |||
1791 | In [1]: %timeit pass |
|
1794 | In [1]: %timeit pass | |
1792 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1795 | 10000000 loops, best of 3: 53.3 ns per loop | |
1793 |
|
1796 | |||
1794 | In [2]: u = None |
|
1797 | In [2]: u = None | |
1795 |
|
1798 | |||
1796 | In [3]: %timeit u is None |
|
1799 | In [3]: %timeit u is None | |
1797 | 10000000 loops, best of 3: 184 ns per loop |
|
1800 | 10000000 loops, best of 3: 184 ns per loop | |
1798 |
|
1801 | |||
1799 | In [4]: %timeit -r 4 u == None |
|
1802 | In [4]: %timeit -r 4 u == None | |
1800 | 1000000 loops, best of 4: 242 ns per loop |
|
1803 | 1000000 loops, best of 4: 242 ns per loop | |
1801 |
|
1804 | |||
1802 | In [5]: import time |
|
1805 | In [5]: import time | |
1803 |
|
1806 | |||
1804 | In [6]: %timeit -n1 time.sleep(2) |
|
1807 | In [6]: %timeit -n1 time.sleep(2) | |
1805 | 1 loops, best of 3: 2 s per loop |
|
1808 | 1 loops, best of 3: 2 s per loop | |
1806 |
|
1809 | |||
1807 |
|
1810 | |||
1808 | The times reported by %timeit will be slightly higher than those |
|
1811 | The times reported by %timeit will be slightly higher than those | |
1809 | reported by the timeit.py script when variables are accessed. This is |
|
1812 | reported by the timeit.py script when variables are accessed. This is | |
1810 | due to the fact that %timeit executes the statement in the namespace |
|
1813 | due to the fact that %timeit executes the statement in the namespace | |
1811 | of the shell, compared with timeit.py, which uses a single setup |
|
1814 | of the shell, compared with timeit.py, which uses a single setup | |
1812 | statement to import function or create variables. Generally, the bias |
|
1815 | statement to import function or create variables. Generally, the bias | |
1813 | does not matter as long as results from timeit.py are not mixed with |
|
1816 | does not matter as long as results from timeit.py are not mixed with | |
1814 | those from %timeit.""" |
|
1817 | those from %timeit.""" | |
1815 |
|
1818 | |||
1816 | import timeit |
|
1819 | import timeit | |
1817 | import math |
|
1820 | import math | |
1818 |
|
1821 | |||
1819 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1822 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1820 | # certain terminals. Until we figure out a robust way of |
|
1823 | # certain terminals. Until we figure out a robust way of | |
1821 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1824 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1822 | # microseconds. I am really NOT happy about disabling the proper |
|
1825 | # microseconds. I am really NOT happy about disabling the proper | |
1823 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1826 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1824 | # right solution for this is, I'm all ears... |
|
1827 | # right solution for this is, I'm all ears... | |
1825 | # |
|
1828 | # | |
1826 | # Note: using |
|
1829 | # Note: using | |
1827 | # |
|
1830 | # | |
1828 | # s = u'\xb5' |
|
1831 | # s = u'\xb5' | |
1829 | # s.encode(sys.getdefaultencoding()) |
|
1832 | # s.encode(sys.getdefaultencoding()) | |
1830 | # |
|
1833 | # | |
1831 | # is not sufficient, as I've seen terminals where that fails but |
|
1834 | # is not sufficient, as I've seen terminals where that fails but | |
1832 | # print s |
|
1835 | # print s | |
1833 | # |
|
1836 | # | |
1834 | # succeeds |
|
1837 | # succeeds | |
1835 | # |
|
1838 | # | |
1836 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1839 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1837 |
|
1840 | |||
1838 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1841 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1839 | units = [u"s", u"ms",u'us',"ns"] |
|
1842 | units = [u"s", u"ms",u'us',"ns"] | |
1840 |
|
1843 | |||
1841 | scaling = [1, 1e3, 1e6, 1e9] |
|
1844 | scaling = [1, 1e3, 1e6, 1e9] | |
1842 |
|
1845 | |||
1843 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1846 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1844 | posix=False) |
|
1847 | posix=False) | |
1845 | if stmt == "": |
|
1848 | if stmt == "": | |
1846 | return |
|
1849 | return | |
1847 | timefunc = timeit.default_timer |
|
1850 | timefunc = timeit.default_timer | |
1848 | number = int(getattr(opts, "n", 0)) |
|
1851 | number = int(getattr(opts, "n", 0)) | |
1849 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1852 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1850 | precision = int(getattr(opts, "p", 3)) |
|
1853 | precision = int(getattr(opts, "p", 3)) | |
1851 | if hasattr(opts, "t"): |
|
1854 | if hasattr(opts, "t"): | |
1852 | timefunc = time.time |
|
1855 | timefunc = time.time | |
1853 | if hasattr(opts, "c"): |
|
1856 | if hasattr(opts, "c"): | |
1854 | timefunc = clock |
|
1857 | timefunc = clock | |
1855 |
|
1858 | |||
1856 | timer = timeit.Timer(timer=timefunc) |
|
1859 | timer = timeit.Timer(timer=timefunc) | |
1857 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1860 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1858 | # but is there a better way to achieve that the code stmt has access |
|
1861 | # but is there a better way to achieve that the code stmt has access | |
1859 | # to the shell namespace? |
|
1862 | # to the shell namespace? | |
1860 |
|
1863 | |||
1861 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1864 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1862 | 'setup': "pass"} |
|
1865 | 'setup': "pass"} | |
1863 | # Track compilation time so it can be reported if too long |
|
1866 | # Track compilation time so it can be reported if too long | |
1864 | # Minimum time above which compilation time will be reported |
|
1867 | # Minimum time above which compilation time will be reported | |
1865 | tc_min = 0.1 |
|
1868 | tc_min = 0.1 | |
1866 |
|
1869 | |||
1867 | t0 = clock() |
|
1870 | t0 = clock() | |
1868 | code = compile(src, "<magic-timeit>", "exec") |
|
1871 | code = compile(src, "<magic-timeit>", "exec") | |
1869 | tc = clock()-t0 |
|
1872 | tc = clock()-t0 | |
1870 |
|
1873 | |||
1871 | ns = {} |
|
1874 | ns = {} | |
1872 | exec code in self.shell.user_ns, ns |
|
1875 | exec code in self.shell.user_ns, ns | |
1873 | timer.inner = ns["inner"] |
|
1876 | timer.inner = ns["inner"] | |
1874 |
|
1877 | |||
1875 | if number == 0: |
|
1878 | if number == 0: | |
1876 | # determine number so that 0.2 <= total time < 2.0 |
|
1879 | # determine number so that 0.2 <= total time < 2.0 | |
1877 | number = 1 |
|
1880 | number = 1 | |
1878 | for i in range(1, 10): |
|
1881 | for i in range(1, 10): | |
1879 | if timer.timeit(number) >= 0.2: |
|
1882 | if timer.timeit(number) >= 0.2: | |
1880 | break |
|
1883 | break | |
1881 | number *= 10 |
|
1884 | number *= 10 | |
1882 |
|
1885 | |||
1883 | best = min(timer.repeat(repeat, number)) / number |
|
1886 | best = min(timer.repeat(repeat, number)) / number | |
1884 |
|
1887 | |||
1885 | if best > 0.0: |
|
1888 | if best > 0.0: | |
1886 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1889 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1887 | else: |
|
1890 | else: | |
1888 | order = 3 |
|
1891 | order = 3 | |
1889 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1892 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1890 | precision, |
|
1893 | precision, | |
1891 | best * scaling[order], |
|
1894 | best * scaling[order], | |
1892 | units[order]) |
|
1895 | units[order]) | |
1893 | if tc > tc_min: |
|
1896 | if tc > tc_min: | |
1894 | print "Compiler time: %.2f s" % tc |
|
1897 | print "Compiler time: %.2f s" % tc | |
1895 |
|
1898 | |||
1896 | @testdec.skip_doctest |
|
1899 | @testdec.skip_doctest | |
1897 | def magic_time(self,parameter_s = ''): |
|
1900 | def magic_time(self,parameter_s = ''): | |
1898 | """Time execution of a Python statement or expression. |
|
1901 | """Time execution of a Python statement or expression. | |
1899 |
|
1902 | |||
1900 | The CPU and wall clock times are printed, and the value of the |
|
1903 | The CPU and wall clock times are printed, and the value of the | |
1901 | expression (if any) is returned. Note that under Win32, system time |
|
1904 | expression (if any) is returned. Note that under Win32, system time | |
1902 | is always reported as 0, since it can not be measured. |
|
1905 | is always reported as 0, since it can not be measured. | |
1903 |
|
1906 | |||
1904 | This function provides very basic timing functionality. In Python |
|
1907 | This function provides very basic timing functionality. In Python | |
1905 | 2.3, the timeit module offers more control and sophistication, so this |
|
1908 | 2.3, the timeit module offers more control and sophistication, so this | |
1906 | could be rewritten to use it (patches welcome). |
|
1909 | could be rewritten to use it (patches welcome). | |
1907 |
|
1910 | |||
1908 | Some examples: |
|
1911 | Some examples: | |
1909 |
|
1912 | |||
1910 | In [1]: time 2**128 |
|
1913 | In [1]: time 2**128 | |
1911 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1914 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1912 | Wall time: 0.00 |
|
1915 | Wall time: 0.00 | |
1913 | Out[1]: 340282366920938463463374607431768211456L |
|
1916 | Out[1]: 340282366920938463463374607431768211456L | |
1914 |
|
1917 | |||
1915 | In [2]: n = 1000000 |
|
1918 | In [2]: n = 1000000 | |
1916 |
|
1919 | |||
1917 | In [3]: time sum(range(n)) |
|
1920 | In [3]: time sum(range(n)) | |
1918 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1921 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1919 | Wall time: 1.37 |
|
1922 | Wall time: 1.37 | |
1920 | Out[3]: 499999500000L |
|
1923 | Out[3]: 499999500000L | |
1921 |
|
1924 | |||
1922 | In [4]: time print 'hello world' |
|
1925 | In [4]: time print 'hello world' | |
1923 | hello world |
|
1926 | hello world | |
1924 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1927 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1925 | Wall time: 0.00 |
|
1928 | Wall time: 0.00 | |
1926 |
|
1929 | |||
1927 | Note that the time needed by Python to compile the given expression |
|
1930 | Note that the time needed by Python to compile the given expression | |
1928 | will be reported if it is more than 0.1s. In this example, the |
|
1931 | will be reported if it is more than 0.1s. In this example, the | |
1929 | actual exponentiation is done by Python at compilation time, so while |
|
1932 | actual exponentiation is done by Python at compilation time, so while | |
1930 | the expression can take a noticeable amount of time to compute, that |
|
1933 | the expression can take a noticeable amount of time to compute, that | |
1931 | time is purely due to the compilation: |
|
1934 | time is purely due to the compilation: | |
1932 |
|
1935 | |||
1933 | In [5]: time 3**9999; |
|
1936 | In [5]: time 3**9999; | |
1934 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1937 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1935 | Wall time: 0.00 s |
|
1938 | Wall time: 0.00 s | |
1936 |
|
1939 | |||
1937 | In [6]: time 3**999999; |
|
1940 | In [6]: time 3**999999; | |
1938 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1941 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1939 | Wall time: 0.00 s |
|
1942 | Wall time: 0.00 s | |
1940 | Compiler : 0.78 s |
|
1943 | Compiler : 0.78 s | |
1941 | """ |
|
1944 | """ | |
1942 |
|
1945 | |||
1943 | # fail immediately if the given expression can't be compiled |
|
1946 | # fail immediately if the given expression can't be compiled | |
1944 |
|
1947 | |||
1945 | expr = self.shell.prefilter(parameter_s,False) |
|
1948 | expr = self.shell.prefilter(parameter_s,False) | |
1946 |
|
1949 | |||
1947 | # Minimum time above which compilation time will be reported |
|
1950 | # Minimum time above which compilation time will be reported | |
1948 | tc_min = 0.1 |
|
1951 | tc_min = 0.1 | |
1949 |
|
1952 | |||
1950 | try: |
|
1953 | try: | |
1951 | mode = 'eval' |
|
1954 | mode = 'eval' | |
1952 | t0 = clock() |
|
1955 | t0 = clock() | |
1953 | code = compile(expr,'<timed eval>',mode) |
|
1956 | code = compile(expr,'<timed eval>',mode) | |
1954 | tc = clock()-t0 |
|
1957 | tc = clock()-t0 | |
1955 | except SyntaxError: |
|
1958 | except SyntaxError: | |
1956 | mode = 'exec' |
|
1959 | mode = 'exec' | |
1957 | t0 = clock() |
|
1960 | t0 = clock() | |
1958 | code = compile(expr,'<timed exec>',mode) |
|
1961 | code = compile(expr,'<timed exec>',mode) | |
1959 | tc = clock()-t0 |
|
1962 | tc = clock()-t0 | |
1960 | # skew measurement as little as possible |
|
1963 | # skew measurement as little as possible | |
1961 | glob = self.shell.user_ns |
|
1964 | glob = self.shell.user_ns | |
1962 | clk = clock2 |
|
1965 | clk = clock2 | |
1963 | wtime = time.time |
|
1966 | wtime = time.time | |
1964 | # time execution |
|
1967 | # time execution | |
1965 | wall_st = wtime() |
|
1968 | wall_st = wtime() | |
1966 | if mode=='eval': |
|
1969 | if mode=='eval': | |
1967 | st = clk() |
|
1970 | st = clk() | |
1968 | out = eval(code,glob) |
|
1971 | out = eval(code,glob) | |
1969 | end = clk() |
|
1972 | end = clk() | |
1970 | else: |
|
1973 | else: | |
1971 | st = clk() |
|
1974 | st = clk() | |
1972 | exec code in glob |
|
1975 | exec code in glob | |
1973 | end = clk() |
|
1976 | end = clk() | |
1974 | out = None |
|
1977 | out = None | |
1975 | wall_end = wtime() |
|
1978 | wall_end = wtime() | |
1976 | # Compute actual times and report |
|
1979 | # Compute actual times and report | |
1977 | wall_time = wall_end-wall_st |
|
1980 | wall_time = wall_end-wall_st | |
1978 | cpu_user = end[0]-st[0] |
|
1981 | cpu_user = end[0]-st[0] | |
1979 | cpu_sys = end[1]-st[1] |
|
1982 | cpu_sys = end[1]-st[1] | |
1980 | cpu_tot = cpu_user+cpu_sys |
|
1983 | cpu_tot = cpu_user+cpu_sys | |
1981 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1984 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1982 | (cpu_user,cpu_sys,cpu_tot) |
|
1985 | (cpu_user,cpu_sys,cpu_tot) | |
1983 | print "Wall time: %.2f s" % wall_time |
|
1986 | print "Wall time: %.2f s" % wall_time | |
1984 | if tc > tc_min: |
|
1987 | if tc > tc_min: | |
1985 | print "Compiler : %.2f s" % tc |
|
1988 | print "Compiler : %.2f s" % tc | |
1986 | return out |
|
1989 | return out | |
1987 |
|
1990 | |||
1988 | @testdec.skip_doctest |
|
1991 | @testdec.skip_doctest | |
1989 | def magic_macro(self,parameter_s = ''): |
|
1992 | def magic_macro(self,parameter_s = ''): | |
1990 | """Define a set of input lines as a macro for future re-execution. |
|
1993 | """Define a set of input lines as a macro for future re-execution. | |
1991 |
|
1994 | |||
1992 | Usage:\\ |
|
1995 | Usage:\\ | |
1993 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1996 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1994 |
|
1997 | |||
1995 | Options: |
|
1998 | Options: | |
1996 |
|
1999 | |||
1997 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2000 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1998 | so that magics are loaded in their transformed version to valid |
|
2001 | so that magics are loaded in their transformed version to valid | |
1999 | Python. If this option is given, the raw input as typed as the |
|
2002 | Python. If this option is given, the raw input as typed as the | |
2000 | command line is used instead. |
|
2003 | command line is used instead. | |
2001 |
|
2004 | |||
2002 | This will define a global variable called `name` which is a string |
|
2005 | This will define a global variable called `name` which is a string | |
2003 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2006 | made of joining the slices and lines you specify (n1,n2,... numbers | |
2004 | above) from your input history into a single string. This variable |
|
2007 | above) from your input history into a single string. This variable | |
2005 | acts like an automatic function which re-executes those lines as if |
|
2008 | acts like an automatic function which re-executes those lines as if | |
2006 | you had typed them. You just type 'name' at the prompt and the code |
|
2009 | you had typed them. You just type 'name' at the prompt and the code | |
2007 | executes. |
|
2010 | executes. | |
2008 |
|
2011 | |||
2009 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
2012 | The notation for indicating number ranges is: n1-n2 means 'use line | |
2010 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
2013 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
2011 | using the lines numbered 5,6 and 7. |
|
2014 | using the lines numbered 5,6 and 7. | |
2012 |
|
2015 | |||
2013 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2016 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2014 | notation, where N:M means numbers N through M-1. |
|
2017 | notation, where N:M means numbers N through M-1. | |
2015 |
|
2018 | |||
2016 | For example, if your history contains (%hist prints it): |
|
2019 | For example, if your history contains (%hist prints it): | |
2017 |
|
2020 | |||
2018 | 44: x=1 |
|
2021 | 44: x=1 | |
2019 | 45: y=3 |
|
2022 | 45: y=3 | |
2020 | 46: z=x+y |
|
2023 | 46: z=x+y | |
2021 | 47: print x |
|
2024 | 47: print x | |
2022 | 48: a=5 |
|
2025 | 48: a=5 | |
2023 | 49: print 'x',x,'y',y |
|
2026 | 49: print 'x',x,'y',y | |
2024 |
|
2027 | |||
2025 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2028 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2026 | called my_macro with: |
|
2029 | called my_macro with: | |
2027 |
|
2030 | |||
2028 | In [55]: %macro my_macro 44-47 49 |
|
2031 | In [55]: %macro my_macro 44-47 49 | |
2029 |
|
2032 | |||
2030 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2033 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2031 | in one pass. |
|
2034 | in one pass. | |
2032 |
|
2035 | |||
2033 | You don't need to give the line-numbers in order, and any given line |
|
2036 | You don't need to give the line-numbers in order, and any given line | |
2034 | number can appear multiple times. You can assemble macros with any |
|
2037 | number can appear multiple times. You can assemble macros with any | |
2035 | lines from your input history in any order. |
|
2038 | lines from your input history in any order. | |
2036 |
|
2039 | |||
2037 | The macro is a simple object which holds its value in an attribute, |
|
2040 | The macro is a simple object which holds its value in an attribute, | |
2038 | but IPython's display system checks for macros and executes them as |
|
2041 | but IPython's display system checks for macros and executes them as | |
2039 | code instead of printing them when you type their name. |
|
2042 | code instead of printing them when you type their name. | |
2040 |
|
2043 | |||
2041 | You can view a macro's contents by explicitly printing it with: |
|
2044 | You can view a macro's contents by explicitly printing it with: | |
2042 |
|
2045 | |||
2043 | 'print macro_name'. |
|
2046 | 'print macro_name'. | |
2044 |
|
2047 | |||
2045 | For one-off cases which DON'T contain magic function calls in them you |
|
2048 | For one-off cases which DON'T contain magic function calls in them you | |
2046 | can obtain similar results by explicitly executing slices from your |
|
2049 | can obtain similar results by explicitly executing slices from your | |
2047 | input history with: |
|
2050 | input history with: | |
2048 |
|
2051 | |||
2049 | In [60]: exec In[44:48]+In[49]""" |
|
2052 | In [60]: exec In[44:48]+In[49]""" | |
2050 |
|
2053 | |||
2051 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2054 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2052 | if not args: |
|
2055 | if not args: | |
2053 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2056 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
2054 | macs.sort() |
|
2057 | macs.sort() | |
2055 | return macs |
|
2058 | return macs | |
2056 | if len(args) == 1: |
|
2059 | if len(args) == 1: | |
2057 | raise UsageError( |
|
2060 | raise UsageError( | |
2058 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2061 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2059 | name,ranges = args[0], args[1:] |
|
2062 | name,ranges = args[0], args[1:] | |
2060 |
|
2063 | |||
2061 | #print 'rng',ranges # dbg |
|
2064 | #print 'rng',ranges # dbg | |
2062 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2065 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
2063 | macro = Macro(lines) |
|
2066 | macro = Macro(lines) | |
2064 | self.shell.user_ns.update({name:macro}) |
|
2067 | self.shell.define_macro(name, macro) | |
2065 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2068 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2066 | print 'Macro contents:' |
|
2069 | print 'Macro contents:' | |
2067 | print macro, |
|
2070 | print macro, | |
2068 |
|
2071 | |||
2069 | def magic_save(self,parameter_s = ''): |
|
2072 | def magic_save(self,parameter_s = ''): | |
2070 | """Save a set of lines to a given filename. |
|
2073 | """Save a set of lines to a given filename. | |
2071 |
|
2074 | |||
2072 | Usage:\\ |
|
2075 | Usage:\\ | |
2073 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2076 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2074 |
|
2077 | |||
2075 | Options: |
|
2078 | Options: | |
2076 |
|
2079 | |||
2077 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2080 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2078 | so that magics are loaded in their transformed version to valid |
|
2081 | so that magics are loaded in their transformed version to valid | |
2079 | Python. If this option is given, the raw input as typed as the |
|
2082 | Python. If this option is given, the raw input as typed as the | |
2080 | command line is used instead. |
|
2083 | command line is used instead. | |
2081 |
|
2084 | |||
2082 | This function uses the same syntax as %macro for line extraction, but |
|
2085 | This function uses the same syntax as %macro for line extraction, but | |
2083 | instead of creating a macro it saves the resulting string to the |
|
2086 | instead of creating a macro it saves the resulting string to the | |
2084 | filename you specify. |
|
2087 | filename you specify. | |
2085 |
|
2088 | |||
2086 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2089 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2087 | it asks for confirmation before overwriting existing files.""" |
|
2090 | it asks for confirmation before overwriting existing files.""" | |
2088 |
|
2091 | |||
2089 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2092 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2090 | fname,ranges = args[0], args[1:] |
|
2093 | fname,ranges = args[0], args[1:] | |
2091 | if not fname.endswith('.py'): |
|
2094 | if not fname.endswith('.py'): | |
2092 | fname += '.py' |
|
2095 | fname += '.py' | |
2093 | if os.path.isfile(fname): |
|
2096 | if os.path.isfile(fname): | |
2094 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2097 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2095 | if ans.lower() not in ['y','yes']: |
|
2098 | if ans.lower() not in ['y','yes']: | |
2096 | print 'Operation cancelled.' |
|
2099 | print 'Operation cancelled.' | |
2097 | return |
|
2100 | return | |
2098 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2101 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2099 | f = file(fname,'w') |
|
2102 | f = file(fname,'w') | |
2100 | f.write(cmds) |
|
2103 | f.write(cmds) | |
2101 | f.close() |
|
2104 | f.close() | |
2102 | print 'The following commands were written to file `%s`:' % fname |
|
2105 | print 'The following commands were written to file `%s`:' % fname | |
2103 | print cmds |
|
2106 | print cmds | |
2104 |
|
2107 | |||
2105 | def _edit_macro(self,mname,macro): |
|
2108 | def _edit_macro(self,mname,macro): | |
2106 | """open an editor with the macro data in a file""" |
|
2109 | """open an editor with the macro data in a file""" | |
2107 | filename = self.shell.mktempfile(macro.value) |
|
2110 | filename = self.shell.mktempfile(macro.value) | |
2108 | self.shell.hooks.editor(filename) |
|
2111 | self.shell.hooks.editor(filename) | |
2109 |
|
2112 | |||
2110 | # and make a new macro object, to replace the old one |
|
2113 | # and make a new macro object, to replace the old one | |
2111 | mfile = open(filename) |
|
2114 | mfile = open(filename) | |
2112 | mvalue = mfile.read() |
|
2115 | mvalue = mfile.read() | |
2113 | mfile.close() |
|
2116 | mfile.close() | |
2114 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2117 | self.shell.user_ns[mname] = Macro(mvalue) | |
2115 |
|
2118 | |||
2116 | def magic_ed(self,parameter_s=''): |
|
2119 | def magic_ed(self,parameter_s=''): | |
2117 | """Alias to %edit.""" |
|
2120 | """Alias to %edit.""" | |
2118 | return self.magic_edit(parameter_s) |
|
2121 | return self.magic_edit(parameter_s) | |
2119 |
|
2122 | |||
2120 | @testdec.skip_doctest |
|
2123 | @testdec.skip_doctest | |
2121 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2124 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2122 | """Bring up an editor and execute the resulting code. |
|
2125 | """Bring up an editor and execute the resulting code. | |
2123 |
|
2126 | |||
2124 | Usage: |
|
2127 | Usage: | |
2125 | %edit [options] [args] |
|
2128 | %edit [options] [args] | |
2126 |
|
2129 | |||
2127 | %edit runs IPython's editor hook. The default version of this hook is |
|
2130 | %edit runs IPython's editor hook. The default version of this hook is | |
2128 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2131 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2129 | environment variable $EDITOR. If this isn't found, it will default to |
|
2132 | environment variable $EDITOR. If this isn't found, it will default to | |
2130 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2133 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2131 | docstring for how to change the editor hook. |
|
2134 | docstring for how to change the editor hook. | |
2132 |
|
2135 | |||
2133 | You can also set the value of this editor via the command line option |
|
2136 | You can also set the value of this editor via the command line option | |
2134 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2137 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2135 | specifically for IPython an editor different from your typical default |
|
2138 | specifically for IPython an editor different from your typical default | |
2136 | (and for Windows users who typically don't set environment variables). |
|
2139 | (and for Windows users who typically don't set environment variables). | |
2137 |
|
2140 | |||
2138 | This command allows you to conveniently edit multi-line code right in |
|
2141 | This command allows you to conveniently edit multi-line code right in | |
2139 | your IPython session. |
|
2142 | your IPython session. | |
2140 |
|
2143 | |||
2141 | If called without arguments, %edit opens up an empty editor with a |
|
2144 | If called without arguments, %edit opens up an empty editor with a | |
2142 | temporary file and will execute the contents of this file when you |
|
2145 | temporary file and will execute the contents of this file when you | |
2143 | close it (don't forget to save it!). |
|
2146 | close it (don't forget to save it!). | |
2144 |
|
2147 | |||
2145 |
|
2148 | |||
2146 | Options: |
|
2149 | Options: | |
2147 |
|
2150 | |||
2148 | -n <number>: open the editor at a specified line number. By default, |
|
2151 | -n <number>: open the editor at a specified line number. By default, | |
2149 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2152 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2150 | you can configure this by providing your own modified hook if your |
|
2153 | you can configure this by providing your own modified hook if your | |
2151 | favorite editor supports line-number specifications with a different |
|
2154 | favorite editor supports line-number specifications with a different | |
2152 | syntax. |
|
2155 | syntax. | |
2153 |
|
2156 | |||
2154 | -p: this will call the editor with the same data as the previous time |
|
2157 | -p: this will call the editor with the same data as the previous time | |
2155 | it was used, regardless of how long ago (in your current session) it |
|
2158 | it was used, regardless of how long ago (in your current session) it | |
2156 | was. |
|
2159 | was. | |
2157 |
|
2160 | |||
2158 | -r: use 'raw' input. This option only applies to input taken from the |
|
2161 | -r: use 'raw' input. This option only applies to input taken from the | |
2159 | user's history. By default, the 'processed' history is used, so that |
|
2162 | user's history. By default, the 'processed' history is used, so that | |
2160 | magics are loaded in their transformed version to valid Python. If |
|
2163 | magics are loaded in their transformed version to valid Python. If | |
2161 | this option is given, the raw input as typed as the command line is |
|
2164 | this option is given, the raw input as typed as the command line is | |
2162 | used instead. When you exit the editor, it will be executed by |
|
2165 | used instead. When you exit the editor, it will be executed by | |
2163 | IPython's own processor. |
|
2166 | IPython's own processor. | |
2164 |
|
2167 | |||
2165 | -x: do not execute the edited code immediately upon exit. This is |
|
2168 | -x: do not execute the edited code immediately upon exit. This is | |
2166 | mainly useful if you are editing programs which need to be called with |
|
2169 | mainly useful if you are editing programs which need to be called with | |
2167 | command line arguments, which you can then do using %run. |
|
2170 | command line arguments, which you can then do using %run. | |
2168 |
|
2171 | |||
2169 |
|
2172 | |||
2170 | Arguments: |
|
2173 | Arguments: | |
2171 |
|
2174 | |||
2172 | If arguments are given, the following possibilites exist: |
|
2175 | If arguments are given, the following possibilites exist: | |
2173 |
|
2176 | |||
2174 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2177 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2175 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2178 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2176 | loaded into the editor. The syntax is the same of the %macro command. |
|
2179 | loaded into the editor. The syntax is the same of the %macro command. | |
2177 |
|
2180 | |||
2178 | - If the argument doesn't start with a number, it is evaluated as a |
|
2181 | - If the argument doesn't start with a number, it is evaluated as a | |
2179 | variable and its contents loaded into the editor. You can thus edit |
|
2182 | variable and its contents loaded into the editor. You can thus edit | |
2180 | any string which contains python code (including the result of |
|
2183 | any string which contains python code (including the result of | |
2181 | previous edits). |
|
2184 | previous edits). | |
2182 |
|
2185 | |||
2183 | - If the argument is the name of an object (other than a string), |
|
2186 | - If the argument is the name of an object (other than a string), | |
2184 | IPython will try to locate the file where it was defined and open the |
|
2187 | IPython will try to locate the file where it was defined and open the | |
2185 | editor at the point where it is defined. You can use `%edit function` |
|
2188 | editor at the point where it is defined. You can use `%edit function` | |
2186 | to load an editor exactly at the point where 'function' is defined, |
|
2189 | to load an editor exactly at the point where 'function' is defined, | |
2187 | edit it and have the file be executed automatically. |
|
2190 | edit it and have the file be executed automatically. | |
2188 |
|
2191 | |||
2189 | If the object is a macro (see %macro for details), this opens up your |
|
2192 | If the object is a macro (see %macro for details), this opens up your | |
2190 | specified editor with a temporary file containing the macro's data. |
|
2193 | specified editor with a temporary file containing the macro's data. | |
2191 | Upon exit, the macro is reloaded with the contents of the file. |
|
2194 | Upon exit, the macro is reloaded with the contents of the file. | |
2192 |
|
2195 | |||
2193 | Note: opening at an exact line is only supported under Unix, and some |
|
2196 | Note: opening at an exact line is only supported under Unix, and some | |
2194 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2197 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2195 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2198 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2196 | (X)Emacs, vi, jed, pico and joe all do. |
|
2199 | (X)Emacs, vi, jed, pico and joe all do. | |
2197 |
|
2200 | |||
2198 | - If the argument is not found as a variable, IPython will look for a |
|
2201 | - If the argument is not found as a variable, IPython will look for a | |
2199 | file with that name (adding .py if necessary) and load it into the |
|
2202 | file with that name (adding .py if necessary) and load it into the | |
2200 | editor. It will execute its contents with execfile() when you exit, |
|
2203 | editor. It will execute its contents with execfile() when you exit, | |
2201 | loading any code in the file into your interactive namespace. |
|
2204 | loading any code in the file into your interactive namespace. | |
2202 |
|
2205 | |||
2203 | After executing your code, %edit will return as output the code you |
|
2206 | After executing your code, %edit will return as output the code you | |
2204 | typed in the editor (except when it was an existing file). This way |
|
2207 | typed in the editor (except when it was an existing file). This way | |
2205 | you can reload the code in further invocations of %edit as a variable, |
|
2208 | you can reload the code in further invocations of %edit as a variable, | |
2206 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2209 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2207 | the output. |
|
2210 | the output. | |
2208 |
|
2211 | |||
2209 | Note that %edit is also available through the alias %ed. |
|
2212 | Note that %edit is also available through the alias %ed. | |
2210 |
|
2213 | |||
2211 | This is an example of creating a simple function inside the editor and |
|
2214 | This is an example of creating a simple function inside the editor and | |
2212 | then modifying it. First, start up the editor: |
|
2215 | then modifying it. First, start up the editor: | |
2213 |
|
2216 | |||
2214 | In [1]: ed |
|
2217 | In [1]: ed | |
2215 | Editing... done. Executing edited code... |
|
2218 | Editing... done. Executing edited code... | |
2216 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2219 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2217 |
|
2220 | |||
2218 | We can then call the function foo(): |
|
2221 | We can then call the function foo(): | |
2219 |
|
2222 | |||
2220 | In [2]: foo() |
|
2223 | In [2]: foo() | |
2221 | foo() was defined in an editing session |
|
2224 | foo() was defined in an editing session | |
2222 |
|
2225 | |||
2223 | Now we edit foo. IPython automatically loads the editor with the |
|
2226 | Now we edit foo. IPython automatically loads the editor with the | |
2224 | (temporary) file where foo() was previously defined: |
|
2227 | (temporary) file where foo() was previously defined: | |
2225 |
|
2228 | |||
2226 | In [3]: ed foo |
|
2229 | In [3]: ed foo | |
2227 | Editing... done. Executing edited code... |
|
2230 | Editing... done. Executing edited code... | |
2228 |
|
2231 | |||
2229 | And if we call foo() again we get the modified version: |
|
2232 | And if we call foo() again we get the modified version: | |
2230 |
|
2233 | |||
2231 | In [4]: foo() |
|
2234 | In [4]: foo() | |
2232 | foo() has now been changed! |
|
2235 | foo() has now been changed! | |
2233 |
|
2236 | |||
2234 | Here is an example of how to edit a code snippet successive |
|
2237 | Here is an example of how to edit a code snippet successive | |
2235 | times. First we call the editor: |
|
2238 | times. First we call the editor: | |
2236 |
|
2239 | |||
2237 | In [5]: ed |
|
2240 | In [5]: ed | |
2238 | Editing... done. Executing edited code... |
|
2241 | Editing... done. Executing edited code... | |
2239 | hello |
|
2242 | hello | |
2240 | Out[5]: "print 'hello'n" |
|
2243 | Out[5]: "print 'hello'n" | |
2241 |
|
2244 | |||
2242 | Now we call it again with the previous output (stored in _): |
|
2245 | Now we call it again with the previous output (stored in _): | |
2243 |
|
2246 | |||
2244 | In [6]: ed _ |
|
2247 | In [6]: ed _ | |
2245 | Editing... done. Executing edited code... |
|
2248 | Editing... done. Executing edited code... | |
2246 | hello world |
|
2249 | hello world | |
2247 | Out[6]: "print 'hello world'n" |
|
2250 | Out[6]: "print 'hello world'n" | |
2248 |
|
2251 | |||
2249 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2252 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2250 |
|
2253 | |||
2251 | In [7]: ed _8 |
|
2254 | In [7]: ed _8 | |
2252 | Editing... done. Executing edited code... |
|
2255 | Editing... done. Executing edited code... | |
2253 | hello again |
|
2256 | hello again | |
2254 | Out[7]: "print 'hello again'n" |
|
2257 | Out[7]: "print 'hello again'n" | |
2255 |
|
2258 | |||
2256 |
|
2259 | |||
2257 | Changing the default editor hook: |
|
2260 | Changing the default editor hook: | |
2258 |
|
2261 | |||
2259 | If you wish to write your own editor hook, you can put it in a |
|
2262 | If you wish to write your own editor hook, you can put it in a | |
2260 | configuration file which you load at startup time. The default hook |
|
2263 | configuration file which you load at startup time. The default hook | |
2261 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2264 | is defined in the IPython.core.hooks module, and you can use that as a | |
2262 | starting example for further modifications. That file also has |
|
2265 | starting example for further modifications. That file also has | |
2263 | general instructions on how to set a new hook for use once you've |
|
2266 | general instructions on how to set a new hook for use once you've | |
2264 | defined it.""" |
|
2267 | defined it.""" | |
2265 |
|
2268 | |||
2266 | # FIXME: This function has become a convoluted mess. It needs a |
|
2269 | # FIXME: This function has become a convoluted mess. It needs a | |
2267 | # ground-up rewrite with clean, simple logic. |
|
2270 | # ground-up rewrite with clean, simple logic. | |
2268 |
|
2271 | |||
2269 | def make_filename(arg): |
|
2272 | def make_filename(arg): | |
2270 | "Make a filename from the given args" |
|
2273 | "Make a filename from the given args" | |
2271 | try: |
|
2274 | try: | |
2272 | filename = get_py_filename(arg) |
|
2275 | filename = get_py_filename(arg) | |
2273 | except IOError: |
|
2276 | except IOError: | |
2274 | if args.endswith('.py'): |
|
2277 | if args.endswith('.py'): | |
2275 | filename = arg |
|
2278 | filename = arg | |
2276 | else: |
|
2279 | else: | |
2277 | filename = None |
|
2280 | filename = None | |
2278 | return filename |
|
2281 | return filename | |
2279 |
|
2282 | |||
2280 | # custom exceptions |
|
2283 | # custom exceptions | |
2281 | class DataIsObject(Exception): pass |
|
2284 | class DataIsObject(Exception): pass | |
2282 |
|
2285 | |||
2283 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2286 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2284 | # Set a few locals from the options for convenience: |
|
2287 | # Set a few locals from the options for convenience: | |
2285 | opts_p = opts.has_key('p') |
|
2288 | opts_p = opts.has_key('p') | |
2286 | opts_r = opts.has_key('r') |
|
2289 | opts_r = opts.has_key('r') | |
2287 |
|
2290 | |||
2288 | # Default line number value |
|
2291 | # Default line number value | |
2289 | lineno = opts.get('n',None) |
|
2292 | lineno = opts.get('n',None) | |
2290 |
|
2293 | |||
2291 | if opts_p: |
|
2294 | if opts_p: | |
2292 | args = '_%s' % last_call[0] |
|
2295 | args = '_%s' % last_call[0] | |
2293 | if not self.shell.user_ns.has_key(args): |
|
2296 | if not self.shell.user_ns.has_key(args): | |
2294 | args = last_call[1] |
|
2297 | args = last_call[1] | |
2295 |
|
2298 | |||
2296 | # use last_call to remember the state of the previous call, but don't |
|
2299 | # use last_call to remember the state of the previous call, but don't | |
2297 | # let it be clobbered by successive '-p' calls. |
|
2300 | # let it be clobbered by successive '-p' calls. | |
2298 | try: |
|
2301 | try: | |
2299 | last_call[0] = self.shell.outputcache.prompt_count |
|
2302 | last_call[0] = self.shell.outputcache.prompt_count | |
2300 | if not opts_p: |
|
2303 | if not opts_p: | |
2301 | last_call[1] = parameter_s |
|
2304 | last_call[1] = parameter_s | |
2302 | except: |
|
2305 | except: | |
2303 | pass |
|
2306 | pass | |
2304 |
|
2307 | |||
2305 | # by default this is done with temp files, except when the given |
|
2308 | # by default this is done with temp files, except when the given | |
2306 | # arg is a filename |
|
2309 | # arg is a filename | |
2307 | use_temp = 1 |
|
2310 | use_temp = 1 | |
2308 |
|
2311 | |||
2309 | if re.match(r'\d',args): |
|
2312 | if re.match(r'\d',args): | |
2310 | # Mode where user specifies ranges of lines, like in %macro. |
|
2313 | # Mode where user specifies ranges of lines, like in %macro. | |
2311 | # This means that you can't edit files whose names begin with |
|
2314 | # This means that you can't edit files whose names begin with | |
2312 | # numbers this way. Tough. |
|
2315 | # numbers this way. Tough. | |
2313 | ranges = args.split() |
|
2316 | ranges = args.split() | |
2314 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2317 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2315 | elif args.endswith('.py'): |
|
2318 | elif args.endswith('.py'): | |
2316 | filename = make_filename(args) |
|
2319 | filename = make_filename(args) | |
2317 | data = '' |
|
2320 | data = '' | |
2318 | use_temp = 0 |
|
2321 | use_temp = 0 | |
2319 | elif args: |
|
2322 | elif args: | |
2320 | try: |
|
2323 | try: | |
2321 | # Load the parameter given as a variable. If not a string, |
|
2324 | # Load the parameter given as a variable. If not a string, | |
2322 | # process it as an object instead (below) |
|
2325 | # process it as an object instead (below) | |
2323 |
|
2326 | |||
2324 | #print '*** args',args,'type',type(args) # dbg |
|
2327 | #print '*** args',args,'type',type(args) # dbg | |
2325 | data = eval(args,self.shell.user_ns) |
|
2328 | data = eval(args,self.shell.user_ns) | |
2326 | if not type(data) in StringTypes: |
|
2329 | if not type(data) in StringTypes: | |
2327 | raise DataIsObject |
|
2330 | raise DataIsObject | |
2328 |
|
2331 | |||
2329 | except (NameError,SyntaxError): |
|
2332 | except (NameError,SyntaxError): | |
2330 | # given argument is not a variable, try as a filename |
|
2333 | # given argument is not a variable, try as a filename | |
2331 | filename = make_filename(args) |
|
2334 | filename = make_filename(args) | |
2332 | if filename is None: |
|
2335 | if filename is None: | |
2333 | warn("Argument given (%s) can't be found as a variable " |
|
2336 | warn("Argument given (%s) can't be found as a variable " | |
2334 | "or as a filename." % args) |
|
2337 | "or as a filename." % args) | |
2335 | return |
|
2338 | return | |
2336 |
|
2339 | |||
2337 | data = '' |
|
2340 | data = '' | |
2338 | use_temp = 0 |
|
2341 | use_temp = 0 | |
2339 | except DataIsObject: |
|
2342 | except DataIsObject: | |
2340 |
|
2343 | |||
2341 | # macros have a special edit function |
|
2344 | # macros have a special edit function | |
2342 | if isinstance(data,Macro): |
|
2345 | if isinstance(data,Macro): | |
2343 | self._edit_macro(args,data) |
|
2346 | self._edit_macro(args,data) | |
2344 | return |
|
2347 | return | |
2345 |
|
2348 | |||
2346 | # For objects, try to edit the file where they are defined |
|
2349 | # For objects, try to edit the file where they are defined | |
2347 | try: |
|
2350 | try: | |
2348 | filename = inspect.getabsfile(data) |
|
2351 | filename = inspect.getabsfile(data) | |
2349 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2352 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2350 | # class created by %edit? Try to find source |
|
2353 | # class created by %edit? Try to find source | |
2351 | # by looking for method definitions instead, the |
|
2354 | # by looking for method definitions instead, the | |
2352 | # __module__ in those classes is FakeModule. |
|
2355 | # __module__ in those classes is FakeModule. | |
2353 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2356 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2354 | for attr in attrs: |
|
2357 | for attr in attrs: | |
2355 | if not inspect.ismethod(attr): |
|
2358 | if not inspect.ismethod(attr): | |
2356 | continue |
|
2359 | continue | |
2357 | filename = inspect.getabsfile(attr) |
|
2360 | filename = inspect.getabsfile(attr) | |
2358 | if filename and 'fakemodule' not in filename.lower(): |
|
2361 | if filename and 'fakemodule' not in filename.lower(): | |
2359 | # change the attribute to be the edit target instead |
|
2362 | # change the attribute to be the edit target instead | |
2360 | data = attr |
|
2363 | data = attr | |
2361 | break |
|
2364 | break | |
2362 |
|
2365 | |||
2363 | datafile = 1 |
|
2366 | datafile = 1 | |
2364 | except TypeError: |
|
2367 | except TypeError: | |
2365 | filename = make_filename(args) |
|
2368 | filename = make_filename(args) | |
2366 | datafile = 1 |
|
2369 | datafile = 1 | |
2367 | warn('Could not find file where `%s` is defined.\n' |
|
2370 | warn('Could not find file where `%s` is defined.\n' | |
2368 | 'Opening a file named `%s`' % (args,filename)) |
|
2371 | 'Opening a file named `%s`' % (args,filename)) | |
2369 | # Now, make sure we can actually read the source (if it was in |
|
2372 | # Now, make sure we can actually read the source (if it was in | |
2370 | # a temp file it's gone by now). |
|
2373 | # a temp file it's gone by now). | |
2371 | if datafile: |
|
2374 | if datafile: | |
2372 | try: |
|
2375 | try: | |
2373 | if lineno is None: |
|
2376 | if lineno is None: | |
2374 | lineno = inspect.getsourcelines(data)[1] |
|
2377 | lineno = inspect.getsourcelines(data)[1] | |
2375 | except IOError: |
|
2378 | except IOError: | |
2376 | filename = make_filename(args) |
|
2379 | filename = make_filename(args) | |
2377 | if filename is None: |
|
2380 | if filename is None: | |
2378 | warn('The file `%s` where `%s` was defined cannot ' |
|
2381 | warn('The file `%s` where `%s` was defined cannot ' | |
2379 | 'be read.' % (filename,data)) |
|
2382 | 'be read.' % (filename,data)) | |
2380 | return |
|
2383 | return | |
2381 | use_temp = 0 |
|
2384 | use_temp = 0 | |
2382 | else: |
|
2385 | else: | |
2383 | data = '' |
|
2386 | data = '' | |
2384 |
|
2387 | |||
2385 | if use_temp: |
|
2388 | if use_temp: | |
2386 | filename = self.shell.mktempfile(data) |
|
2389 | filename = self.shell.mktempfile(data) | |
2387 | print 'IPython will make a temporary file named:',filename |
|
2390 | print 'IPython will make a temporary file named:',filename | |
2388 |
|
2391 | |||
2389 | # do actual editing here |
|
2392 | # do actual editing here | |
2390 | print 'Editing...', |
|
2393 | print 'Editing...', | |
2391 | sys.stdout.flush() |
|
2394 | sys.stdout.flush() | |
2392 | try: |
|
2395 | try: | |
2393 | self.shell.hooks.editor(filename,lineno) |
|
2396 | self.shell.hooks.editor(filename,lineno) | |
2394 |
except |
|
2397 | except TryNext: | |
2395 | warn('Could not open editor') |
|
2398 | warn('Could not open editor') | |
2396 | return |
|
2399 | return | |
2397 |
|
2400 | |||
2398 | # XXX TODO: should this be generalized for all string vars? |
|
2401 | # XXX TODO: should this be generalized for all string vars? | |
2399 | # For now, this is special-cased to blocks created by cpaste |
|
2402 | # For now, this is special-cased to blocks created by cpaste | |
2400 | if args.strip() == 'pasted_block': |
|
2403 | if args.strip() == 'pasted_block': | |
2401 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2404 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2402 |
|
2405 | |||
2403 | if opts.has_key('x'): # -x prevents actual execution |
|
2406 | if opts.has_key('x'): # -x prevents actual execution | |
2404 |
|
2407 | |||
2405 | else: |
|
2408 | else: | |
2406 | print 'done. Executing edited code...' |
|
2409 | print 'done. Executing edited code...' | |
2407 | if opts_r: |
|
2410 | if opts_r: | |
2408 | self.shell.runlines(file_read(filename)) |
|
2411 | self.shell.runlines(file_read(filename)) | |
2409 | else: |
|
2412 | else: | |
2410 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2413 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2411 | self.shell.user_ns) |
|
2414 | self.shell.user_ns) | |
2412 |
|
2415 | |||
2413 |
|
2416 | |||
2414 | if use_temp: |
|
2417 | if use_temp: | |
2415 | try: |
|
2418 | try: | |
2416 | return open(filename).read() |
|
2419 | return open(filename).read() | |
2417 | except IOError,msg: |
|
2420 | except IOError,msg: | |
2418 | if msg.filename == filename: |
|
2421 | if msg.filename == filename: | |
2419 | warn('File not found. Did you forget to save?') |
|
2422 | warn('File not found. Did you forget to save?') | |
2420 | return |
|
2423 | return | |
2421 | else: |
|
2424 | else: | |
2422 | self.shell.showtraceback() |
|
2425 | self.shell.showtraceback() | |
2423 |
|
2426 | |||
2424 | def magic_xmode(self,parameter_s = ''): |
|
2427 | def magic_xmode(self,parameter_s = ''): | |
2425 | """Switch modes for the exception handlers. |
|
2428 | """Switch modes for the exception handlers. | |
2426 |
|
2429 | |||
2427 | Valid modes: Plain, Context and Verbose. |
|
2430 | Valid modes: Plain, Context and Verbose. | |
2428 |
|
2431 | |||
2429 | If called without arguments, acts as a toggle.""" |
|
2432 | If called without arguments, acts as a toggle.""" | |
2430 |
|
2433 | |||
2431 | def xmode_switch_err(name): |
|
2434 | def xmode_switch_err(name): | |
2432 | warn('Error changing %s exception modes.\n%s' % |
|
2435 | warn('Error changing %s exception modes.\n%s' % | |
2433 | (name,sys.exc_info()[1])) |
|
2436 | (name,sys.exc_info()[1])) | |
2434 |
|
2437 | |||
2435 | shell = self.shell |
|
2438 | shell = self.shell | |
2436 | new_mode = parameter_s.strip().capitalize() |
|
2439 | new_mode = parameter_s.strip().capitalize() | |
2437 | try: |
|
2440 | try: | |
2438 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2441 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2439 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2442 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2440 | except: |
|
2443 | except: | |
2441 | xmode_switch_err('user') |
|
2444 | xmode_switch_err('user') | |
2442 |
|
2445 | |||
2443 | # threaded shells use a special handler in sys.excepthook |
|
2446 | # threaded shells use a special handler in sys.excepthook | |
2444 | if shell.isthreaded: |
|
2447 | if shell.isthreaded: | |
2445 | try: |
|
2448 | try: | |
2446 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2449 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2447 | except: |
|
2450 | except: | |
2448 | xmode_switch_err('threaded') |
|
2451 | xmode_switch_err('threaded') | |
2449 |
|
2452 | |||
2450 | def magic_colors(self,parameter_s = ''): |
|
2453 | def magic_colors(self,parameter_s = ''): | |
2451 | """Switch color scheme for prompts, info system and exception handlers. |
|
2454 | """Switch color scheme for prompts, info system and exception handlers. | |
2452 |
|
2455 | |||
2453 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2456 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2454 |
|
2457 | |||
2455 | Color scheme names are not case-sensitive.""" |
|
2458 | Color scheme names are not case-sensitive.""" | |
2456 |
|
2459 | |||
2457 | def color_switch_err(name): |
|
2460 | def color_switch_err(name): | |
2458 | warn('Error changing %s color schemes.\n%s' % |
|
2461 | warn('Error changing %s color schemes.\n%s' % | |
2459 | (name,sys.exc_info()[1])) |
|
2462 | (name,sys.exc_info()[1])) | |
2460 |
|
2463 | |||
2461 |
|
2464 | |||
2462 | new_scheme = parameter_s.strip() |
|
2465 | new_scheme = parameter_s.strip() | |
2463 | if not new_scheme: |
|
2466 | if not new_scheme: | |
2464 | raise UsageError( |
|
2467 | raise UsageError( | |
2465 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2468 | "%colors: you must specify a color scheme. See '%colors?'") | |
2466 | return |
|
2469 | return | |
2467 | # local shortcut |
|
2470 | # local shortcut | |
2468 | shell = self.shell |
|
2471 | shell = self.shell | |
2469 |
|
2472 | |||
2470 | import IPython.utils.rlineimpl as readline |
|
2473 | import IPython.utils.rlineimpl as readline | |
2471 |
|
2474 | |||
2472 | if not readline.have_readline and sys.platform == "win32": |
|
2475 | if not readline.have_readline and sys.platform == "win32": | |
2473 | msg = """\ |
|
2476 | msg = """\ | |
2474 | Proper color support under MS Windows requires the pyreadline library. |
|
2477 | Proper color support under MS Windows requires the pyreadline library. | |
2475 | You can find it at: |
|
2478 | You can find it at: | |
2476 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2479 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2477 | Gary's readline needs the ctypes module, from: |
|
2480 | Gary's readline needs the ctypes module, from: | |
2478 | http://starship.python.net/crew/theller/ctypes |
|
2481 | http://starship.python.net/crew/theller/ctypes | |
2479 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2482 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2480 |
|
2483 | |||
2481 | Defaulting color scheme to 'NoColor'""" |
|
2484 | Defaulting color scheme to 'NoColor'""" | |
2482 | new_scheme = 'NoColor' |
|
2485 | new_scheme = 'NoColor' | |
2483 | warn(msg) |
|
2486 | warn(msg) | |
2484 |
|
2487 | |||
2485 | # readline option is 0 |
|
2488 | # readline option is 0 | |
2486 | if not shell.has_readline: |
|
2489 | if not shell.has_readline: | |
2487 | new_scheme = 'NoColor' |
|
2490 | new_scheme = 'NoColor' | |
2488 |
|
2491 | |||
2489 | # Set prompt colors |
|
2492 | # Set prompt colors | |
2490 | try: |
|
2493 | try: | |
2491 | shell.outputcache.set_colors(new_scheme) |
|
2494 | shell.outputcache.set_colors(new_scheme) | |
2492 | except: |
|
2495 | except: | |
2493 | color_switch_err('prompt') |
|
2496 | color_switch_err('prompt') | |
2494 | else: |
|
2497 | else: | |
2495 |
shell |
|
2498 | shell.colors = \ | |
2496 | shell.outputcache.color_table.active_scheme_name |
|
2499 | shell.outputcache.color_table.active_scheme_name | |
2497 | # Set exception colors |
|
2500 | # Set exception colors | |
2498 | try: |
|
2501 | try: | |
2499 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2502 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2500 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2503 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2501 | except: |
|
2504 | except: | |
2502 | color_switch_err('exception') |
|
2505 | color_switch_err('exception') | |
2503 |
|
2506 | |||
2504 | # threaded shells use a verbose traceback in sys.excepthook |
|
2507 | # threaded shells use a verbose traceback in sys.excepthook | |
2505 | if shell.isthreaded: |
|
2508 | if shell.isthreaded: | |
2506 | try: |
|
2509 | try: | |
2507 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2510 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2508 | except: |
|
2511 | except: | |
2509 | color_switch_err('system exception handler') |
|
2512 | color_switch_err('system exception handler') | |
2510 |
|
2513 | |||
2511 | # Set info (for 'object?') colors |
|
2514 | # Set info (for 'object?') colors | |
2512 |
if shell. |
|
2515 | if shell.color_info: | |
2513 | try: |
|
2516 | try: | |
2514 | shell.inspector.set_active_scheme(new_scheme) |
|
2517 | shell.inspector.set_active_scheme(new_scheme) | |
2515 | except: |
|
2518 | except: | |
2516 | color_switch_err('object inspector') |
|
2519 | color_switch_err('object inspector') | |
2517 | else: |
|
2520 | else: | |
2518 | shell.inspector.set_active_scheme('NoColor') |
|
2521 | shell.inspector.set_active_scheme('NoColor') | |
2519 |
|
2522 | |||
2520 | def magic_color_info(self,parameter_s = ''): |
|
2523 | def magic_color_info(self,parameter_s = ''): | |
2521 | """Toggle color_info. |
|
2524 | """Toggle color_info. | |
2522 |
|
2525 | |||
2523 | The color_info configuration parameter controls whether colors are |
|
2526 | The color_info configuration parameter controls whether colors are | |
2524 | used for displaying object details (by things like %psource, %pfile or |
|
2527 | used for displaying object details (by things like %psource, %pfile or | |
2525 | the '?' system). This function toggles this value with each call. |
|
2528 | the '?' system). This function toggles this value with each call. | |
2526 |
|
2529 | |||
2527 | Note that unless you have a fairly recent pager (less works better |
|
2530 | Note that unless you have a fairly recent pager (less works better | |
2528 | than more) in your system, using colored object information displays |
|
2531 | than more) in your system, using colored object information displays | |
2529 | will not work properly. Test it and see.""" |
|
2532 | will not work properly. Test it and see.""" | |
2530 |
|
2533 | |||
2531 |
self.shell. |
|
2534 | self.shell.color_info = not self.shell.color_info | |
2532 |
self.magic_colors(self.shell. |
|
2535 | self.magic_colors(self.shell.colors) | |
2533 | print 'Object introspection functions have now coloring:', |
|
2536 | print 'Object introspection functions have now coloring:', | |
2534 |
print ['OFF','ON'][self.shell. |
|
2537 | print ['OFF','ON'][int(self.shell.color_info)] | |
2535 |
|
2538 | |||
2536 | def magic_Pprint(self, parameter_s=''): |
|
2539 | def magic_Pprint(self, parameter_s=''): | |
2537 | """Toggle pretty printing on/off.""" |
|
2540 | """Toggle pretty printing on/off.""" | |
2538 |
|
2541 | |||
2539 |
self.shell |
|
2542 | self.shell.pprint = 1 - self.shell.pprint | |
2540 | print 'Pretty printing has been turned', \ |
|
2543 | print 'Pretty printing has been turned', \ | |
2541 |
['OFF','ON'][self.shell. |
|
2544 | ['OFF','ON'][self.shell.pprint] | |
2542 |
|
2545 | |||
2543 | def magic_exit(self, parameter_s=''): |
|
2546 | def magic_exit(self, parameter_s=''): | |
2544 | """Exit IPython, confirming if configured to do so. |
|
2547 | """Exit IPython, confirming if configured to do so. | |
2545 |
|
2548 | |||
2546 | You can configure whether IPython asks for confirmation upon exit by |
|
2549 | You can configure whether IPython asks for confirmation upon exit by | |
2547 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2550 | setting the confirm_exit flag in the ipythonrc file.""" | |
2548 |
|
2551 | |||
2549 | self.shell.exit() |
|
2552 | self.shell.exit() | |
2550 |
|
2553 | |||
2551 | def magic_quit(self, parameter_s=''): |
|
2554 | def magic_quit(self, parameter_s=''): | |
2552 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2555 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2553 |
|
2556 | |||
2554 | self.shell.exit() |
|
2557 | self.shell.exit() | |
2555 |
|
2558 | |||
2556 | def magic_Exit(self, parameter_s=''): |
|
2559 | def magic_Exit(self, parameter_s=''): | |
2557 | """Exit IPython without confirmation.""" |
|
2560 | """Exit IPython without confirmation.""" | |
2558 |
|
2561 | |||
2559 | self.shell.ask_exit() |
|
2562 | self.shell.ask_exit() | |
2560 |
|
2563 | |||
2561 | #...................................................................... |
|
2564 | #...................................................................... | |
2562 | # Functions to implement unix shell-type things |
|
2565 | # Functions to implement unix shell-type things | |
2563 |
|
2566 | |||
2564 | @testdec.skip_doctest |
|
2567 | @testdec.skip_doctest | |
2565 | def magic_alias(self, parameter_s = ''): |
|
2568 | def magic_alias(self, parameter_s = ''): | |
2566 | """Define an alias for a system command. |
|
2569 | """Define an alias for a system command. | |
2567 |
|
2570 | |||
2568 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2571 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2569 |
|
2572 | |||
2570 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2573 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2571 | params' (from your underlying operating system). |
|
2574 | params' (from your underlying operating system). | |
2572 |
|
2575 | |||
2573 | Aliases have lower precedence than magic functions and Python normal |
|
2576 | Aliases have lower precedence than magic functions and Python normal | |
2574 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2577 | variables, so if 'foo' is both a Python variable and an alias, the | |
2575 | alias can not be executed until 'del foo' removes the Python variable. |
|
2578 | alias can not be executed until 'del foo' removes the Python variable. | |
2576 |
|
2579 | |||
2577 | You can use the %l specifier in an alias definition to represent the |
|
2580 | You can use the %l specifier in an alias definition to represent the | |
2578 | whole line when the alias is called. For example: |
|
2581 | whole line when the alias is called. For example: | |
2579 |
|
2582 | |||
2580 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2583 | In [2]: alias all echo "Input in brackets: <%l>" | |
2581 | In [3]: all hello world |
|
2584 | In [3]: all hello world | |
2582 | Input in brackets: <hello world> |
|
2585 | Input in brackets: <hello world> | |
2583 |
|
2586 | |||
2584 | You can also define aliases with parameters using %s specifiers (one |
|
2587 | You can also define aliases with parameters using %s specifiers (one | |
2585 | per parameter): |
|
2588 | per parameter): | |
2586 |
|
2589 | |||
2587 | In [1]: alias parts echo first %s second %s |
|
2590 | In [1]: alias parts echo first %s second %s | |
2588 | In [2]: %parts A B |
|
2591 | In [2]: %parts A B | |
2589 | first A second B |
|
2592 | first A second B | |
2590 | In [3]: %parts A |
|
2593 | In [3]: %parts A | |
2591 | Incorrect number of arguments: 2 expected. |
|
2594 | Incorrect number of arguments: 2 expected. | |
2592 | parts is an alias to: 'echo first %s second %s' |
|
2595 | parts is an alias to: 'echo first %s second %s' | |
2593 |
|
2596 | |||
2594 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2597 | Note that %l and %s are mutually exclusive. You can only use one or | |
2595 | the other in your aliases. |
|
2598 | the other in your aliases. | |
2596 |
|
2599 | |||
2597 | Aliases expand Python variables just like system calls using ! or !! |
|
2600 | Aliases expand Python variables just like system calls using ! or !! | |
2598 | do: all expressions prefixed with '$' get expanded. For details of |
|
2601 | do: all expressions prefixed with '$' get expanded. For details of | |
2599 | the semantic rules, see PEP-215: |
|
2602 | the semantic rules, see PEP-215: | |
2600 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2603 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2601 | IPython for variable expansion. If you want to access a true shell |
|
2604 | IPython for variable expansion. If you want to access a true shell | |
2602 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2605 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2603 |
|
2606 | |||
2604 | In [6]: alias show echo |
|
2607 | In [6]: alias show echo | |
2605 | In [7]: PATH='A Python string' |
|
2608 | In [7]: PATH='A Python string' | |
2606 | In [8]: show $PATH |
|
2609 | In [8]: show $PATH | |
2607 | A Python string |
|
2610 | A Python string | |
2608 | In [9]: show $$PATH |
|
2611 | In [9]: show $$PATH | |
2609 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2612 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2610 |
|
2613 | |||
2611 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2614 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2612 | and %rehashx functions, which automatically create aliases for the |
|
2615 | and %rehashx functions, which automatically create aliases for the | |
2613 | contents of your $PATH. |
|
2616 | contents of your $PATH. | |
2614 |
|
2617 | |||
2615 | If called with no parameters, %alias prints the current alias table.""" |
|
2618 | If called with no parameters, %alias prints the current alias table.""" | |
2616 |
|
2619 | |||
2617 | par = parameter_s.strip() |
|
2620 | par = parameter_s.strip() | |
2618 | if not par: |
|
2621 | if not par: | |
2619 | stored = self.db.get('stored_aliases', {} ) |
|
2622 | stored = self.db.get('stored_aliases', {} ) | |
2620 | atab = self.shell.alias_table |
|
2623 | atab = self.shell.alias_table | |
2621 | aliases = atab.keys() |
|
2624 | aliases = atab.keys() | |
2622 | aliases.sort() |
|
2625 | aliases.sort() | |
2623 | res = [] |
|
2626 | res = [] | |
2624 | showlast = [] |
|
2627 | showlast = [] | |
2625 | for alias in aliases: |
|
2628 | for alias in aliases: | |
2626 | special = False |
|
2629 | special = False | |
2627 | try: |
|
2630 | try: | |
2628 | tgt = atab[alias][1] |
|
2631 | tgt = atab[alias][1] | |
2629 | except (TypeError, AttributeError): |
|
2632 | except (TypeError, AttributeError): | |
2630 | # unsubscriptable? probably a callable |
|
2633 | # unsubscriptable? probably a callable | |
2631 | tgt = atab[alias] |
|
2634 | tgt = atab[alias] | |
2632 | special = True |
|
2635 | special = True | |
2633 | # 'interesting' aliases |
|
2636 | # 'interesting' aliases | |
2634 | if (alias in stored or |
|
2637 | if (alias in stored or | |
2635 | special or |
|
2638 | special or | |
2636 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2639 | alias.lower() != os.path.splitext(tgt)[0].lower() or | |
2637 | ' ' in tgt): |
|
2640 | ' ' in tgt): | |
2638 | showlast.append((alias, tgt)) |
|
2641 | showlast.append((alias, tgt)) | |
2639 | else: |
|
2642 | else: | |
2640 | res.append((alias, tgt )) |
|
2643 | res.append((alias, tgt )) | |
2641 |
|
2644 | |||
2642 | # show most interesting aliases last |
|
2645 | # show most interesting aliases last | |
2643 | res.extend(showlast) |
|
2646 | res.extend(showlast) | |
2644 | print "Total number of aliases:",len(aliases) |
|
2647 | print "Total number of aliases:",len(aliases) | |
2645 | return res |
|
2648 | return res | |
2646 | try: |
|
2649 | try: | |
2647 | alias,cmd = par.split(None,1) |
|
2650 | alias,cmd = par.split(None,1) | |
2648 | except: |
|
2651 | except: | |
2649 | print oinspect.getdoc(self.magic_alias) |
|
2652 | print oinspect.getdoc(self.magic_alias) | |
2650 | else: |
|
2653 | else: | |
2651 | nargs = cmd.count('%s') |
|
2654 | nargs = cmd.count('%s') | |
2652 | if nargs>0 and cmd.find('%l')>=0: |
|
2655 | if nargs>0 and cmd.find('%l')>=0: | |
2653 | error('The %s and %l specifiers are mutually exclusive ' |
|
2656 | error('The %s and %l specifiers are mutually exclusive ' | |
2654 | 'in alias definitions.') |
|
2657 | 'in alias definitions.') | |
2655 | else: # all looks OK |
|
2658 | else: # all looks OK | |
2656 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2659 | self.shell.alias_table[alias] = (nargs,cmd) | |
2657 | self.shell.alias_table_validate(verbose=0) |
|
2660 | self.shell.alias_table_validate(verbose=0) | |
2658 | # end magic_alias |
|
2661 | # end magic_alias | |
2659 |
|
2662 | |||
2660 | def magic_unalias(self, parameter_s = ''): |
|
2663 | def magic_unalias(self, parameter_s = ''): | |
2661 | """Remove an alias""" |
|
2664 | """Remove an alias""" | |
2662 |
|
2665 | |||
2663 | aname = parameter_s.strip() |
|
2666 | aname = parameter_s.strip() | |
2664 | if aname in self.shell.alias_table: |
|
2667 | if aname in self.shell.alias_table: | |
2665 | del self.shell.alias_table[aname] |
|
2668 | del self.shell.alias_table[aname] | |
2666 | stored = self.db.get('stored_aliases', {} ) |
|
2669 | stored = self.db.get('stored_aliases', {} ) | |
2667 | if aname in stored: |
|
2670 | if aname in stored: | |
2668 | print "Removing %stored alias",aname |
|
2671 | print "Removing %stored alias",aname | |
2669 | del stored[aname] |
|
2672 | del stored[aname] | |
2670 | self.db['stored_aliases'] = stored |
|
2673 | self.db['stored_aliases'] = stored | |
2671 |
|
2674 | |||
2672 |
|
2675 | |||
2673 | def magic_rehashx(self, parameter_s = ''): |
|
2676 | def magic_rehashx(self, parameter_s = ''): | |
2674 | """Update the alias table with all executable files in $PATH. |
|
2677 | """Update the alias table with all executable files in $PATH. | |
2675 |
|
2678 | |||
2676 | This version explicitly checks that every entry in $PATH is a file |
|
2679 | This version explicitly checks that every entry in $PATH is a file | |
2677 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2680 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2678 |
|
2681 | |||
2679 | Under Windows, it checks executability as a match agains a |
|
2682 | Under Windows, it checks executability as a match agains a | |
2680 | '|'-separated string of extensions, stored in the IPython config |
|
2683 | '|'-separated string of extensions, stored in the IPython config | |
2681 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2684 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2682 |
|
2685 | |||
2683 | This function also resets the root module cache of module completer, |
|
2686 | This function also resets the root module cache of module completer, | |
2684 | used on slow filesystems. |
|
2687 | used on slow filesystems. | |
2685 | """ |
|
2688 | """ | |
2686 |
|
||||
2687 |
|
||||
2688 | ip = self.api |
|
|||
2689 |
|
2689 | |||
2690 | # for the benefit of module completer in ipy_completers.py |
|
2690 | # for the benefit of module completer in ipy_completers.py | |
2691 |
del |
|
2691 | del self.db['rootmodules'] | |
2692 |
|
2692 | |||
2693 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2693 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2694 | os.environ.get('PATH','').split(os.pathsep)] |
|
2694 | os.environ.get('PATH','').split(os.pathsep)] | |
2695 | path = filter(os.path.isdir,path) |
|
2695 | path = filter(os.path.isdir,path) | |
2696 |
|
2696 | |||
2697 | alias_table = self.shell.alias_table |
|
2697 | alias_table = self.shell.alias_table | |
2698 | syscmdlist = [] |
|
2698 | syscmdlist = [] | |
2699 | if os.name == 'posix': |
|
2699 | if os.name == 'posix': | |
2700 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2700 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2701 | os.access(fname,os.X_OK) |
|
2701 | os.access(fname,os.X_OK) | |
2702 | else: |
|
2702 | else: | |
2703 |
|
2703 | |||
2704 | try: |
|
2704 | try: | |
2705 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2705 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2706 | except KeyError: |
|
2706 | except KeyError: | |
2707 | winext = 'exe|com|bat|py' |
|
2707 | winext = 'exe|com|bat|py' | |
2708 | if 'py' not in winext: |
|
2708 | if 'py' not in winext: | |
2709 | winext += '|py' |
|
2709 | winext += '|py' | |
2710 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2710 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2711 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2711 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2712 | savedir = os.getcwd() |
|
2712 | savedir = os.getcwd() | |
2713 | try: |
|
2713 | try: | |
2714 | # write the whole loop for posix/Windows so we don't have an if in |
|
2714 | # write the whole loop for posix/Windows so we don't have an if in | |
2715 | # the innermost part |
|
2715 | # the innermost part | |
2716 | if os.name == 'posix': |
|
2716 | if os.name == 'posix': | |
2717 | for pdir in path: |
|
2717 | for pdir in path: | |
2718 | os.chdir(pdir) |
|
2718 | os.chdir(pdir) | |
2719 | for ff in os.listdir(pdir): |
|
2719 | for ff in os.listdir(pdir): | |
2720 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2720 | if isexec(ff) and ff not in self.shell.no_alias: | |
2721 | # each entry in the alias table must be (N,name), |
|
2721 | # each entry in the alias table must be (N,name), | |
2722 | # where N is the number of positional arguments of the |
|
2722 | # where N is the number of positional arguments of the | |
2723 | # alias. |
|
2723 | # alias. | |
2724 | # Dots will be removed from alias names, since ipython |
|
2724 | # Dots will be removed from alias names, since ipython | |
2725 | # assumes names with dots to be python code |
|
2725 | # assumes names with dots to be python code | |
2726 | alias_table[ff.replace('.','')] = (0,ff) |
|
2726 | alias_table[ff.replace('.','')] = (0,ff) | |
2727 | syscmdlist.append(ff) |
|
2727 | syscmdlist.append(ff) | |
2728 | else: |
|
2728 | else: | |
2729 | for pdir in path: |
|
2729 | for pdir in path: | |
2730 | os.chdir(pdir) |
|
2730 | os.chdir(pdir) | |
2731 | for ff in os.listdir(pdir): |
|
2731 | for ff in os.listdir(pdir): | |
2732 | base, ext = os.path.splitext(ff) |
|
2732 | base, ext = os.path.splitext(ff) | |
2733 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2733 | if isexec(ff) and base.lower() not in self.shell.no_alias: | |
2734 | if ext.lower() == '.exe': |
|
2734 | if ext.lower() == '.exe': | |
2735 | ff = base |
|
2735 | ff = base | |
2736 | alias_table[base.lower().replace('.','')] = (0,ff) |
|
2736 | alias_table[base.lower().replace('.','')] = (0,ff) | |
2737 | syscmdlist.append(ff) |
|
2737 | syscmdlist.append(ff) | |
2738 | # Make sure the alias table doesn't contain keywords or builtins |
|
2738 | # Make sure the alias table doesn't contain keywords or builtins | |
2739 | self.shell.alias_table_validate() |
|
2739 | self.shell.alias_table_validate() | |
2740 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2740 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2741 | # modified aliases since %rehashx will probably clobber them |
|
2741 | # modified aliases since %rehashx will probably clobber them | |
2742 |
|
2742 | |||
2743 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2743 | # no, we don't want them. if %rehashx clobbers them, good, | |
2744 | # we'll probably get better versions |
|
2744 | # we'll probably get better versions | |
2745 | # self.shell.init_auto_alias() |
|
2745 | # self.shell.init_auto_alias() | |
2746 |
db = |
|
2746 | db = self.db | |
2747 | db['syscmdlist'] = syscmdlist |
|
2747 | db['syscmdlist'] = syscmdlist | |
2748 | finally: |
|
2748 | finally: | |
2749 | os.chdir(savedir) |
|
2749 | os.chdir(savedir) | |
2750 |
|
2750 | |||
2751 | def magic_pwd(self, parameter_s = ''): |
|
2751 | def magic_pwd(self, parameter_s = ''): | |
2752 | """Return the current working directory path.""" |
|
2752 | """Return the current working directory path.""" | |
2753 | return os.getcwd() |
|
2753 | return os.getcwd() | |
2754 |
|
2754 | |||
2755 | def magic_cd(self, parameter_s=''): |
|
2755 | def magic_cd(self, parameter_s=''): | |
2756 | """Change the current working directory. |
|
2756 | """Change the current working directory. | |
2757 |
|
2757 | |||
2758 | This command automatically maintains an internal list of directories |
|
2758 | This command automatically maintains an internal list of directories | |
2759 | you visit during your IPython session, in the variable _dh. The |
|
2759 | you visit during your IPython session, in the variable _dh. The | |
2760 | command %dhist shows this history nicely formatted. You can also |
|
2760 | command %dhist shows this history nicely formatted. You can also | |
2761 | do 'cd -<tab>' to see directory history conveniently. |
|
2761 | do 'cd -<tab>' to see directory history conveniently. | |
2762 |
|
2762 | |||
2763 | Usage: |
|
2763 | Usage: | |
2764 |
|
2764 | |||
2765 | cd 'dir': changes to directory 'dir'. |
|
2765 | cd 'dir': changes to directory 'dir'. | |
2766 |
|
2766 | |||
2767 | cd -: changes to the last visited directory. |
|
2767 | cd -: changes to the last visited directory. | |
2768 |
|
2768 | |||
2769 | cd -<n>: changes to the n-th directory in the directory history. |
|
2769 | cd -<n>: changes to the n-th directory in the directory history. | |
2770 |
|
2770 | |||
2771 | cd --foo: change to directory that matches 'foo' in history |
|
2771 | cd --foo: change to directory that matches 'foo' in history | |
2772 |
|
2772 | |||
2773 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2773 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2774 | (note: cd <bookmark_name> is enough if there is no |
|
2774 | (note: cd <bookmark_name> is enough if there is no | |
2775 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2775 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2776 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2776 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2777 |
|
2777 | |||
2778 | Options: |
|
2778 | Options: | |
2779 |
|
2779 | |||
2780 | -q: quiet. Do not print the working directory after the cd command is |
|
2780 | -q: quiet. Do not print the working directory after the cd command is | |
2781 | executed. By default IPython's cd command does print this directory, |
|
2781 | executed. By default IPython's cd command does print this directory, | |
2782 | since the default prompts do not display path information. |
|
2782 | since the default prompts do not display path information. | |
2783 |
|
2783 | |||
2784 | Note that !cd doesn't work for this purpose because the shell where |
|
2784 | Note that !cd doesn't work for this purpose because the shell where | |
2785 | !command runs is immediately discarded after executing 'command'.""" |
|
2785 | !command runs is immediately discarded after executing 'command'.""" | |
2786 |
|
2786 | |||
2787 | parameter_s = parameter_s.strip() |
|
2787 | parameter_s = parameter_s.strip() | |
2788 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2788 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2789 |
|
2789 | |||
2790 | oldcwd = os.getcwd() |
|
2790 | oldcwd = os.getcwd() | |
2791 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2791 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2792 | # jump in directory history by number |
|
2792 | # jump in directory history by number | |
2793 | if numcd: |
|
2793 | if numcd: | |
2794 | nn = int(numcd.group(2)) |
|
2794 | nn = int(numcd.group(2)) | |
2795 | try: |
|
2795 | try: | |
2796 | ps = self.shell.user_ns['_dh'][nn] |
|
2796 | ps = self.shell.user_ns['_dh'][nn] | |
2797 | except IndexError: |
|
2797 | except IndexError: | |
2798 | print 'The requested directory does not exist in history.' |
|
2798 | print 'The requested directory does not exist in history.' | |
2799 | return |
|
2799 | return | |
2800 | else: |
|
2800 | else: | |
2801 | opts = {} |
|
2801 | opts = {} | |
2802 | elif parameter_s.startswith('--'): |
|
2802 | elif parameter_s.startswith('--'): | |
2803 | ps = None |
|
2803 | ps = None | |
2804 | fallback = None |
|
2804 | fallback = None | |
2805 | pat = parameter_s[2:] |
|
2805 | pat = parameter_s[2:] | |
2806 | dh = self.shell.user_ns['_dh'] |
|
2806 | dh = self.shell.user_ns['_dh'] | |
2807 | # first search only by basename (last component) |
|
2807 | # first search only by basename (last component) | |
2808 | for ent in reversed(dh): |
|
2808 | for ent in reversed(dh): | |
2809 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2809 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2810 | ps = ent |
|
2810 | ps = ent | |
2811 | break |
|
2811 | break | |
2812 |
|
2812 | |||
2813 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2813 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2814 | fallback = ent |
|
2814 | fallback = ent | |
2815 |
|
2815 | |||
2816 | # if we have no last part match, pick the first full path match |
|
2816 | # if we have no last part match, pick the first full path match | |
2817 | if ps is None: |
|
2817 | if ps is None: | |
2818 | ps = fallback |
|
2818 | ps = fallback | |
2819 |
|
2819 | |||
2820 | if ps is None: |
|
2820 | if ps is None: | |
2821 | print "No matching entry in directory history" |
|
2821 | print "No matching entry in directory history" | |
2822 | return |
|
2822 | return | |
2823 | else: |
|
2823 | else: | |
2824 | opts = {} |
|
2824 | opts = {} | |
2825 |
|
2825 | |||
2826 |
|
2826 | |||
2827 | else: |
|
2827 | else: | |
2828 | #turn all non-space-escaping backslashes to slashes, |
|
2828 | #turn all non-space-escaping backslashes to slashes, | |
2829 | # for c:\windows\directory\names\ |
|
2829 | # for c:\windows\directory\names\ | |
2830 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2830 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2831 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2831 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2832 | # jump to previous |
|
2832 | # jump to previous | |
2833 | if ps == '-': |
|
2833 | if ps == '-': | |
2834 | try: |
|
2834 | try: | |
2835 | ps = self.shell.user_ns['_dh'][-2] |
|
2835 | ps = self.shell.user_ns['_dh'][-2] | |
2836 | except IndexError: |
|
2836 | except IndexError: | |
2837 | raise UsageError('%cd -: No previous directory to change to.') |
|
2837 | raise UsageError('%cd -: No previous directory to change to.') | |
2838 | # jump to bookmark if needed |
|
2838 | # jump to bookmark if needed | |
2839 | else: |
|
2839 | else: | |
2840 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2840 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2841 | bkms = self.db.get('bookmarks', {}) |
|
2841 | bkms = self.db.get('bookmarks', {}) | |
2842 |
|
2842 | |||
2843 | if bkms.has_key(ps): |
|
2843 | if bkms.has_key(ps): | |
2844 | target = bkms[ps] |
|
2844 | target = bkms[ps] | |
2845 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2845 | print '(bookmark:%s) -> %s' % (ps,target) | |
2846 | ps = target |
|
2846 | ps = target | |
2847 | else: |
|
2847 | else: | |
2848 | if opts.has_key('b'): |
|
2848 | if opts.has_key('b'): | |
2849 | raise UsageError("Bookmark '%s' not found. " |
|
2849 | raise UsageError("Bookmark '%s' not found. " | |
2850 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2850 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2851 |
|
2851 | |||
2852 | # at this point ps should point to the target dir |
|
2852 | # at this point ps should point to the target dir | |
2853 | if ps: |
|
2853 | if ps: | |
2854 | try: |
|
2854 | try: | |
2855 | os.chdir(os.path.expanduser(ps)) |
|
2855 | os.chdir(os.path.expanduser(ps)) | |
2856 |
if self.shell. |
|
2856 | if self.shell.term_title: | |
2857 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2857 | platutils.set_term_title('IPython: ' + abbrev_cwd()) | |
2858 | platutils.set_term_title('IPy ' + abbrev_cwd()) |
|
|||
2859 | except OSError: |
|
2858 | except OSError: | |
2860 | print sys.exc_info()[1] |
|
2859 | print sys.exc_info()[1] | |
2861 | else: |
|
2860 | else: | |
2862 | cwd = os.getcwd() |
|
2861 | cwd = os.getcwd() | |
2863 | dhist = self.shell.user_ns['_dh'] |
|
2862 | dhist = self.shell.user_ns['_dh'] | |
2864 | if oldcwd != cwd: |
|
2863 | if oldcwd != cwd: | |
2865 | dhist.append(cwd) |
|
2864 | dhist.append(cwd) | |
2866 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2865 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2867 |
|
2866 | |||
2868 | else: |
|
2867 | else: | |
2869 | os.chdir(self.shell.home_dir) |
|
2868 | os.chdir(self.shell.home_dir) | |
2870 |
if self.shell. |
|
2869 | if self.shell.term_title: | |
2871 |
platutils.set_term_title( |
|
2870 | platutils.set_term_title('IPython: ' + '~') | |
2872 | cwd = os.getcwd() |
|
2871 | cwd = os.getcwd() | |
2873 | dhist = self.shell.user_ns['_dh'] |
|
2872 | dhist = self.shell.user_ns['_dh'] | |
2874 |
|
2873 | |||
2875 | if oldcwd != cwd: |
|
2874 | if oldcwd != cwd: | |
2876 | dhist.append(cwd) |
|
2875 | dhist.append(cwd) | |
2877 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2876 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2878 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2877 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2879 | print self.shell.user_ns['_dh'][-1] |
|
2878 | print self.shell.user_ns['_dh'][-1] | |
2880 |
|
2879 | |||
2881 |
|
2880 | |||
2882 | def magic_env(self, parameter_s=''): |
|
2881 | def magic_env(self, parameter_s=''): | |
2883 | """List environment variables.""" |
|
2882 | """List environment variables.""" | |
2884 |
|
2883 | |||
2885 | return os.environ.data |
|
2884 | return os.environ.data | |
2886 |
|
2885 | |||
2887 | def magic_pushd(self, parameter_s=''): |
|
2886 | def magic_pushd(self, parameter_s=''): | |
2888 | """Place the current dir on stack and change directory. |
|
2887 | """Place the current dir on stack and change directory. | |
2889 |
|
2888 | |||
2890 | Usage:\\ |
|
2889 | Usage:\\ | |
2891 | %pushd ['dirname'] |
|
2890 | %pushd ['dirname'] | |
2892 | """ |
|
2891 | """ | |
2893 |
|
2892 | |||
2894 | dir_s = self.shell.dir_stack |
|
2893 | dir_s = self.shell.dir_stack | |
2895 | tgt = os.path.expanduser(parameter_s) |
|
2894 | tgt = os.path.expanduser(parameter_s) | |
2896 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2895 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2897 | if tgt: |
|
2896 | if tgt: | |
2898 | self.magic_cd(parameter_s) |
|
2897 | self.magic_cd(parameter_s) | |
2899 | dir_s.insert(0,cwd) |
|
2898 | dir_s.insert(0,cwd) | |
2900 | return self.magic_dirs() |
|
2899 | return self.magic_dirs() | |
2901 |
|
2900 | |||
2902 | def magic_popd(self, parameter_s=''): |
|
2901 | def magic_popd(self, parameter_s=''): | |
2903 | """Change to directory popped off the top of the stack. |
|
2902 | """Change to directory popped off the top of the stack. | |
2904 | """ |
|
2903 | """ | |
2905 | if not self.shell.dir_stack: |
|
2904 | if not self.shell.dir_stack: | |
2906 | raise UsageError("%popd on empty stack") |
|
2905 | raise UsageError("%popd on empty stack") | |
2907 | top = self.shell.dir_stack.pop(0) |
|
2906 | top = self.shell.dir_stack.pop(0) | |
2908 | self.magic_cd(top) |
|
2907 | self.magic_cd(top) | |
2909 | print "popd ->",top |
|
2908 | print "popd ->",top | |
2910 |
|
2909 | |||
2911 | def magic_dirs(self, parameter_s=''): |
|
2910 | def magic_dirs(self, parameter_s=''): | |
2912 | """Return the current directory stack.""" |
|
2911 | """Return the current directory stack.""" | |
2913 |
|
2912 | |||
2914 | return self.shell.dir_stack |
|
2913 | return self.shell.dir_stack | |
2915 |
|
2914 | |||
2916 | def magic_dhist(self, parameter_s=''): |
|
2915 | def magic_dhist(self, parameter_s=''): | |
2917 | """Print your history of visited directories. |
|
2916 | """Print your history of visited directories. | |
2918 |
|
2917 | |||
2919 | %dhist -> print full history\\ |
|
2918 | %dhist -> print full history\\ | |
2920 | %dhist n -> print last n entries only\\ |
|
2919 | %dhist n -> print last n entries only\\ | |
2921 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2920 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2922 |
|
2921 | |||
2923 | This history is automatically maintained by the %cd command, and |
|
2922 | This history is automatically maintained by the %cd command, and | |
2924 | always available as the global list variable _dh. You can use %cd -<n> |
|
2923 | always available as the global list variable _dh. You can use %cd -<n> | |
2925 | to go to directory number <n>. |
|
2924 | to go to directory number <n>. | |
2926 |
|
2925 | |||
2927 | Note that most of time, you should view directory history by entering |
|
2926 | Note that most of time, you should view directory history by entering | |
2928 | cd -<TAB>. |
|
2927 | cd -<TAB>. | |
2929 |
|
2928 | |||
2930 | """ |
|
2929 | """ | |
2931 |
|
2930 | |||
2932 | dh = self.shell.user_ns['_dh'] |
|
2931 | dh = self.shell.user_ns['_dh'] | |
2933 | if parameter_s: |
|
2932 | if parameter_s: | |
2934 | try: |
|
2933 | try: | |
2935 | args = map(int,parameter_s.split()) |
|
2934 | args = map(int,parameter_s.split()) | |
2936 | except: |
|
2935 | except: | |
2937 | self.arg_err(Magic.magic_dhist) |
|
2936 | self.arg_err(Magic.magic_dhist) | |
2938 | return |
|
2937 | return | |
2939 | if len(args) == 1: |
|
2938 | if len(args) == 1: | |
2940 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2939 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2941 | elif len(args) == 2: |
|
2940 | elif len(args) == 2: | |
2942 | ini,fin = args |
|
2941 | ini,fin = args | |
2943 | else: |
|
2942 | else: | |
2944 | self.arg_err(Magic.magic_dhist) |
|
2943 | self.arg_err(Magic.magic_dhist) | |
2945 | return |
|
2944 | return | |
2946 | else: |
|
2945 | else: | |
2947 | ini,fin = 0,len(dh) |
|
2946 | ini,fin = 0,len(dh) | |
2948 | nlprint(dh, |
|
2947 | nlprint(dh, | |
2949 | header = 'Directory history (kept in _dh)', |
|
2948 | header = 'Directory history (kept in _dh)', | |
2950 | start=ini,stop=fin) |
|
2949 | start=ini,stop=fin) | |
2951 |
|
2950 | |||
2952 | @testdec.skip_doctest |
|
2951 | @testdec.skip_doctest | |
2953 | def magic_sc(self, parameter_s=''): |
|
2952 | def magic_sc(self, parameter_s=''): | |
2954 | """Shell capture - execute a shell command and capture its output. |
|
2953 | """Shell capture - execute a shell command and capture its output. | |
2955 |
|
2954 | |||
2956 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2955 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2957 |
|
2956 | |||
2958 | You should use the form 'var = !command' instead. Example: |
|
2957 | You should use the form 'var = !command' instead. Example: | |
2959 |
|
2958 | |||
2960 | "%sc -l myfiles = ls ~" should now be written as |
|
2959 | "%sc -l myfiles = ls ~" should now be written as | |
2961 |
|
2960 | |||
2962 | "myfiles = !ls ~" |
|
2961 | "myfiles = !ls ~" | |
2963 |
|
2962 | |||
2964 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2963 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2965 | below. |
|
2964 | below. | |
2966 |
|
2965 | |||
2967 | -- |
|
2966 | -- | |
2968 | %sc [options] varname=command |
|
2967 | %sc [options] varname=command | |
2969 |
|
2968 | |||
2970 | IPython will run the given command using commands.getoutput(), and |
|
2969 | IPython will run the given command using commands.getoutput(), and | |
2971 | will then update the user's interactive namespace with a variable |
|
2970 | will then update the user's interactive namespace with a variable | |
2972 | called varname, containing the value of the call. Your command can |
|
2971 | called varname, containing the value of the call. Your command can | |
2973 | contain shell wildcards, pipes, etc. |
|
2972 | contain shell wildcards, pipes, etc. | |
2974 |
|
2973 | |||
2975 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2974 | The '=' sign in the syntax is mandatory, and the variable name you | |
2976 | supply must follow Python's standard conventions for valid names. |
|
2975 | supply must follow Python's standard conventions for valid names. | |
2977 |
|
2976 | |||
2978 | (A special format without variable name exists for internal use) |
|
2977 | (A special format without variable name exists for internal use) | |
2979 |
|
2978 | |||
2980 | Options: |
|
2979 | Options: | |
2981 |
|
2980 | |||
2982 | -l: list output. Split the output on newlines into a list before |
|
2981 | -l: list output. Split the output on newlines into a list before | |
2983 | assigning it to the given variable. By default the output is stored |
|
2982 | assigning it to the given variable. By default the output is stored | |
2984 | as a single string. |
|
2983 | as a single string. | |
2985 |
|
2984 | |||
2986 | -v: verbose. Print the contents of the variable. |
|
2985 | -v: verbose. Print the contents of the variable. | |
2987 |
|
2986 | |||
2988 | In most cases you should not need to split as a list, because the |
|
2987 | In most cases you should not need to split as a list, because the | |
2989 | returned value is a special type of string which can automatically |
|
2988 | returned value is a special type of string which can automatically | |
2990 | provide its contents either as a list (split on newlines) or as a |
|
2989 | provide its contents either as a list (split on newlines) or as a | |
2991 | space-separated string. These are convenient, respectively, either |
|
2990 | space-separated string. These are convenient, respectively, either | |
2992 | for sequential processing or to be passed to a shell command. |
|
2991 | for sequential processing or to be passed to a shell command. | |
2993 |
|
2992 | |||
2994 | For example: |
|
2993 | For example: | |
2995 |
|
2994 | |||
2996 | # all-random |
|
2995 | # all-random | |
2997 |
|
2996 | |||
2998 | # Capture into variable a |
|
2997 | # Capture into variable a | |
2999 | In [1]: sc a=ls *py |
|
2998 | In [1]: sc a=ls *py | |
3000 |
|
2999 | |||
3001 | # a is a string with embedded newlines |
|
3000 | # a is a string with embedded newlines | |
3002 | In [2]: a |
|
3001 | In [2]: a | |
3003 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3002 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
3004 |
|
3003 | |||
3005 | # which can be seen as a list: |
|
3004 | # which can be seen as a list: | |
3006 | In [3]: a.l |
|
3005 | In [3]: a.l | |
3007 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3006 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
3008 |
|
3007 | |||
3009 | # or as a whitespace-separated string: |
|
3008 | # or as a whitespace-separated string: | |
3010 | In [4]: a.s |
|
3009 | In [4]: a.s | |
3011 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3010 | Out[4]: 'setup.py win32_manual_post_install.py' | |
3012 |
|
3011 | |||
3013 | # a.s is useful to pass as a single command line: |
|
3012 | # a.s is useful to pass as a single command line: | |
3014 | In [5]: !wc -l $a.s |
|
3013 | In [5]: !wc -l $a.s | |
3015 | 146 setup.py |
|
3014 | 146 setup.py | |
3016 | 130 win32_manual_post_install.py |
|
3015 | 130 win32_manual_post_install.py | |
3017 | 276 total |
|
3016 | 276 total | |
3018 |
|
3017 | |||
3019 | # while the list form is useful to loop over: |
|
3018 | # while the list form is useful to loop over: | |
3020 | In [6]: for f in a.l: |
|
3019 | In [6]: for f in a.l: | |
3021 | ...: !wc -l $f |
|
3020 | ...: !wc -l $f | |
3022 | ...: |
|
3021 | ...: | |
3023 | 146 setup.py |
|
3022 | 146 setup.py | |
3024 | 130 win32_manual_post_install.py |
|
3023 | 130 win32_manual_post_install.py | |
3025 |
|
3024 | |||
3026 | Similiarly, the lists returned by the -l option are also special, in |
|
3025 | Similiarly, the lists returned by the -l option are also special, in | |
3027 | the sense that you can equally invoke the .s attribute on them to |
|
3026 | the sense that you can equally invoke the .s attribute on them to | |
3028 | automatically get a whitespace-separated string from their contents: |
|
3027 | automatically get a whitespace-separated string from their contents: | |
3029 |
|
3028 | |||
3030 | In [7]: sc -l b=ls *py |
|
3029 | In [7]: sc -l b=ls *py | |
3031 |
|
3030 | |||
3032 | In [8]: b |
|
3031 | In [8]: b | |
3033 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3032 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3034 |
|
3033 | |||
3035 | In [9]: b.s |
|
3034 | In [9]: b.s | |
3036 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3035 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3037 |
|
3036 | |||
3038 | In summary, both the lists and strings used for ouptut capture have |
|
3037 | In summary, both the lists and strings used for ouptut capture have | |
3039 | the following special attributes: |
|
3038 | the following special attributes: | |
3040 |
|
3039 | |||
3041 | .l (or .list) : value as list. |
|
3040 | .l (or .list) : value as list. | |
3042 | .n (or .nlstr): value as newline-separated string. |
|
3041 | .n (or .nlstr): value as newline-separated string. | |
3043 | .s (or .spstr): value as space-separated string. |
|
3042 | .s (or .spstr): value as space-separated string. | |
3044 | """ |
|
3043 | """ | |
3045 |
|
3044 | |||
3046 | opts,args = self.parse_options(parameter_s,'lv') |
|
3045 | opts,args = self.parse_options(parameter_s,'lv') | |
3047 | # Try to get a variable name and command to run |
|
3046 | # Try to get a variable name and command to run | |
3048 | try: |
|
3047 | try: | |
3049 | # the variable name must be obtained from the parse_options |
|
3048 | # the variable name must be obtained from the parse_options | |
3050 | # output, which uses shlex.split to strip options out. |
|
3049 | # output, which uses shlex.split to strip options out. | |
3051 | var,_ = args.split('=',1) |
|
3050 | var,_ = args.split('=',1) | |
3052 | var = var.strip() |
|
3051 | var = var.strip() | |
3053 | # But the the command has to be extracted from the original input |
|
3052 | # But the the command has to be extracted from the original input | |
3054 | # parameter_s, not on what parse_options returns, to avoid the |
|
3053 | # parameter_s, not on what parse_options returns, to avoid the | |
3055 | # quote stripping which shlex.split performs on it. |
|
3054 | # quote stripping which shlex.split performs on it. | |
3056 | _,cmd = parameter_s.split('=',1) |
|
3055 | _,cmd = parameter_s.split('=',1) | |
3057 | except ValueError: |
|
3056 | except ValueError: | |
3058 | var,cmd = '','' |
|
3057 | var,cmd = '','' | |
3059 | # If all looks ok, proceed |
|
3058 | # If all looks ok, proceed | |
3060 | out,err = self.shell.getoutputerror(cmd) |
|
3059 | out,err = self.shell.getoutputerror(cmd) | |
3061 | if err: |
|
3060 | if err: | |
3062 | print >> Term.cerr,err |
|
3061 | print >> Term.cerr,err | |
3063 | if opts.has_key('l'): |
|
3062 | if opts.has_key('l'): | |
3064 | out = SList(out.split('\n')) |
|
3063 | out = SList(out.split('\n')) | |
3065 | else: |
|
3064 | else: | |
3066 | out = LSString(out) |
|
3065 | out = LSString(out) | |
3067 | if opts.has_key('v'): |
|
3066 | if opts.has_key('v'): | |
3068 | print '%s ==\n%s' % (var,pformat(out)) |
|
3067 | print '%s ==\n%s' % (var,pformat(out)) | |
3069 | if var: |
|
3068 | if var: | |
3070 | self.shell.user_ns.update({var:out}) |
|
3069 | self.shell.user_ns.update({var:out}) | |
3071 | else: |
|
3070 | else: | |
3072 | return out |
|
3071 | return out | |
3073 |
|
3072 | |||
3074 | def magic_sx(self, parameter_s=''): |
|
3073 | def magic_sx(self, parameter_s=''): | |
3075 | """Shell execute - run a shell command and capture its output. |
|
3074 | """Shell execute - run a shell command and capture its output. | |
3076 |
|
3075 | |||
3077 | %sx command |
|
3076 | %sx command | |
3078 |
|
3077 | |||
3079 | IPython will run the given command using commands.getoutput(), and |
|
3078 | IPython will run the given command using commands.getoutput(), and | |
3080 | return the result formatted as a list (split on '\\n'). Since the |
|
3079 | return the result formatted as a list (split on '\\n'). Since the | |
3081 | output is _returned_, it will be stored in ipython's regular output |
|
3080 | output is _returned_, it will be stored in ipython's regular output | |
3082 | cache Out[N] and in the '_N' automatic variables. |
|
3081 | cache Out[N] and in the '_N' automatic variables. | |
3083 |
|
3082 | |||
3084 | Notes: |
|
3083 | Notes: | |
3085 |
|
3084 | |||
3086 | 1) If an input line begins with '!!', then %sx is automatically |
|
3085 | 1) If an input line begins with '!!', then %sx is automatically | |
3087 | invoked. That is, while: |
|
3086 | invoked. That is, while: | |
3088 | !ls |
|
3087 | !ls | |
3089 | causes ipython to simply issue system('ls'), typing |
|
3088 | causes ipython to simply issue system('ls'), typing | |
3090 | !!ls |
|
3089 | !!ls | |
3091 | is a shorthand equivalent to: |
|
3090 | is a shorthand equivalent to: | |
3092 | %sx ls |
|
3091 | %sx ls | |
3093 |
|
3092 | |||
3094 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3093 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3095 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3094 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3096 | to process line-oriented shell output via further python commands. |
|
3095 | to process line-oriented shell output via further python commands. | |
3097 | %sc is meant to provide much finer control, but requires more |
|
3096 | %sc is meant to provide much finer control, but requires more | |
3098 | typing. |
|
3097 | typing. | |
3099 |
|
3098 | |||
3100 | 3) Just like %sc -l, this is a list with special attributes: |
|
3099 | 3) Just like %sc -l, this is a list with special attributes: | |
3101 |
|
3100 | |||
3102 | .l (or .list) : value as list. |
|
3101 | .l (or .list) : value as list. | |
3103 | .n (or .nlstr): value as newline-separated string. |
|
3102 | .n (or .nlstr): value as newline-separated string. | |
3104 | .s (or .spstr): value as whitespace-separated string. |
|
3103 | .s (or .spstr): value as whitespace-separated string. | |
3105 |
|
3104 | |||
3106 | This is very useful when trying to use such lists as arguments to |
|
3105 | This is very useful when trying to use such lists as arguments to | |
3107 | system commands.""" |
|
3106 | system commands.""" | |
3108 |
|
3107 | |||
3109 | if parameter_s: |
|
3108 | if parameter_s: | |
3110 | out,err = self.shell.getoutputerror(parameter_s) |
|
3109 | out,err = self.shell.getoutputerror(parameter_s) | |
3111 | if err: |
|
3110 | if err: | |
3112 | print >> Term.cerr,err |
|
3111 | print >> Term.cerr,err | |
3113 | return SList(out.split('\n')) |
|
3112 | return SList(out.split('\n')) | |
3114 |
|
3113 | |||
3115 | def magic_bg(self, parameter_s=''): |
|
3114 | def magic_bg(self, parameter_s=''): | |
3116 | """Run a job in the background, in a separate thread. |
|
3115 | """Run a job in the background, in a separate thread. | |
3117 |
|
3116 | |||
3118 | For example, |
|
3117 | For example, | |
3119 |
|
3118 | |||
3120 | %bg myfunc(x,y,z=1) |
|
3119 | %bg myfunc(x,y,z=1) | |
3121 |
|
3120 | |||
3122 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3121 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
3123 | execution starts, a message will be printed indicating the job |
|
3122 | execution starts, a message will be printed indicating the job | |
3124 | number. If your job number is 5, you can use |
|
3123 | number. If your job number is 5, you can use | |
3125 |
|
3124 | |||
3126 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3125 | myvar = jobs.result(5) or myvar = jobs[5].result | |
3127 |
|
3126 | |||
3128 | to assign this result to variable 'myvar'. |
|
3127 | to assign this result to variable 'myvar'. | |
3129 |
|
3128 | |||
3130 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3129 | IPython has a job manager, accessible via the 'jobs' object. You can | |
3131 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3130 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
3132 | its attributes. All attributes not starting with an underscore are |
|
3131 | its attributes. All attributes not starting with an underscore are | |
3133 | meant for public use. |
|
3132 | meant for public use. | |
3134 |
|
3133 | |||
3135 | In particular, look at the jobs.new() method, which is used to create |
|
3134 | In particular, look at the jobs.new() method, which is used to create | |
3136 | new jobs. This magic %bg function is just a convenience wrapper |
|
3135 | new jobs. This magic %bg function is just a convenience wrapper | |
3137 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3136 | around jobs.new(), for expression-based jobs. If you want to create a | |
3138 | new job with an explicit function object and arguments, you must call |
|
3137 | new job with an explicit function object and arguments, you must call | |
3139 | jobs.new() directly. |
|
3138 | jobs.new() directly. | |
3140 |
|
3139 | |||
3141 | The jobs.new docstring also describes in detail several important |
|
3140 | The jobs.new docstring also describes in detail several important | |
3142 | caveats associated with a thread-based model for background job |
|
3141 | caveats associated with a thread-based model for background job | |
3143 | execution. Type jobs.new? for details. |
|
3142 | execution. Type jobs.new? for details. | |
3144 |
|
3143 | |||
3145 | You can check the status of all jobs with jobs.status(). |
|
3144 | You can check the status of all jobs with jobs.status(). | |
3146 |
|
3145 | |||
3147 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3146 | The jobs variable is set by IPython into the Python builtin namespace. | |
3148 | If you ever declare a variable named 'jobs', you will shadow this |
|
3147 | If you ever declare a variable named 'jobs', you will shadow this | |
3149 | name. You can either delete your global jobs variable to regain |
|
3148 | name. You can either delete your global jobs variable to regain | |
3150 | access to the job manager, or make a new name and assign it manually |
|
3149 | access to the job manager, or make a new name and assign it manually | |
3151 | to the manager (stored in IPython's namespace). For example, to |
|
3150 | to the manager (stored in IPython's namespace). For example, to | |
3152 | assign the job manager to the Jobs name, use: |
|
3151 | assign the job manager to the Jobs name, use: | |
3153 |
|
3152 | |||
3154 | Jobs = __builtins__.jobs""" |
|
3153 | Jobs = __builtins__.jobs""" | |
3155 |
|
3154 | |||
3156 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3155 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
3157 |
|
3156 | |||
3158 | def magic_r(self, parameter_s=''): |
|
3157 | def magic_r(self, parameter_s=''): | |
3159 | """Repeat previous input. |
|
3158 | """Repeat previous input. | |
3160 |
|
3159 | |||
3161 | Note: Consider using the more powerfull %rep instead! |
|
3160 | Note: Consider using the more powerfull %rep instead! | |
3162 |
|
3161 | |||
3163 | If given an argument, repeats the previous command which starts with |
|
3162 | If given an argument, repeats the previous command which starts with | |
3164 | the same string, otherwise it just repeats the previous input. |
|
3163 | the same string, otherwise it just repeats the previous input. | |
3165 |
|
3164 | |||
3166 | Shell escaped commands (with ! as first character) are not recognized |
|
3165 | Shell escaped commands (with ! as first character) are not recognized | |
3167 | by this system, only pure python code and magic commands. |
|
3166 | by this system, only pure python code and magic commands. | |
3168 | """ |
|
3167 | """ | |
3169 |
|
3168 | |||
3170 | start = parameter_s.strip() |
|
3169 | start = parameter_s.strip() | |
3171 | esc_magic = self.shell.ESC_MAGIC |
|
3170 | esc_magic = self.shell.ESC_MAGIC | |
3172 | # Identify magic commands even if automagic is on (which means |
|
3171 | # Identify magic commands even if automagic is on (which means | |
3173 | # the in-memory version is different from that typed by the user). |
|
3172 | # the in-memory version is different from that typed by the user). | |
3174 |
if self.shell. |
|
3173 | if self.shell.automagic: | |
3175 | start_magic = esc_magic+start |
|
3174 | start_magic = esc_magic+start | |
3176 | else: |
|
3175 | else: | |
3177 | start_magic = start |
|
3176 | start_magic = start | |
3178 | # Look through the input history in reverse |
|
3177 | # Look through the input history in reverse | |
3179 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3178 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3180 | input = self.shell.input_hist[n] |
|
3179 | input = self.shell.input_hist[n] | |
3181 | # skip plain 'r' lines so we don't recurse to infinity |
|
3180 | # skip plain 'r' lines so we don't recurse to infinity | |
3182 | if input != '_ip.magic("r")\n' and \ |
|
3181 | if input != '_ip.magic("r")\n' and \ | |
3183 | (input.startswith(start) or input.startswith(start_magic)): |
|
3182 | (input.startswith(start) or input.startswith(start_magic)): | |
3184 | #print 'match',`input` # dbg |
|
3183 | #print 'match',`input` # dbg | |
3185 | print 'Executing:',input, |
|
3184 | print 'Executing:',input, | |
3186 | self.shell.runlines(input) |
|
3185 | self.shell.runlines(input) | |
3187 | return |
|
3186 | return | |
3188 | print 'No previous input matching `%s` found.' % start |
|
3187 | print 'No previous input matching `%s` found.' % start | |
3189 |
|
3188 | |||
3190 |
|
3189 | |||
3191 | def magic_bookmark(self, parameter_s=''): |
|
3190 | def magic_bookmark(self, parameter_s=''): | |
3192 | """Manage IPython's bookmark system. |
|
3191 | """Manage IPython's bookmark system. | |
3193 |
|
3192 | |||
3194 | %bookmark <name> - set bookmark to current dir |
|
3193 | %bookmark <name> - set bookmark to current dir | |
3195 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3194 | %bookmark <name> <dir> - set bookmark to <dir> | |
3196 | %bookmark -l - list all bookmarks |
|
3195 | %bookmark -l - list all bookmarks | |
3197 | %bookmark -d <name> - remove bookmark |
|
3196 | %bookmark -d <name> - remove bookmark | |
3198 | %bookmark -r - remove all bookmarks |
|
3197 | %bookmark -r - remove all bookmarks | |
3199 |
|
3198 | |||
3200 | You can later on access a bookmarked folder with: |
|
3199 | You can later on access a bookmarked folder with: | |
3201 | %cd -b <name> |
|
3200 | %cd -b <name> | |
3202 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3201 | or simply '%cd <name>' if there is no directory called <name> AND | |
3203 | there is such a bookmark defined. |
|
3202 | there is such a bookmark defined. | |
3204 |
|
3203 | |||
3205 | Your bookmarks persist through IPython sessions, but they are |
|
3204 | Your bookmarks persist through IPython sessions, but they are | |
3206 | associated with each profile.""" |
|
3205 | associated with each profile.""" | |
3207 |
|
3206 | |||
3208 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3207 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3209 | if len(args) > 2: |
|
3208 | if len(args) > 2: | |
3210 | raise UsageError("%bookmark: too many arguments") |
|
3209 | raise UsageError("%bookmark: too many arguments") | |
3211 |
|
3210 | |||
3212 | bkms = self.db.get('bookmarks',{}) |
|
3211 | bkms = self.db.get('bookmarks',{}) | |
3213 |
|
3212 | |||
3214 | if opts.has_key('d'): |
|
3213 | if opts.has_key('d'): | |
3215 | try: |
|
3214 | try: | |
3216 | todel = args[0] |
|
3215 | todel = args[0] | |
3217 | except IndexError: |
|
3216 | except IndexError: | |
3218 | raise UsageError( |
|
3217 | raise UsageError( | |
3219 | "%bookmark -d: must provide a bookmark to delete") |
|
3218 | "%bookmark -d: must provide a bookmark to delete") | |
3220 | else: |
|
3219 | else: | |
3221 | try: |
|
3220 | try: | |
3222 | del bkms[todel] |
|
3221 | del bkms[todel] | |
3223 | except KeyError: |
|
3222 | except KeyError: | |
3224 | raise UsageError( |
|
3223 | raise UsageError( | |
3225 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3224 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3226 |
|
3225 | |||
3227 | elif opts.has_key('r'): |
|
3226 | elif opts.has_key('r'): | |
3228 | bkms = {} |
|
3227 | bkms = {} | |
3229 | elif opts.has_key('l'): |
|
3228 | elif opts.has_key('l'): | |
3230 | bks = bkms.keys() |
|
3229 | bks = bkms.keys() | |
3231 | bks.sort() |
|
3230 | bks.sort() | |
3232 | if bks: |
|
3231 | if bks: | |
3233 | size = max(map(len,bks)) |
|
3232 | size = max(map(len,bks)) | |
3234 | else: |
|
3233 | else: | |
3235 | size = 0 |
|
3234 | size = 0 | |
3236 | fmt = '%-'+str(size)+'s -> %s' |
|
3235 | fmt = '%-'+str(size)+'s -> %s' | |
3237 | print 'Current bookmarks:' |
|
3236 | print 'Current bookmarks:' | |
3238 | for bk in bks: |
|
3237 | for bk in bks: | |
3239 | print fmt % (bk,bkms[bk]) |
|
3238 | print fmt % (bk,bkms[bk]) | |
3240 | else: |
|
3239 | else: | |
3241 | if not args: |
|
3240 | if not args: | |
3242 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3241 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3243 | elif len(args)==1: |
|
3242 | elif len(args)==1: | |
3244 | bkms[args[0]] = os.getcwd() |
|
3243 | bkms[args[0]] = os.getcwd() | |
3245 | elif len(args)==2: |
|
3244 | elif len(args)==2: | |
3246 | bkms[args[0]] = args[1] |
|
3245 | bkms[args[0]] = args[1] | |
3247 | self.db['bookmarks'] = bkms |
|
3246 | self.db['bookmarks'] = bkms | |
3248 |
|
3247 | |||
3249 | def magic_pycat(self, parameter_s=''): |
|
3248 | def magic_pycat(self, parameter_s=''): | |
3250 | """Show a syntax-highlighted file through a pager. |
|
3249 | """Show a syntax-highlighted file through a pager. | |
3251 |
|
3250 | |||
3252 | This magic is similar to the cat utility, but it will assume the file |
|
3251 | This magic is similar to the cat utility, but it will assume the file | |
3253 | to be Python source and will show it with syntax highlighting. """ |
|
3252 | to be Python source and will show it with syntax highlighting. """ | |
3254 |
|
3253 | |||
3255 | try: |
|
3254 | try: | |
3256 | filename = get_py_filename(parameter_s) |
|
3255 | filename = get_py_filename(parameter_s) | |
3257 | cont = file_read(filename) |
|
3256 | cont = file_read(filename) | |
3258 | except IOError: |
|
3257 | except IOError: | |
3259 | try: |
|
3258 | try: | |
3260 | cont = eval(parameter_s,self.user_ns) |
|
3259 | cont = eval(parameter_s,self.user_ns) | |
3261 | except NameError: |
|
3260 | except NameError: | |
3262 | cont = None |
|
3261 | cont = None | |
3263 | if cont is None: |
|
3262 | if cont is None: | |
3264 | print "Error: no such file or variable" |
|
3263 | print "Error: no such file or variable" | |
3265 | return |
|
3264 | return | |
3266 |
|
3265 | |||
3267 | page(self.shell.pycolorize(cont), |
|
3266 | page(self.shell.pycolorize(cont), | |
3268 |
screen_lines=self.shell. |
|
3267 | screen_lines=self.shell.usable_screen_length) | |
3269 |
|
3268 | |||
3270 | def _rerun_pasted(self): |
|
3269 | def _rerun_pasted(self): | |
3271 | """ Rerun a previously pasted command. |
|
3270 | """ Rerun a previously pasted command. | |
3272 | """ |
|
3271 | """ | |
3273 | b = self.user_ns.get('pasted_block', None) |
|
3272 | b = self.user_ns.get('pasted_block', None) | |
3274 | if b is None: |
|
3273 | if b is None: | |
3275 | raise UsageError('No previous pasted block available') |
|
3274 | raise UsageError('No previous pasted block available') | |
3276 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3275 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3277 | exec b in self.user_ns |
|
3276 | exec b in self.user_ns | |
3278 |
|
3277 | |||
3279 | def _get_pasted_lines(self, sentinel): |
|
3278 | def _get_pasted_lines(self, sentinel): | |
3280 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3279 | """ Yield pasted lines until the user enters the given sentinel value. | |
3281 | """ |
|
3280 | """ | |
3282 | from IPython.core import iplib |
|
3281 | from IPython.core import iplib | |
3283 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3282 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3284 | while True: |
|
3283 | while True: | |
3285 | l = iplib.raw_input_original(':') |
|
3284 | l = iplib.raw_input_original(':') | |
3286 | if l == sentinel: |
|
3285 | if l == sentinel: | |
3287 | return |
|
3286 | return | |
3288 | else: |
|
3287 | else: | |
3289 | yield l |
|
3288 | yield l | |
3290 |
|
3289 | |||
3291 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3290 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3292 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3291 | """ Strip non-code parts of a sequence of lines to return a block of | |
3293 | code. |
|
3292 | code. | |
3294 | """ |
|
3293 | """ | |
3295 | # Regular expressions that declare text we strip from the input: |
|
3294 | # Regular expressions that declare text we strip from the input: | |
3296 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3295 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3297 | r'^\s*(\s?>)+', # Python input prompt |
|
3296 | r'^\s*(\s?>)+', # Python input prompt | |
3298 | r'^\s*\.{3,}', # Continuation prompts |
|
3297 | r'^\s*\.{3,}', # Continuation prompts | |
3299 | r'^\++', |
|
3298 | r'^\++', | |
3300 | ] |
|
3299 | ] | |
3301 |
|
3300 | |||
3302 | strip_from_start = map(re.compile,strip_re) |
|
3301 | strip_from_start = map(re.compile,strip_re) | |
3303 |
|
3302 | |||
3304 | lines = [] |
|
3303 | lines = [] | |
3305 | for l in raw_lines: |
|
3304 | for l in raw_lines: | |
3306 | for pat in strip_from_start: |
|
3305 | for pat in strip_from_start: | |
3307 | l = pat.sub('',l) |
|
3306 | l = pat.sub('',l) | |
3308 | lines.append(l) |
|
3307 | lines.append(l) | |
3309 |
|
3308 | |||
3310 | block = "\n".join(lines) + '\n' |
|
3309 | block = "\n".join(lines) + '\n' | |
3311 | #print "block:\n",block |
|
3310 | #print "block:\n",block | |
3312 | return block |
|
3311 | return block | |
3313 |
|
3312 | |||
3314 | def _execute_block(self, block, par): |
|
3313 | def _execute_block(self, block, par): | |
3315 | """ Execute a block, or store it in a variable, per the user's request. |
|
3314 | """ Execute a block, or store it in a variable, per the user's request. | |
3316 | """ |
|
3315 | """ | |
3317 | if not par: |
|
3316 | if not par: | |
3318 | b = textwrap.dedent(block) |
|
3317 | b = textwrap.dedent(block) | |
3319 | self.user_ns['pasted_block'] = b |
|
3318 | self.user_ns['pasted_block'] = b | |
3320 | exec b in self.user_ns |
|
3319 | exec b in self.user_ns | |
3321 | else: |
|
3320 | else: | |
3322 | self.user_ns[par] = SList(block.splitlines()) |
|
3321 | self.user_ns[par] = SList(block.splitlines()) | |
3323 | print "Block assigned to '%s'" % par |
|
3322 | print "Block assigned to '%s'" % par | |
3324 |
|
3323 | |||
3325 | def magic_cpaste(self, parameter_s=''): |
|
3324 | def magic_cpaste(self, parameter_s=''): | |
3326 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3325 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3327 |
|
3326 | |||
3328 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3327 | You must terminate the block with '--' (two minus-signs) alone on the | |
3329 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3328 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3330 | is the new sentinel for this operation) |
|
3329 | is the new sentinel for this operation) | |
3331 |
|
3330 | |||
3332 | The block is dedented prior to execution to enable execution of method |
|
3331 | The block is dedented prior to execution to enable execution of method | |
3333 | definitions. '>' and '+' characters at the beginning of a line are |
|
3332 | definitions. '>' and '+' characters at the beginning of a line are | |
3334 | ignored, to allow pasting directly from e-mails, diff files and |
|
3333 | ignored, to allow pasting directly from e-mails, diff files and | |
3335 | doctests (the '...' continuation prompt is also stripped). The |
|
3334 | doctests (the '...' continuation prompt is also stripped). The | |
3336 | executed block is also assigned to variable named 'pasted_block' for |
|
3335 | executed block is also assigned to variable named 'pasted_block' for | |
3337 | later editing with '%edit pasted_block'. |
|
3336 | later editing with '%edit pasted_block'. | |
3338 |
|
3337 | |||
3339 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3338 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3340 | This assigns the pasted block to variable 'foo' as string, without |
|
3339 | This assigns the pasted block to variable 'foo' as string, without | |
3341 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3340 | dedenting or executing it (preceding >>> and + is still stripped) | |
3342 |
|
3341 | |||
3343 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3342 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
3344 |
|
3343 | |||
3345 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3344 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3346 | Just press enter and type -- (and press enter again) and the block |
|
3345 | Just press enter and type -- (and press enter again) and the block | |
3347 | will be what was just pasted. |
|
3346 | will be what was just pasted. | |
3348 |
|
3347 | |||
3349 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3348 | IPython statements (magics, shell escapes) are not supported (yet). | |
3350 |
|
3349 | |||
3351 | See also |
|
3350 | See also | |
3352 | -------- |
|
3351 | -------- | |
3353 | paste: automatically pull code from clipboard. |
|
3352 | paste: automatically pull code from clipboard. | |
3354 | """ |
|
3353 | """ | |
3355 |
|
3354 | |||
3356 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3355 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
3357 | par = args.strip() |
|
3356 | par = args.strip() | |
3358 | if opts.has_key('r'): |
|
3357 | if opts.has_key('r'): | |
3359 | self._rerun_pasted() |
|
3358 | self._rerun_pasted() | |
3360 | return |
|
3359 | return | |
3361 |
|
3360 | |||
3362 | sentinel = opts.get('s','--') |
|
3361 | sentinel = opts.get('s','--') | |
3363 |
|
3362 | |||
3364 | block = self._strip_pasted_lines_for_code( |
|
3363 | block = self._strip_pasted_lines_for_code( | |
3365 | self._get_pasted_lines(sentinel)) |
|
3364 | self._get_pasted_lines(sentinel)) | |
3366 |
|
3365 | |||
3367 | self._execute_block(block, par) |
|
3366 | self._execute_block(block, par) | |
3368 |
|
3367 | |||
3369 | def magic_paste(self, parameter_s=''): |
|
3368 | def magic_paste(self, parameter_s=''): | |
3370 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3369 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3371 |
|
3370 | |||
3372 | The text is pulled directly from the clipboard without user |
|
3371 | The text is pulled directly from the clipboard without user | |
3373 | intervention and printed back on the screen before execution (unless |
|
3372 | intervention and printed back on the screen before execution (unless | |
3374 | the -q flag is given to force quiet mode). |
|
3373 | the -q flag is given to force quiet mode). | |
3375 |
|
3374 | |||
3376 | The block is dedented prior to execution to enable execution of method |
|
3375 | The block is dedented prior to execution to enable execution of method | |
3377 | definitions. '>' and '+' characters at the beginning of a line are |
|
3376 | definitions. '>' and '+' characters at the beginning of a line are | |
3378 | ignored, to allow pasting directly from e-mails, diff files and |
|
3377 | ignored, to allow pasting directly from e-mails, diff files and | |
3379 | doctests (the '...' continuation prompt is also stripped). The |
|
3378 | doctests (the '...' continuation prompt is also stripped). The | |
3380 | executed block is also assigned to variable named 'pasted_block' for |
|
3379 | executed block is also assigned to variable named 'pasted_block' for | |
3381 | later editing with '%edit pasted_block'. |
|
3380 | later editing with '%edit pasted_block'. | |
3382 |
|
3381 | |||
3383 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3382 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
3384 | This assigns the pasted block to variable 'foo' as string, without |
|
3383 | This assigns the pasted block to variable 'foo' as string, without | |
3385 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3384 | dedenting or executing it (preceding >>> and + is still stripped) | |
3386 |
|
3385 | |||
3387 | Options |
|
3386 | Options | |
3388 | ------- |
|
3387 | ------- | |
3389 |
|
3388 | |||
3390 | -r: re-executes the block previously entered by cpaste. |
|
3389 | -r: re-executes the block previously entered by cpaste. | |
3391 |
|
3390 | |||
3392 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3391 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
3393 |
|
3392 | |||
3394 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3393 | IPython statements (magics, shell escapes) are not supported (yet). | |
3395 |
|
3394 | |||
3396 | See also |
|
3395 | See also | |
3397 | -------- |
|
3396 | -------- | |
3398 | cpaste: manually paste code into terminal until you mark its end. |
|
3397 | cpaste: manually paste code into terminal until you mark its end. | |
3399 | """ |
|
3398 | """ | |
3400 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3399 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
3401 | par = args.strip() |
|
3400 | par = args.strip() | |
3402 | if opts.has_key('r'): |
|
3401 | if opts.has_key('r'): | |
3403 | self._rerun_pasted() |
|
3402 | self._rerun_pasted() | |
3404 | return |
|
3403 | return | |
3405 |
|
3404 | |||
3406 | text = self.shell.hooks.clipboard_get() |
|
3405 | text = self.shell.hooks.clipboard_get() | |
3407 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3406 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
3408 |
|
3407 | |||
3409 | # By default, echo back to terminal unless quiet mode is requested |
|
3408 | # By default, echo back to terminal unless quiet mode is requested | |
3410 | if not opts.has_key('q'): |
|
3409 | if not opts.has_key('q'): | |
3411 | write = self.shell.write |
|
3410 | write = self.shell.write | |
3412 | write(block) |
|
3411 | write(block) | |
3413 | if not block.endswith('\n'): |
|
3412 | if not block.endswith('\n'): | |
3414 | write('\n') |
|
3413 | write('\n') | |
3415 | write("## -- End pasted text --\n") |
|
3414 | write("## -- End pasted text --\n") | |
3416 |
|
3415 | |||
3417 | self._execute_block(block, par) |
|
3416 | self._execute_block(block, par) | |
3418 |
|
3417 | |||
3419 | def magic_quickref(self,arg): |
|
3418 | def magic_quickref(self,arg): | |
3420 | """ Show a quick reference sheet """ |
|
3419 | """ Show a quick reference sheet """ | |
3421 | import IPython.core.usage |
|
3420 | import IPython.core.usage | |
3422 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3421 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3423 |
|
3422 | |||
3424 | page(qr) |
|
3423 | page(qr) | |
3425 |
|
3424 | |||
3426 | def magic_upgrade(self,arg): |
|
3425 | def magic_upgrade(self,arg): | |
3427 | """ Upgrade your IPython installation |
|
3426 | """ Upgrade your IPython installation | |
3428 |
|
3427 | |||
3429 | This will copy the config files that don't yet exist in your |
|
3428 | This will copy the config files that don't yet exist in your | |
3430 | ipython dir from the system config dir. Use this after upgrading |
|
3429 | ipython dir from the system config dir. Use this after upgrading | |
3431 | IPython if you don't wish to delete your .ipython dir. |
|
3430 | IPython if you don't wish to delete your .ipython dir. | |
3432 |
|
3431 | |||
3433 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3432 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
3434 | new users) |
|
3433 | new users) | |
3435 |
|
3434 | |||
3436 | """ |
|
3435 | """ | |
3437 | ip = self.getapi() |
|
3436 | ip = self.getapi() | |
3438 | ipinstallation = path(IPython.__file__).dirname() |
|
3437 | ipinstallation = path(IPython.__file__).dirname() | |
3439 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py') |
|
3438 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py') | |
3440 | src_config = ipinstallation / 'config' / 'userconfig' |
|
3439 | src_config = ipinstallation / 'config' / 'userconfig' | |
3441 |
userdir = path(ip. |
|
3440 | userdir = path(ip.config.IPYTHONDIR) | |
3442 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3441 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3443 | print ">",cmd |
|
3442 | print ">",cmd | |
3444 | shell(cmd) |
|
3443 | shell(cmd) | |
3445 | if arg == '-nolegacy': |
|
3444 | if arg == '-nolegacy': | |
3446 | legacy = userdir.files('ipythonrc*') |
|
3445 | legacy = userdir.files('ipythonrc*') | |
3447 | print "Nuking legacy files:",legacy |
|
3446 | print "Nuking legacy files:",legacy | |
3448 |
|
3447 | |||
3449 | [p.remove() for p in legacy] |
|
3448 | [p.remove() for p in legacy] | |
3450 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3449 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
3451 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3450 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
3452 |
|
3451 | |||
3453 |
|
3452 | |||
3454 | def magic_doctest_mode(self,parameter_s=''): |
|
3453 | def magic_doctest_mode(self,parameter_s=''): | |
3455 | """Toggle doctest mode on and off. |
|
3454 | """Toggle doctest mode on and off. | |
3456 |
|
3455 | |||
3457 | This mode allows you to toggle the prompt behavior between normal |
|
3456 | This mode allows you to toggle the prompt behavior between normal | |
3458 | IPython prompts and ones that are as similar to the default IPython |
|
3457 | IPython prompts and ones that are as similar to the default IPython | |
3459 | interpreter as possible. |
|
3458 | interpreter as possible. | |
3460 |
|
3459 | |||
3461 | It also supports the pasting of code snippets that have leading '>>>' |
|
3460 | It also supports the pasting of code snippets that have leading '>>>' | |
3462 | and '...' prompts in them. This means that you can paste doctests from |
|
3461 | and '...' prompts in them. This means that you can paste doctests from | |
3463 | files or docstrings (even if they have leading whitespace), and the |
|
3462 | files or docstrings (even if they have leading whitespace), and the | |
3464 | code will execute correctly. You can then use '%history -tn' to see |
|
3463 | code will execute correctly. You can then use '%history -tn' to see | |
3465 | the translated history without line numbers; this will give you the |
|
3464 | the translated history without line numbers; this will give you the | |
3466 | input after removal of all the leading prompts and whitespace, which |
|
3465 | input after removal of all the leading prompts and whitespace, which | |
3467 | can be pasted back into an editor. |
|
3466 | can be pasted back into an editor. | |
3468 |
|
3467 | |||
3469 | With these features, you can switch into this mode easily whenever you |
|
3468 | With these features, you can switch into this mode easily whenever you | |
3470 | need to do testing and changes to doctests, without having to leave |
|
3469 | need to do testing and changes to doctests, without having to leave | |
3471 | your existing IPython session. |
|
3470 | your existing IPython session. | |
3472 | """ |
|
3471 | """ | |
3473 |
|
3472 | |||
3474 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3473 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
3475 | from IPython.extensions import InterpreterPasteInput as ipaste |
|
3474 | from IPython.extensions import InterpreterPasteInput as ipaste | |
3476 | from IPython.utils.ipstruct import Struct |
|
3475 | from IPython.utils.ipstruct import Struct | |
3477 |
|
3476 | |||
3478 | # Shorthands |
|
3477 | # Shorthands | |
3479 | shell = self.shell |
|
3478 | shell = self.shell | |
3480 | oc = shell.outputcache |
|
3479 | oc = shell.outputcache | |
3481 | rc = shell.rc |
|
|||
3482 | meta = shell.meta |
|
3480 | meta = shell.meta | |
3483 | # dstore is a data store kept in the instance metadata bag to track any |
|
3481 | # dstore is a data store kept in the instance metadata bag to track any | |
3484 | # changes we make, so we can undo them later. |
|
3482 | # changes we make, so we can undo them later. | |
3485 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3483 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3486 | save_dstore = dstore.setdefault |
|
3484 | save_dstore = dstore.setdefault | |
3487 |
|
3485 | |||
3488 | # save a few values we'll need to recover later |
|
3486 | # save a few values we'll need to recover later | |
3489 | mode = save_dstore('mode',False) |
|
3487 | mode = save_dstore('mode',False) | |
3490 |
save_dstore('rc_pprint', |
|
3488 | save_dstore('rc_pprint',shell.pprint) | |
3491 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3489 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3492 |
save_dstore('rc_separate_out', |
|
3490 | save_dstore('rc_separate_out',shell.separate_out) | |
3493 |
save_dstore('rc_separate_out2', |
|
3491 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3494 |
save_dstore('rc_prompts_pad_left', |
|
3492 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3495 |
save_dstore('rc_separate_in', |
|
3493 | save_dstore('rc_separate_in',shell.separate_in) | |
3496 |
|
3494 | |||
3497 | if mode == False: |
|
3495 | if mode == False: | |
3498 | # turn on |
|
3496 | # turn on | |
3499 | ipaste.activate_prefilter() |
|
3497 | ipaste.activate_prefilter() | |
3500 |
|
3498 | |||
3501 | oc.prompt1.p_template = '>>> ' |
|
3499 | oc.prompt1.p_template = '>>> ' | |
3502 | oc.prompt2.p_template = '... ' |
|
3500 | oc.prompt2.p_template = '... ' | |
3503 | oc.prompt_out.p_template = '' |
|
3501 | oc.prompt_out.p_template = '' | |
3504 |
|
3502 | |||
3505 | # Prompt separators like plain python |
|
3503 | # Prompt separators like plain python | |
3506 | oc.input_sep = oc.prompt1.sep = '' |
|
3504 | oc.input_sep = oc.prompt1.sep = '' | |
3507 | oc.output_sep = '' |
|
3505 | oc.output_sep = '' | |
3508 | oc.output_sep2 = '' |
|
3506 | oc.output_sep2 = '' | |
3509 |
|
3507 | |||
3510 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3508 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3511 | oc.prompt_out.pad_left = False |
|
3509 | oc.prompt_out.pad_left = False | |
3512 |
|
3510 | |||
3513 |
|
|
3511 | shell.pprint = False | |
3514 |
|
3512 | |||
3515 | shell.magic_xmode('Plain') |
|
3513 | shell.magic_xmode('Plain') | |
3516 |
|
3514 | |||
3517 | else: |
|
3515 | else: | |
3518 | # turn off |
|
3516 | # turn off | |
3519 | ipaste.deactivate_prefilter() |
|
3517 | ipaste.deactivate_prefilter() | |
3520 |
|
3518 | |||
3521 |
oc.prompt1.p_template = |
|
3519 | oc.prompt1.p_template = shell.prompt_in1 | |
3522 |
oc.prompt2.p_template = |
|
3520 | oc.prompt2.p_template = shell.prompt_in2 | |
3523 |
oc.prompt_out.p_template = |
|
3521 | oc.prompt_out.p_template = shell.prompt_out | |
3524 |
|
3522 | |||
3525 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3523 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3526 |
|
3524 | |||
3527 | oc.output_sep = dstore.rc_separate_out |
|
3525 | oc.output_sep = dstore.rc_separate_out | |
3528 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3526 | oc.output_sep2 = dstore.rc_separate_out2 | |
3529 |
|
3527 | |||
3530 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3528 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3531 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3529 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3532 |
|
3530 | |||
3533 | rc.pprint = dstore.rc_pprint |
|
3531 | rc.pprint = dstore.rc_pprint | |
3534 |
|
3532 | |||
3535 | shell.magic_xmode(dstore.xmode) |
|
3533 | shell.magic_xmode(dstore.xmode) | |
3536 |
|
3534 | |||
3537 | # Store new mode and inform |
|
3535 | # Store new mode and inform | |
3538 | dstore.mode = bool(1-int(mode)) |
|
3536 | dstore.mode = bool(1-int(mode)) | |
3539 | print 'Doctest mode is:', |
|
3537 | print 'Doctest mode is:', | |
3540 | print ['OFF','ON'][dstore.mode] |
|
3538 | print ['OFF','ON'][dstore.mode] | |
3541 |
|
3539 | |||
3542 | def magic_gui(self, parameter_s=''): |
|
3540 | def magic_gui(self, parameter_s=''): | |
3543 | """Enable or disable IPython GUI event loop integration. |
|
3541 | """Enable or disable IPython GUI event loop integration. | |
3544 |
|
3542 | |||
3545 | %gui [-a] [GUINAME] |
|
3543 | %gui [-a] [GUINAME] | |
3546 |
|
3544 | |||
3547 | This magic replaces IPython's threaded shells that were activated |
|
3545 | This magic replaces IPython's threaded shells that were activated | |
3548 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3546 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3549 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3547 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3550 | interrupts should work without any problems. The following toolkits |
|
3548 | interrupts should work without any problems. The following toolkits | |
3551 | are supports: wxPython, PyQt4, PyGTK, and Tk:: |
|
3549 | are supports: wxPython, PyQt4, PyGTK, and Tk:: | |
3552 |
|
3550 | |||
3553 | %gui wx # enable wxPython event loop integration |
|
3551 | %gui wx # enable wxPython event loop integration | |
3554 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3552 | %gui qt4|qt # enable PyQt4 event loop integration | |
3555 | %gui gtk # enable PyGTK event loop integration |
|
3553 | %gui gtk # enable PyGTK event loop integration | |
3556 | %gui tk # enable Tk event loop integration |
|
3554 | %gui tk # enable Tk event loop integration | |
3557 | %gui # disable all event loop integration |
|
3555 | %gui # disable all event loop integration | |
3558 |
|
3556 | |||
3559 | WARNING: after any of these has been called you can simply create |
|
3557 | WARNING: after any of these has been called you can simply create | |
3560 | an application object, but DO NOT start the event loop yourself, as |
|
3558 | an application object, but DO NOT start the event loop yourself, as | |
3561 | we have already handled that. |
|
3559 | we have already handled that. | |
3562 |
|
3560 | |||
3563 | If you want us to create an appropriate application object add the |
|
3561 | If you want us to create an appropriate application object add the | |
3564 | "-a" flag to your command:: |
|
3562 | "-a" flag to your command:: | |
3565 |
|
3563 | |||
3566 | %gui -a wx |
|
3564 | %gui -a wx | |
3567 |
|
3565 | |||
3568 | This is highly recommended for most users. |
|
3566 | This is highly recommended for most users. | |
3569 | """ |
|
3567 | """ | |
3570 | from IPython.lib import inputhook |
|
3568 | from IPython.lib import inputhook | |
3571 | if "-a" in parameter_s: |
|
3569 | if "-a" in parameter_s: | |
3572 | app = True |
|
3570 | app = True | |
3573 | else: |
|
3571 | else: | |
3574 | app = False |
|
3572 | app = False | |
3575 | if not parameter_s: |
|
3573 | if not parameter_s: | |
3576 | inputhook.clear_inputhook() |
|
3574 | inputhook.clear_inputhook() | |
3577 | elif 'wx' in parameter_s: |
|
3575 | elif 'wx' in parameter_s: | |
3578 | return inputhook.enable_wx(app) |
|
3576 | return inputhook.enable_wx(app) | |
3579 | elif ('qt4' in parameter_s) or ('qt' in parameter_s): |
|
3577 | elif ('qt4' in parameter_s) or ('qt' in parameter_s): | |
3580 | return inputhook.enable_qt4(app) |
|
3578 | return inputhook.enable_qt4(app) | |
3581 | elif 'gtk' in parameter_s: |
|
3579 | elif 'gtk' in parameter_s: | |
3582 | return inputhook.enable_gtk(app) |
|
3580 | return inputhook.enable_gtk(app) | |
3583 | elif 'tk' in parameter_s: |
|
3581 | elif 'tk' in parameter_s: | |
3584 | return inputhook.enable_tk(app) |
|
3582 | return inputhook.enable_tk(app) | |
3585 |
|
3583 | |||
3586 |
|
3584 | |||
3587 | # end Magic |
|
3585 | # end Magic |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
1 | NO CONTENT: file was removed |
|
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 |
|
NO CONTENT: file was removed | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now