Show More
@@ -1,260 +1,268 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | An embedded IPython shell. |
|
4 | An embedded IPython shell. | |
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 | from __future__ import with_statement |
|
26 | from __future__ import with_statement | |
27 |
|
27 | |||
28 | import sys |
|
28 | import sys | |
29 | from contextlib import nested |
|
29 | from contextlib import nested | |
30 |
|
30 | |||
31 | from IPython.core import ultratb |
|
31 | from IPython.core import ultratb | |
32 | from IPython.core.iplib import InteractiveShell |
|
32 | from IPython.core.iplib import InteractiveShell | |
33 |
|
33 | |||
34 | from IPython.utils.traitlets import Bool, Str, CBool |
|
34 | from IPython.utils.traitlets import Bool, Str, CBool | |
35 | from IPython.utils.genutils import ask_yes_no |
|
35 | from IPython.utils.genutils import ask_yes_no | |
36 |
|
36 | |||
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 | # Classes and functions |
|
38 | # Classes and functions | |
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 |
|
40 | |||
41 | # This is an additional magic that is exposed in embedded shells. |
|
41 | # This is an additional magic that is exposed in embedded shells. | |
42 | def kill_embedded(self,parameter_s=''): |
|
42 | def kill_embedded(self,parameter_s=''): | |
43 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
43 | """%kill_embedded : deactivate for good the current embedded IPython. | |
44 |
|
44 | |||
45 | This function (after asking for confirmation) sets an internal flag so that |
|
45 | This function (after asking for confirmation) sets an internal flag so that | |
46 | an embedded IPython will never activate again. This is useful to |
|
46 | an embedded IPython will never activate again. This is useful to | |
47 | permanently disable a shell that is being called inside a loop: once you've |
|
47 | permanently disable a shell that is being called inside a loop: once you've | |
48 | figured out what you needed from it, you may then kill it and the program |
|
48 | figured out what you needed from it, you may then kill it and the program | |
49 | will then continue to run without the interactive shell interfering again. |
|
49 | will then continue to run without the interactive shell interfering again. | |
50 | """ |
|
50 | """ | |
51 |
|
51 | |||
52 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
52 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " | |
53 | "(y/n)? [y/N] ",'n') |
|
53 | "(y/n)? [y/N] ",'n') | |
54 | if kill: |
|
54 | if kill: | |
55 | self.embedded_active = False |
|
55 | self.embedded_active = False | |
56 | print "This embedded IPython will not reactivate anymore once you exit." |
|
56 | print "This embedded IPython will not reactivate anymore once you exit." | |
57 |
|
57 | |||
58 |
|
58 | |||
59 | class InteractiveShellEmbed(InteractiveShell): |
|
59 | class InteractiveShellEmbed(InteractiveShell): | |
60 |
|
60 | |||
61 | dummy_mode = Bool(False) |
|
61 | dummy_mode = Bool(False) | |
62 | exit_msg = Str('') |
|
62 | exit_msg = Str('') | |
63 | embedded = CBool(True) |
|
63 | embedded = CBool(True) | |
64 | embedded_active = CBool(True) |
|
64 | embedded_active = CBool(True) | |
65 |
|
65 | |||
66 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, |
|
66 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
67 | user_ns=None, user_global_ns=None, |
|
67 | user_ns=None, user_global_ns=None, | |
68 | banner1=None, banner2=None, |
|
68 | banner1=None, banner2=None, | |
69 | custom_exceptions=((),None), exit_msg=''): |
|
69 | custom_exceptions=((),None), exit_msg=''): | |
70 |
|
70 | |||
71 | self.save_sys_ipcompleter() |
|
71 | self.save_sys_ipcompleter() | |
72 |
|
72 | |||
73 | super(InteractiveShellEmbed,self).__init__( |
|
73 | super(InteractiveShellEmbed,self).__init__( | |
74 | parent=parent, config=config, ipythondir=ipythondir, usage=usage, |
|
74 | parent=parent, config=config, ipythondir=ipythondir, usage=usage, | |
75 | user_ns=user_ns, user_global_ns=user_global_ns, |
|
75 | user_ns=user_ns, user_global_ns=user_global_ns, | |
76 | banner1=banner1, banner2=banner2, |
|
76 | banner1=banner1, banner2=banner2, | |
77 | custom_exceptions=custom_exceptions) |
|
77 | custom_exceptions=custom_exceptions) | |
78 |
|
78 | |||
79 | self.exit_msg = exit_msg |
|
79 | self.exit_msg = exit_msg | |
80 | self.define_magic("kill_embedded", kill_embedded) |
|
80 | self.define_magic("kill_embedded", kill_embedded) | |
81 |
|
81 | |||
82 | # don't use the ipython crash handler so that user exceptions aren't |
|
82 | # don't use the ipython crash handler so that user exceptions aren't | |
83 | # trapped |
|
83 | # trapped | |
84 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
84 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, | |
85 | mode=self.xmode, |
|
85 | mode=self.xmode, | |
86 | call_pdb=self.pdb) |
|
86 | call_pdb=self.pdb) | |
87 |
|
87 | |||
88 | self.restore_sys_ipcompleter() |
|
88 | self.restore_sys_ipcompleter() | |
89 |
|
89 | |||
90 | def init_sys_modules(self): |
|
90 | def init_sys_modules(self): | |
91 | pass |
|
91 | pass | |
92 |
|
92 | |||
93 | def save_sys_ipcompleter(self): |
|
93 | def save_sys_ipcompleter(self): | |
94 | """Save readline completer status.""" |
|
94 | """Save readline completer status.""" | |
95 | try: |
|
95 | try: | |
96 | #print 'Save completer',sys.ipcompleter # dbg |
|
96 | #print 'Save completer',sys.ipcompleter # dbg | |
97 | self.sys_ipcompleter_orig = sys.ipcompleter |
|
97 | self.sys_ipcompleter_orig = sys.ipcompleter | |
98 | except: |
|
98 | except: | |
99 | pass # not nested with IPython |
|
99 | pass # not nested with IPython | |
100 |
|
100 | |||
101 | def restore_sys_ipcompleter(self): |
|
101 | def restore_sys_ipcompleter(self): | |
102 | """Restores the readline completer which was in place. |
|
102 | """Restores the readline completer which was in place. | |
103 |
|
103 | |||
104 | This allows embedded IPython within IPython not to disrupt the |
|
104 | This allows embedded IPython within IPython not to disrupt the | |
105 | parent's completion. |
|
105 | parent's completion. | |
106 | """ |
|
106 | """ | |
107 | try: |
|
107 | try: | |
108 | self.readline.set_completer(self.sys_ipcompleter_orig) |
|
108 | self.readline.set_completer(self.sys_ipcompleter_orig) | |
109 | sys.ipcompleter = self.sys_ipcompleter_orig |
|
109 | sys.ipcompleter = self.sys_ipcompleter_orig | |
110 | except: |
|
110 | except: | |
111 | pass |
|
111 | pass | |
112 |
|
112 | |||
113 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, |
|
113 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, | |
114 | stack_depth=1): |
|
114 | stack_depth=1): | |
115 | """Activate the interactive interpreter. |
|
115 | """Activate the interactive interpreter. | |
116 |
|
116 | |||
117 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
117 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start | |
118 | the interpreter shell with the given local and global namespaces, and |
|
118 | the interpreter shell with the given local and global namespaces, and | |
119 | optionally print a header string at startup. |
|
119 | optionally print a header string at startup. | |
120 |
|
120 | |||
121 | The shell can be globally activated/deactivated using the |
|
121 | The shell can be globally activated/deactivated using the | |
122 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
122 | set/get_dummy_mode methods. This allows you to turn off a shell used | |
123 | for debugging globally. |
|
123 | for debugging globally. | |
124 |
|
124 | |||
125 | However, *each* time you call the shell you can override the current |
|
125 | However, *each* time you call the shell you can override the current | |
126 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
126 | state of dummy_mode with the optional keyword parameter 'dummy'. For | |
127 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
127 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you | |
128 | can still have a specific call work by making it as IPShell(dummy=0). |
|
128 | can still have a specific call work by making it as IPShell(dummy=0). | |
129 |
|
129 | |||
130 | The optional keyword parameter dummy controls whether the call |
|
130 | The optional keyword parameter dummy controls whether the call | |
131 | actually does anything. |
|
131 | actually does anything. | |
132 | """ |
|
132 | """ | |
133 |
|
133 | |||
134 | # If the user has turned it off, go away |
|
134 | # If the user has turned it off, go away | |
135 | if not self.embedded_active: |
|
135 | if not self.embedded_active: | |
136 | return |
|
136 | return | |
137 |
|
137 | |||
138 | # Normal exits from interactive mode set this flag, so the shell can't |
|
138 | # Normal exits from interactive mode set this flag, so the shell can't | |
139 | # re-enter (it checks this variable at the start of interactive mode). |
|
139 | # re-enter (it checks this variable at the start of interactive mode). | |
140 | self.exit_now = False |
|
140 | self.exit_now = False | |
141 |
|
141 | |||
142 | # Allow the dummy parameter to override the global __dummy_mode |
|
142 | # Allow the dummy parameter to override the global __dummy_mode | |
143 | if dummy or (dummy != 0 and self.dummy_mode): |
|
143 | if dummy or (dummy != 0 and self.dummy_mode): | |
144 | return |
|
144 | return | |
145 |
|
145 | |||
146 | if self.has_readline: |
|
146 | if self.has_readline: | |
147 | self.set_completer() |
|
147 | self.set_completer() | |
148 |
|
148 | |||
149 | if self.banner and header: |
|
149 | if self.banner and header: | |
150 | format = '%s\n%s\n' |
|
150 | format = '%s\n%s\n' | |
151 | else: |
|
151 | else: | |
152 | format = '%s%s\n' |
|
152 | format = '%s%s\n' | |
153 | banner = format % (self.banner,header) |
|
153 | banner = format % (self.banner,header) | |
154 |
|
154 | |||
155 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
155 | # Call the embedding code with a stack depth of 1 so it can skip over | |
156 | # our call and get the original caller's namespaces. |
|
156 | # our call and get the original caller's namespaces. | |
157 | self.mainloop(banner, local_ns, global_ns, |
|
157 | self.mainloop(banner, local_ns, global_ns, | |
158 | stack_depth=stack_depth) |
|
158 | stack_depth=stack_depth) | |
159 |
|
159 | |||
160 | if self.exit_msg is not None: |
|
160 | if self.exit_msg is not None: | |
161 | print self.exit_msg |
|
161 | print self.exit_msg | |
162 |
|
162 | |||
163 | self.restore_sys_ipcompleter() |
|
163 | self.restore_sys_ipcompleter() | |
164 |
|
164 | |||
165 | def mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
165 | def mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
166 | """Embeds IPython into a running python program. |
|
166 | """Embeds IPython into a running python program. | |
167 |
|
167 | |||
168 | Input: |
|
168 | Input: | |
169 |
|
169 | |||
170 | - header: An optional header message can be specified. |
|
170 | - header: An optional header message can be specified. | |
171 |
|
171 | |||
172 | - local_ns, global_ns: working namespaces. If given as None, the |
|
172 | - local_ns, global_ns: working namespaces. If given as None, the | |
173 | IPython-initialized one is updated with __main__.__dict__, so that |
|
173 | IPython-initialized one is updated with __main__.__dict__, so that | |
174 | program variables become visible but user-specific configuration |
|
174 | program variables become visible but user-specific configuration | |
175 | remains possible. |
|
175 | remains possible. | |
176 |
|
176 | |||
177 | - stack_depth: specifies how many levels in the stack to go to |
|
177 | - stack_depth: specifies how many levels in the stack to go to | |
178 | looking for namespaces (when local_ns and global_ns are None). This |
|
178 | looking for namespaces (when local_ns and global_ns are None). This | |
179 | allows an intermediate caller to make sure that this function gets |
|
179 | allows an intermediate caller to make sure that this function gets | |
180 | the namespace from the intended level in the stack. By default (0) |
|
180 | the namespace from the intended level in the stack. By default (0) | |
181 | it will get its locals and globals from the immediate caller. |
|
181 | it will get its locals and globals from the immediate caller. | |
182 |
|
182 | |||
183 | Warning: it's possible to use this in a program which is being run by |
|
183 | Warning: it's possible to use this in a program which is being run by | |
184 | IPython itself (via %run), but some funny things will happen (a few |
|
184 | IPython itself (via %run), but some funny things will happen (a few | |
185 | globals get overwritten). In the future this will be cleaned up, as |
|
185 | globals get overwritten). In the future this will be cleaned up, as | |
186 | there is no fundamental reason why it can't work perfectly.""" |
|
186 | there is no fundamental reason why it can't work perfectly.""" | |
187 |
|
187 | |||
188 | # Get locals and globals from caller |
|
188 | # Get locals and globals from caller | |
189 | if local_ns is None or global_ns is None: |
|
189 | if local_ns is None or global_ns is None: | |
190 | call_frame = sys._getframe(stack_depth).f_back |
|
190 | call_frame = sys._getframe(stack_depth).f_back | |
191 |
|
191 | |||
192 | if local_ns is None: |
|
192 | if local_ns is None: | |
193 | local_ns = call_frame.f_locals |
|
193 | local_ns = call_frame.f_locals | |
194 | if global_ns is None: |
|
194 | if global_ns is None: | |
195 | global_ns = call_frame.f_globals |
|
195 | global_ns = call_frame.f_globals | |
196 |
|
196 | |||
197 | # Update namespaces and fire up interpreter |
|
197 | # Update namespaces and fire up interpreter | |
198 |
|
198 | |||
199 | # The global one is easy, we can just throw it in |
|
199 | # The global one is easy, we can just throw it in | |
200 | self.user_global_ns = global_ns |
|
200 | self.user_global_ns = global_ns | |
201 |
|
201 | |||
202 | # but the user/local one is tricky: ipython needs it to store internal |
|
202 | # but the user/local one is tricky: ipython needs it to store internal | |
203 | # data, but we also need the locals. We'll copy locals in the user |
|
203 | # data, but we also need the locals. We'll copy locals in the user | |
204 | # one, but will track what got copied so we can delete them at exit. |
|
204 | # one, but will track what got copied so we can delete them at exit. | |
205 | # This is so that a later embedded call doesn't see locals from a |
|
205 | # This is so that a later embedded call doesn't see locals from a | |
206 | # previous call (which most likely existed in a separate scope). |
|
206 | # previous call (which most likely existed in a separate scope). | |
207 | local_varnames = local_ns.keys() |
|
207 | local_varnames = local_ns.keys() | |
208 | self.user_ns.update(local_ns) |
|
208 | self.user_ns.update(local_ns) | |
209 | #self.user_ns['local_ns'] = local_ns # dbg |
|
209 | #self.user_ns['local_ns'] = local_ns # dbg | |
210 |
|
210 | |||
211 | # Patch for global embedding to make sure that things don't overwrite |
|
211 | # Patch for global embedding to make sure that things don't overwrite | |
212 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
212 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
213 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
213 | # FIXME. Test this a bit more carefully (the if.. is new) | |
214 | if local_ns is None and global_ns is None: |
|
214 | if local_ns is None and global_ns is None: | |
215 | self.user_global_ns.update(__main__.__dict__) |
|
215 | self.user_global_ns.update(__main__.__dict__) | |
216 |
|
216 | |||
217 | # make sure the tab-completer has the correct frame information, so it |
|
217 | # make sure the tab-completer has the correct frame information, so it | |
218 | # actually completes using the frame's locals/globals |
|
218 | # actually completes using the frame's locals/globals | |
219 | self.set_completer_frame() |
|
219 | self.set_completer_frame() | |
220 |
|
220 | |||
221 | with nested(self.builtin_trap, self.display_trap): |
|
221 | with nested(self.builtin_trap, self.display_trap): | |
222 | self.interact(header) |
|
222 | self.interact(header) | |
223 |
|
223 | |||
224 | # now, purge out the user namespace from anything we might have added |
|
224 | # now, purge out the user namespace from anything we might have added | |
225 | # from the caller's local namespace |
|
225 | # from the caller's local namespace | |
226 | delvar = self.user_ns.pop |
|
226 | delvar = self.user_ns.pop | |
227 | for var in local_varnames: |
|
227 | for var in local_varnames: | |
228 | delvar(var,None) |
|
228 | delvar(var,None) | |
229 |
|
229 | |||
|
230 | def set_completer_frame(self, frame=None): | |||
|
231 | if frame: | |||
|
232 | self.Completer.namespace = frame.f_locals | |||
|
233 | self.Completer.global_namespace = frame.f_globals | |||
|
234 | else: | |||
|
235 | self.Completer.namespace = self.user_ns | |||
|
236 | self.Completer.global_namespace = self.user_global_ns | |||
|
237 | ||||
230 |
|
238 | |||
231 | _embedded_shell = None |
|
239 | _embedded_shell = None | |
232 |
|
240 | |||
233 |
|
241 | |||
234 | def embed(header='', config=None, usage=None, banner1=None, banner2=None, |
|
242 | def embed(header='', config=None, usage=None, banner1=None, banner2=None, | |
235 | exit_msg=''): |
|
243 | exit_msg=''): | |
236 | """Call this to embed IPython at the current point in your program. |
|
244 | """Call this to embed IPython at the current point in your program. | |
237 |
|
245 | |||
238 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
246 | The first invocation of this will create an :class:`InteractiveShellEmbed` | |
239 | instance and then call it. Consecutive calls just call the already |
|
247 | instance and then call it. Consecutive calls just call the already | |
240 | created instance. |
|
248 | created instance. | |
241 |
|
249 | |||
242 | Here is a simple example:: |
|
250 | Here is a simple example:: | |
243 |
|
251 | |||
244 | from IPython import embed |
|
252 | from IPython import embed | |
245 | a = 10 |
|
253 | a = 10 | |
246 | b = 20 |
|
254 | b = 20 | |
247 | embed('First time') |
|
255 | embed('First time') | |
248 | c = 30 |
|
256 | c = 30 | |
249 | d = 40 |
|
257 | d = 40 | |
250 | embed |
|
258 | embed | |
251 |
|
259 | |||
252 | Full customization can be done by passing a :class:`Struct` in as the |
|
260 | Full customization can be done by passing a :class:`Struct` in as the | |
253 | config argument. |
|
261 | config argument. | |
254 | """ |
|
262 | """ | |
255 | global _embedded_shell |
|
263 | global _embedded_shell | |
256 | if _embedded_shell is None: |
|
264 | if _embedded_shell is None: | |
257 | _embedded_shell = InteractiveShellEmbed(config=config, |
|
265 | _embedded_shell = InteractiveShellEmbed(config=config, | |
258 | usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg) |
|
266 | usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg) | |
259 | _embedded_shell(header=header, stack_depth=2) |
|
267 | _embedded_shell(header=header, stack_depth=2) | |
260 |
|
268 |
This diff has been collapsed as it changes many lines, (2836 lines changed) Show them Hide them | |||||
@@ -1,2958 +1,3018 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Main IPython Component |
|
3 | Main IPython Component | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # 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 | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | from __future__ import with_statement |
|
19 | from __future__ import with_statement | |
20 |
|
20 | |||
21 | import __main__ |
|
21 | import __main__ | |
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 | import StringIO |
|
23 | import StringIO | |
24 | import bdb |
|
24 | import bdb | |
25 | import codeop |
|
25 | import codeop | |
26 | import exceptions |
|
26 | import exceptions | |
27 | import glob |
|
27 | import glob | |
28 | import keyword |
|
28 | import keyword | |
29 | import new |
|
29 | import new | |
30 | import os |
|
30 | import os | |
31 | import re |
|
31 | import re | |
32 | import shutil |
|
32 | import shutil | |
33 | import string |
|
33 | import string | |
34 | import sys |
|
34 | import sys | |
35 | import tempfile |
|
35 | import tempfile | |
36 | from contextlib import nested |
|
36 | from contextlib import nested | |
37 |
|
37 | |||
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core import debugger, oinspect |
|
39 | from IPython.core import debugger, oinspect | |
40 | from IPython.core import shadowns |
|
40 | from IPython.core import shadowns | |
41 | from IPython.core import history as ipcorehist |
|
41 | from IPython.core import history as ipcorehist | |
42 | from IPython.core import prefilter |
|
42 | from IPython.core import prefilter | |
43 | from IPython.core.autocall import IPyAutocall |
|
43 | from IPython.core.autocall import IPyAutocall | |
44 | from IPython.core.builtin_trap import BuiltinTrap |
|
44 | from IPython.core.builtin_trap import BuiltinTrap | |
45 | from IPython.core.display_trap import DisplayTrap |
|
45 | from IPython.core.display_trap import DisplayTrap | |
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
47 | from IPython.core.logger import Logger |
|
47 | from IPython.core.logger import Logger | |
48 | from IPython.core.magic import Magic |
|
48 | from IPython.core.magic import Magic | |
49 | from IPython.core.prompts import CachedOutput |
|
49 | from IPython.core.prompts import CachedOutput | |
50 | from IPython.core.page import page |
|
50 | from IPython.core.page import page | |
51 | from IPython.core.component import Component |
|
51 | from IPython.core.component import Component | |
52 | from IPython.core.oldusersetup import user_setup |
|
52 | from IPython.core.oldusersetup import user_setup | |
53 | from IPython.core.usage import interactive_usage, default_banner |
|
53 | from IPython.core.usage import interactive_usage, default_banner | |
54 | from IPython.core.error import TryNext, UsageError |
|
54 | from IPython.core.error import TryNext, UsageError | |
55 |
|
55 | |||
56 | from IPython.extensions import pickleshare |
|
56 | from IPython.extensions import pickleshare | |
57 | from IPython.external.Itpl import ItplNS |
|
57 | from IPython.external.Itpl import ItplNS | |
58 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
58 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
59 | from IPython.utils.ipstruct import Struct |
|
59 | from IPython.utils.ipstruct import Struct | |
60 | from IPython.utils import PyColorize |
|
60 | from IPython.utils import PyColorize | |
61 | from IPython.utils.genutils import * |
|
61 | from IPython.utils.genutils import * | |
62 | from IPython.utils.strdispatch import StrDispatch |
|
62 | from IPython.utils.strdispatch import StrDispatch | |
63 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
63 | from IPython.utils.platutils import toggle_set_term_title, set_term_title | |
64 |
|
64 | |||
65 | from IPython.utils.traitlets import ( |
|
65 | from IPython.utils.traitlets import ( | |
66 | Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
66 | Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode | |
67 | ) |
|
67 | ) | |
68 |
|
68 | |||
69 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
70 | # Globals |
|
70 | # Globals | |
71 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
72 |
|
72 | |||
73 |
|
73 | |||
74 | # store the builtin raw_input globally, and use this always, in case user code |
|
74 | # store the builtin raw_input globally, and use this always, in case user code | |
75 | # overwrites it (like wx.py.PyShell does) |
|
75 | # overwrites it (like wx.py.PyShell does) | |
76 | raw_input_original = raw_input |
|
76 | raw_input_original = raw_input | |
77 |
|
77 | |||
78 | # compiled regexps for autoindent management |
|
78 | # compiled regexps for autoindent management | |
79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 | # Utilities |
|
83 | # Utilities | |
84 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
87 | ini_spaces_re = re.compile(r'^(\s+)') | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | def num_ini_spaces(strng): |
|
90 | def num_ini_spaces(strng): | |
91 | """Return the number of initial spaces in a string""" |
|
91 | """Return the number of initial spaces in a string""" | |
92 |
|
92 | |||
93 | ini_spaces = ini_spaces_re.match(strng) |
|
93 | ini_spaces = ini_spaces_re.match(strng) | |
94 | if ini_spaces: |
|
94 | if ini_spaces: | |
95 | return ini_spaces.end() |
|
95 | return ini_spaces.end() | |
96 | else: |
|
96 | else: | |
97 | return 0 |
|
97 | return 0 | |
98 |
|
98 | |||
99 |
|
99 | |||
100 | def softspace(file, newvalue): |
|
100 | def softspace(file, newvalue): | |
101 | """Copied from code.py, to remove the dependency""" |
|
101 | """Copied from code.py, to remove the dependency""" | |
102 |
|
102 | |||
103 | oldvalue = 0 |
|
103 | oldvalue = 0 | |
104 | try: |
|
104 | try: | |
105 | oldvalue = file.softspace |
|
105 | oldvalue = file.softspace | |
106 | except AttributeError: |
|
106 | except AttributeError: | |
107 | pass |
|
107 | pass | |
108 | try: |
|
108 | try: | |
109 | file.softspace = newvalue |
|
109 | file.softspace = newvalue | |
110 | except (AttributeError, TypeError): |
|
110 | except (AttributeError, TypeError): | |
111 | # "attribute-less object" or "read-only attributes" |
|
111 | # "attribute-less object" or "read-only attributes" | |
112 | pass |
|
112 | pass | |
113 | return oldvalue |
|
113 | return oldvalue | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | class SpaceInInput(exceptions.Exception): pass |
|
116 | class SpaceInInput(exceptions.Exception): pass | |
117 |
|
117 | |||
118 | class Bunch: pass |
|
118 | class Bunch: pass | |
119 |
|
119 | |||
120 | class InputList(list): |
|
120 | class InputList(list): | |
121 | """Class to store user input. |
|
121 | """Class to store user input. | |
122 |
|
122 | |||
123 | It's basically a list, but slices return a string instead of a list, thus |
|
123 | It's basically a list, but slices return a string instead of a list, thus | |
124 | allowing things like (assuming 'In' is an instance): |
|
124 | allowing things like (assuming 'In' is an instance): | |
125 |
|
125 | |||
126 | exec In[4:7] |
|
126 | exec In[4:7] | |
127 |
|
127 | |||
128 | or |
|
128 | or | |
129 |
|
129 | |||
130 | exec In[5:9] + In[14] + In[21:25]""" |
|
130 | exec In[5:9] + In[14] + In[21:25]""" | |
131 |
|
131 | |||
132 | def __getslice__(self,i,j): |
|
132 | def __getslice__(self,i,j): | |
133 | return ''.join(list.__getslice__(self,i,j)) |
|
133 | return ''.join(list.__getslice__(self,i,j)) | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | class SyntaxTB(ultratb.ListTB): |
|
136 | class SyntaxTB(ultratb.ListTB): | |
137 | """Extension which holds some state: the last exception value""" |
|
137 | """Extension which holds some state: the last exception value""" | |
138 |
|
138 | |||
139 | def __init__(self,color_scheme = 'NoColor'): |
|
139 | def __init__(self,color_scheme = 'NoColor'): | |
140 | ultratb.ListTB.__init__(self,color_scheme) |
|
140 | ultratb.ListTB.__init__(self,color_scheme) | |
141 | self.last_syntax_error = None |
|
141 | self.last_syntax_error = None | |
142 |
|
142 | |||
143 | def __call__(self, etype, value, elist): |
|
143 | def __call__(self, etype, value, elist): | |
144 | self.last_syntax_error = value |
|
144 | self.last_syntax_error = value | |
145 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
145 | ultratb.ListTB.__call__(self,etype,value,elist) | |
146 |
|
146 | |||
147 | def clear_err_state(self): |
|
147 | def clear_err_state(self): | |
148 | """Return the current error state and clear it""" |
|
148 | """Return the current error state and clear it""" | |
149 | e = self.last_syntax_error |
|
149 | e = self.last_syntax_error | |
150 | self.last_syntax_error = None |
|
150 | self.last_syntax_error = None | |
151 | return e |
|
151 | return e | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def get_default_editor(): |
|
154 | def get_default_editor(): | |
155 | try: |
|
155 | try: | |
156 | ed = os.environ['EDITOR'] |
|
156 | ed = os.environ['EDITOR'] | |
157 | except KeyError: |
|
157 | except KeyError: | |
158 | if os.name == 'posix': |
|
158 | if os.name == 'posix': | |
159 | ed = 'vi' # the only one guaranteed to be there! |
|
159 | ed = 'vi' # the only one guaranteed to be there! | |
160 | else: |
|
160 | else: | |
161 | ed = 'notepad' # same in Windows! |
|
161 | ed = 'notepad' # same in Windows! | |
162 | return ed |
|
162 | return ed | |
163 |
|
163 | |||
164 |
|
164 | |||
165 | class SeparateStr(Str): |
|
165 | class SeparateStr(Str): | |
166 | """A Str subclass to validate separate_in, separate_out, etc. |
|
166 | """A Str subclass to validate separate_in, separate_out, etc. | |
167 |
|
167 | |||
168 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. |
|
168 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. | |
169 | """ |
|
169 | """ | |
170 |
|
170 | |||
171 | def validate(self, obj, value): |
|
171 | def validate(self, obj, value): | |
172 | if value == '0': value = '' |
|
172 | if value == '0': value = '' | |
173 | value = value.replace('\\n','\n') |
|
173 | value = value.replace('\\n','\n') | |
174 | return super(SeparateStr, self).validate(obj, value) |
|
174 | return super(SeparateStr, self).validate(obj, value) | |
175 |
|
175 | |||
176 |
|
176 | |||
177 | #----------------------------------------------------------------------------- |
|
177 | #----------------------------------------------------------------------------- | |
178 | # Main IPython class |
|
178 | # Main IPython class | |
179 | #----------------------------------------------------------------------------- |
|
179 | #----------------------------------------------------------------------------- | |
180 |
|
180 | |||
181 |
|
181 | |||
182 | class InteractiveShell(Component, Magic): |
|
182 | class InteractiveShell(Component, Magic): | |
183 | """An enhanced, interactive shell for Python.""" |
|
183 | """An enhanced, interactive shell for Python.""" | |
184 |
|
184 | |||
185 | autocall = Enum((0,1,2), config_key='AUTOCALL') |
|
185 | autocall = Enum((0,1,2), config_key='AUTOCALL') | |
186 | autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX') |
|
186 | autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX') | |
187 | autoindent = CBool(True, config_key='AUTOINDENT') |
|
187 | autoindent = CBool(True, config_key='AUTOINDENT') | |
188 | automagic = CBool(True, config_key='AUTOMAGIC') |
|
188 | automagic = CBool(True, config_key='AUTOMAGIC') | |
189 | display_banner = CBool(True, config_key='DISPLAY_BANNER') |
|
189 | display_banner = CBool(True, config_key='DISPLAY_BANNER') | |
190 | banner = Str('') |
|
190 | banner = Str('') | |
191 | banner1 = Str(default_banner, config_key='BANNER1') |
|
191 | banner1 = Str(default_banner, config_key='BANNER1') | |
192 | banner2 = Str('', config_key='BANNER2') |
|
192 | banner2 = Str('', config_key='BANNER2') | |
193 | c = Str('', config_key='C') |
|
193 | c = Str('', config_key='C') | |
194 | cache_size = Int(1000, config_key='CACHE_SIZE') |
|
194 | cache_size = Int(1000, config_key='CACHE_SIZE') | |
195 | classic = CBool(False, config_key='CLASSIC') |
|
195 | classic = CBool(False, config_key='CLASSIC') | |
196 | color_info = CBool(True, config_key='COLOR_INFO') |
|
196 | color_info = CBool(True, config_key='COLOR_INFO') | |
197 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
197 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
198 | default_value='LightBG', config_key='COLORS') |
|
198 | default_value='LightBG', config_key='COLORS') | |
199 | confirm_exit = CBool(True, config_key='CONFIRM_EXIT') |
|
199 | confirm_exit = CBool(True, config_key='CONFIRM_EXIT') | |
200 | debug = CBool(False, config_key='DEBUG') |
|
200 | debug = CBool(False, config_key='DEBUG') | |
201 | deep_reload = CBool(False, config_key='DEEP_RELOAD') |
|
201 | deep_reload = CBool(False, config_key='DEEP_RELOAD') | |
202 | embedded = CBool(False) |
|
202 | embedded = CBool(False) | |
203 | embedded_active = CBool(False) |
|
203 | embedded_active = CBool(False) | |
204 | editor = Str(get_default_editor(), config_key='EDITOR') |
|
204 | editor = Str(get_default_editor(), config_key='EDITOR') | |
205 | filename = Str("<ipython console>") |
|
205 | filename = Str("<ipython console>") | |
206 | interactive = CBool(False, config_key='INTERACTIVE') |
|
206 | interactive = CBool(False, config_key='INTERACTIVE') | |
207 | ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__ |
|
207 | ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__ | |
208 | logstart = CBool(False, config_key='LOGSTART') |
|
208 | logstart = CBool(False, config_key='LOGSTART') | |
209 | logfile = Str('', config_key='LOGFILE') |
|
209 | logfile = Str('', config_key='LOGFILE') | |
210 | logplay = Str('', config_key='LOGPLAY') |
|
210 | logplay = Str('', config_key='LOGPLAY') | |
211 | multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS') |
|
211 | multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS') | |
212 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
212 | object_info_string_level = Enum((0,1,2), default_value=0, | |
213 | config_keys='OBJECT_INFO_STRING_LEVEL') |
|
213 | config_keys='OBJECT_INFO_STRING_LEVEL') | |
214 | pager = Str('less', config_key='PAGER') |
|
214 | pager = Str('less', config_key='PAGER') | |
215 | pdb = CBool(False, config_key='PDB') |
|
215 | pdb = CBool(False, config_key='PDB') | |
216 | pprint = CBool(True, config_key='PPRINT') |
|
216 | pprint = CBool(True, config_key='PPRINT') | |
217 | profile = Str('', config_key='PROFILE') |
|
217 | profile = Str('', config_key='PROFILE') | |
218 | prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1') |
|
218 | prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1') | |
219 | prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2') |
|
219 | prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2') | |
220 | prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1') |
|
220 | prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1') | |
221 | prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT') |
|
221 | prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT') | |
222 | quiet = CBool(False, config_key='QUIET') |
|
222 | quiet = CBool(False, config_key='QUIET') | |
223 |
|
223 | |||
224 | readline_use = CBool(True, config_key='READLINE_USE') |
|
224 | readline_use = CBool(True, config_key='READLINE_USE') | |
225 | readline_merge_completions = CBool(True, |
|
225 | readline_merge_completions = CBool(True, | |
226 | config_key='READLINE_MERGE_COMPLETIONS') |
|
226 | config_key='READLINE_MERGE_COMPLETIONS') | |
227 | readline_omit__names = Enum((0,1,2), default_value=0, |
|
227 | readline_omit__names = Enum((0,1,2), default_value=0, | |
228 | config_key='READLINE_OMIT_NAMES') |
|
228 | config_key='READLINE_OMIT_NAMES') | |
229 | readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS') |
|
229 | readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS') | |
230 | readline_parse_and_bind = List([ |
|
230 | readline_parse_and_bind = List([ | |
231 | 'tab: complete', |
|
231 | 'tab: complete', | |
232 | '"\C-l": possible-completions', |
|
232 | '"\C-l": possible-completions', | |
233 | 'set show-all-if-ambiguous on', |
|
233 | 'set show-all-if-ambiguous on', | |
234 | '"\C-o": tab-insert', |
|
234 | '"\C-o": tab-insert', | |
235 | '"\M-i": " "', |
|
235 | '"\M-i": " "', | |
236 | '"\M-o": "\d\d\d\d"', |
|
236 | '"\M-o": "\d\d\d\d"', | |
237 | '"\M-I": "\d\d\d\d"', |
|
237 | '"\M-I": "\d\d\d\d"', | |
238 | '"\C-r": reverse-search-history', |
|
238 | '"\C-r": reverse-search-history', | |
239 | '"\C-s": forward-search-history', |
|
239 | '"\C-s": forward-search-history', | |
240 | '"\C-p": history-search-backward', |
|
240 | '"\C-p": history-search-backward', | |
241 | '"\C-n": history-search-forward', |
|
241 | '"\C-n": history-search-forward', | |
242 | '"\e[A": history-search-backward', |
|
242 | '"\e[A": history-search-backward', | |
243 | '"\e[B": history-search-forward', |
|
243 | '"\e[B": history-search-forward', | |
244 | '"\C-k": kill-line', |
|
244 | '"\C-k": kill-line', | |
245 | '"\C-u": unix-line-discard', |
|
245 | '"\C-u": unix-line-discard', | |
246 | ], allow_none=False, config_key='READLINE_PARSE_AND_BIND' |
|
246 | ], allow_none=False, config_key='READLINE_PARSE_AND_BIND' | |
247 | ) |
|
247 | ) | |
248 |
|
248 | |||
249 | screen_length = Int(0, config_key='SCREEN_LENGTH') |
|
249 | screen_length = Int(0, config_key='SCREEN_LENGTH') | |
250 |
|
250 | |||
251 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' |
|
251 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' | |
252 | separate_in = SeparateStr('\n', config_key='SEPARATE_IN') |
|
252 | separate_in = SeparateStr('\n', config_key='SEPARATE_IN') | |
253 | separate_out = SeparateStr('', config_key='SEPARATE_OUT') |
|
253 | separate_out = SeparateStr('', config_key='SEPARATE_OUT') | |
254 | separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2') |
|
254 | separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2') | |
255 |
|
255 | |||
256 | system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER') |
|
256 | system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER') | |
257 | system_verbose = CBool(False, config_key='SYSTEM_VERBOSE') |
|
257 | system_verbose = CBool(False, config_key='SYSTEM_VERBOSE') | |
258 | term_title = CBool(False, config_key='TERM_TITLE') |
|
258 | term_title = CBool(False, config_key='TERM_TITLE') | |
259 | wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE') |
|
259 | wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE') | |
260 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
260 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
261 | default_value='Context', config_key='XMODE') |
|
261 | default_value='Context', config_key='XMODE') | |
262 |
|
262 | |||
263 | alias = List(allow_none=False, config_key='ALIAS') |
|
263 | alias = List(allow_none=False, config_key='ALIAS') | |
264 | autoexec = List(allow_none=False) |
|
264 | autoexec = List(allow_none=False) | |
265 |
|
265 | |||
266 | # class attribute to indicate whether the class supports threads or not. |
|
266 | # class attribute to indicate whether the class supports threads or not. | |
267 | # Subclasses with thread support should override this as needed. |
|
267 | # Subclasses with thread support should override this as needed. | |
268 | isthreaded = False |
|
268 | isthreaded = False | |
269 |
|
269 | |||
270 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, |
|
270 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
271 | user_ns=None, user_global_ns=None, |
|
271 | user_ns=None, user_global_ns=None, | |
272 | banner1=None, banner2=None, |
|
272 | banner1=None, banner2=None, | |
273 | custom_exceptions=((),None)): |
|
273 | custom_exceptions=((),None)): | |
274 |
|
274 | |||
275 | # This is where traitlets with a config_key argument are updated |
|
275 | # This is where traitlets with a config_key argument are updated | |
276 | # from the values on config. |
|
276 | # from the values on config. | |
277 | super(InteractiveShell, self).__init__(parent, config=config, name='__IP') |
|
277 | super(InteractiveShell, self).__init__(parent, config=config, name='__IP') | |
278 |
|
278 | |||
279 | # These are relatively independent and stateless |
|
279 | # These are relatively independent and stateless | |
280 | self.init_ipythondir(ipythondir) |
|
280 | self.init_ipythondir(ipythondir) | |
281 | self.init_instance_attrs() |
|
281 | self.init_instance_attrs() | |
282 | self.init_term_title() |
|
282 | self.init_term_title() | |
283 | self.init_usage(usage) |
|
283 | self.init_usage(usage) | |
284 | self.init_banner(banner1, banner2) |
|
284 | self.init_banner(banner1, banner2) | |
285 |
|
285 | |||
286 | # Create namespaces (user_ns, user_global_ns, alias_table, etc.) |
|
286 | # Create namespaces (user_ns, user_global_ns, alias_table, etc.) | |
287 | self.init_create_namespaces(user_ns, user_global_ns) |
|
287 | self.init_create_namespaces(user_ns, user_global_ns) | |
288 | # This has to be done after init_create_namespaces because it uses |
|
288 | # This has to be done after init_create_namespaces because it uses | |
289 | # something in self.user_ns, but before init_sys_modules, which |
|
289 | # something in self.user_ns, but before init_sys_modules, which | |
290 | # is the first thing to modify sys. |
|
290 | # is the first thing to modify sys. | |
291 | self.save_sys_module_state() |
|
291 | self.save_sys_module_state() | |
292 | self.init_sys_modules() |
|
292 | self.init_sys_modules() | |
293 |
|
293 | |||
294 | self.init_history() |
|
294 | self.init_history() | |
295 | self.init_encoding() |
|
295 | self.init_encoding() | |
296 | self.init_handlers() |
|
296 | self.init_handlers() | |
297 |
|
297 | |||
298 | Magic.__init__(self, self) |
|
298 | Magic.__init__(self, self) | |
299 |
|
299 | |||
300 | self.init_syntax_highlighting() |
|
300 | self.init_syntax_highlighting() | |
301 | self.init_hooks() |
|
301 | self.init_hooks() | |
302 | self.init_pushd_popd_magic() |
|
302 | self.init_pushd_popd_magic() | |
303 | self.init_traceback_handlers(custom_exceptions) |
|
303 | self.init_traceback_handlers(custom_exceptions) | |
304 | self.init_user_ns() |
|
304 | self.init_user_ns() | |
305 | self.init_logger() |
|
305 | self.init_logger() | |
306 | self.init_aliases() |
|
306 | self.init_aliases() | |
307 | self.init_builtins() |
|
307 | self.init_builtins() | |
308 |
|
308 | |||
309 | # pre_config_initialization |
|
309 | # pre_config_initialization | |
310 | self.init_shadow_hist() |
|
310 | self.init_shadow_hist() | |
311 |
|
311 | |||
312 | # The next section should contain averything that was in ipmaker. |
|
312 | # The next section should contain averything that was in ipmaker. | |
313 | self.init_logstart() |
|
313 | self.init_logstart() | |
314 |
|
314 | |||
315 | # The following was in post_config_initialization |
|
315 | # The following was in post_config_initialization | |
316 | self.init_inspector() |
|
316 | self.init_inspector() | |
317 | self.init_readline() |
|
317 | self.init_readline() | |
318 | self.init_prompts() |
|
318 | self.init_prompts() | |
319 | self.init_displayhook() |
|
319 | self.init_displayhook() | |
320 | self.init_reload_doctest() |
|
320 | self.init_reload_doctest() | |
321 | self.init_magics() |
|
321 | self.init_magics() | |
322 | self.init_pdb() |
|
322 | self.init_pdb() | |
323 | self.hooks.late_startup_hook() |
|
323 | self.hooks.late_startup_hook() | |
324 |
|
324 | |||
325 | def cleanup(self): |
|
|||
326 | self.restore_sys_module_state() |
|
|||
327 |
|
||||
328 | #------------------------------------------------------------------------- |
|
325 | #------------------------------------------------------------------------- | |
329 | # Traitlet changed handlers |
|
326 | # Traitlet changed handlers | |
330 | #------------------------------------------------------------------------- |
|
327 | #------------------------------------------------------------------------- | |
331 |
|
328 | |||
332 | def _banner1_changed(self): |
|
329 | def _banner1_changed(self): | |
333 | self.compute_banner() |
|
330 | self.compute_banner() | |
334 |
|
331 | |||
335 | def _banner2_changed(self): |
|
332 | def _banner2_changed(self): | |
336 | self.compute_banner() |
|
333 | self.compute_banner() | |
337 |
|
334 | |||
338 | @property |
|
335 | @property | |
339 | def usable_screen_length(self): |
|
336 | def usable_screen_length(self): | |
340 | if self.screen_length == 0: |
|
337 | if self.screen_length == 0: | |
341 | return 0 |
|
338 | return 0 | |
342 | else: |
|
339 | else: | |
343 | num_lines_bot = self.separate_in.count('\n')+1 |
|
340 | num_lines_bot = self.separate_in.count('\n')+1 | |
344 | return self.screen_length - num_lines_bot |
|
341 | return self.screen_length - num_lines_bot | |
345 |
|
342 | |||
346 | def _term_title_changed(self, name, new_value): |
|
343 | def _term_title_changed(self, name, new_value): | |
347 | self.init_term_title() |
|
344 | self.init_term_title() | |
348 |
|
345 | |||
|
346 | def set_autoindent(self,value=None): | |||
|
347 | """Set the autoindent flag, checking for readline support. | |||
|
348 | ||||
|
349 | If called with no arguments, it acts as a toggle.""" | |||
|
350 | ||||
|
351 | if not self.has_readline: | |||
|
352 | if os.name == 'posix': | |||
|
353 | warn("The auto-indent feature requires the readline library") | |||
|
354 | self.autoindent = 0 | |||
|
355 | return | |||
|
356 | if value is None: | |||
|
357 | self.autoindent = not self.autoindent | |||
|
358 | else: | |||
|
359 | self.autoindent = value | |||
|
360 | ||||
349 | #------------------------------------------------------------------------- |
|
361 | #------------------------------------------------------------------------- | |
350 | # init_* methods called by __init__ |
|
362 | # init_* methods called by __init__ | |
351 | #------------------------------------------------------------------------- |
|
363 | #------------------------------------------------------------------------- | |
352 |
|
364 | |||
353 | def init_ipythondir(self, ipythondir): |
|
365 | def init_ipythondir(self, ipythondir): | |
354 | if ipythondir is not None: |
|
366 | if ipythondir is not None: | |
355 | self.ipythondir = ipythondir |
|
367 | self.ipythondir = ipythondir | |
356 | self.config.IPYTHONDIR = self.ipythondir |
|
368 | self.config.IPYTHONDIR = self.ipythondir | |
357 | return |
|
369 | return | |
358 |
|
370 | |||
359 | if hasattr(self.config, 'IPYTHONDIR'): |
|
371 | if hasattr(self.config, 'IPYTHONDIR'): | |
360 | self.ipythondir = self.config.IPYTHONDIR |
|
372 | self.ipythondir = self.config.IPYTHONDIR | |
361 | if not hasattr(self.config, 'IPYTHONDIR'): |
|
373 | if not hasattr(self.config, 'IPYTHONDIR'): | |
362 | # cdw is always defined |
|
374 | # cdw is always defined | |
363 | self.ipythondir = os.getcwd() |
|
375 | self.ipythondir = os.getcwd() | |
364 |
|
376 | |||
365 | # The caller must make sure that ipythondir exists. We should |
|
377 | # The caller must make sure that ipythondir exists. We should | |
366 | # probably handle this using a Dir traitlet. |
|
378 | # probably handle this using a Dir traitlet. | |
367 | if not os.path.isdir(self.ipythondir): |
|
379 | if not os.path.isdir(self.ipythondir): | |
368 | raise IOError('IPython dir does not exist: %s' % self.ipythondir) |
|
380 | raise IOError('IPython dir does not exist: %s' % self.ipythondir) | |
369 |
|
381 | |||
370 | # All children can just read this |
|
382 | # All children can just read this | |
371 | self.config.IPYTHONDIR = self.ipythondir |
|
383 | self.config.IPYTHONDIR = self.ipythondir | |
372 |
|
384 | |||
373 | def init_instance_attrs(self): |
|
385 | def init_instance_attrs(self): | |
374 | self.jobs = BackgroundJobManager() |
|
386 | self.jobs = BackgroundJobManager() | |
375 | self.more = False |
|
387 | self.more = False | |
376 |
|
388 | |||
377 | # command compiler |
|
389 | # command compiler | |
378 | self.compile = codeop.CommandCompiler() |
|
390 | self.compile = codeop.CommandCompiler() | |
379 |
|
391 | |||
380 | # User input buffer |
|
392 | # User input buffer | |
381 | self.buffer = [] |
|
393 | self.buffer = [] | |
382 |
|
394 | |||
383 | # Make an empty namespace, which extension writers can rely on both |
|
395 | # Make an empty namespace, which extension writers can rely on both | |
384 | # existing and NEVER being used by ipython itself. This gives them a |
|
396 | # existing and NEVER being used by ipython itself. This gives them a | |
385 | # convenient location for storing additional information and state |
|
397 | # convenient location for storing additional information and state | |
386 | # their extensions may require, without fear of collisions with other |
|
398 | # their extensions may require, without fear of collisions with other | |
387 | # ipython names that may develop later. |
|
399 | # ipython names that may develop later. | |
388 | self.meta = Struct() |
|
400 | self.meta = Struct() | |
389 |
|
401 | |||
390 | # Object variable to store code object waiting execution. This is |
|
402 | # Object variable to store code object waiting execution. This is | |
391 | # used mainly by the multithreaded shells, but it can come in handy in |
|
403 | # used mainly by the multithreaded shells, but it can come in handy in | |
392 | # other situations. No need to use a Queue here, since it's a single |
|
404 | # other situations. No need to use a Queue here, since it's a single | |
393 | # item which gets cleared once run. |
|
405 | # item which gets cleared once run. | |
394 | self.code_to_run = None |
|
406 | self.code_to_run = None | |
395 |
|
407 | |||
396 | # Flag to mark unconditional exit |
|
408 | # Flag to mark unconditional exit | |
397 | self.exit_now = False |
|
409 | self.exit_now = False | |
398 |
|
410 | |||
399 | # Temporary files used for various purposes. Deleted at exit. |
|
411 | # Temporary files used for various purposes. Deleted at exit. | |
400 | self.tempfiles = [] |
|
412 | self.tempfiles = [] | |
401 |
|
413 | |||
402 | # Keep track of readline usage (later set by init_readline) |
|
414 | # Keep track of readline usage (later set by init_readline) | |
403 | self.has_readline = False |
|
415 | self.has_readline = False | |
404 |
|
416 | |||
405 | # keep track of where we started running (mainly for crash post-mortem) |
|
417 | # keep track of where we started running (mainly for crash post-mortem) | |
406 | # This is not being used anywhere currently. |
|
418 | # This is not being used anywhere currently. | |
407 | self.starting_dir = os.getcwd() |
|
419 | self.starting_dir = os.getcwd() | |
408 |
|
420 | |||
409 | # Indentation management |
|
421 | # Indentation management | |
410 | self.indent_current_nsp = 0 |
|
422 | self.indent_current_nsp = 0 | |
411 |
|
423 | |||
412 | def init_term_title(self): |
|
424 | def init_term_title(self): | |
413 | # Enable or disable the terminal title. |
|
425 | # Enable or disable the terminal title. | |
414 | if self.term_title: |
|
426 | if self.term_title: | |
415 | toggle_set_term_title(True) |
|
427 | toggle_set_term_title(True) | |
416 | set_term_title('IPython: ' + abbrev_cwd()) |
|
428 | set_term_title('IPython: ' + abbrev_cwd()) | |
417 | else: |
|
429 | else: | |
418 | toggle_set_term_title(False) |
|
430 | toggle_set_term_title(False) | |
419 |
|
431 | |||
420 | def init_usage(self, usage=None): |
|
432 | def init_usage(self, usage=None): | |
421 | if usage is None: |
|
433 | if usage is None: | |
422 | self.usage = interactive_usage |
|
434 | self.usage = interactive_usage | |
423 | else: |
|
435 | else: | |
424 | self.usage = usage |
|
436 | self.usage = usage | |
425 |
|
437 | |||
426 | def init_banner(self, banner1, banner2): |
|
438 | def init_banner(self, banner1, banner2): | |
427 | if self.c: # regular python doesn't print the banner with -c |
|
439 | if self.c: # regular python doesn't print the banner with -c | |
428 | self.display_banner = False |
|
440 | self.display_banner = False | |
429 | if banner1 is not None: |
|
441 | if banner1 is not None: | |
430 | self.banner1 = banner1 |
|
442 | self.banner1 = banner1 | |
431 | if banner2 is not None: |
|
443 | if banner2 is not None: | |
432 | self.banner2 = banner2 |
|
444 | self.banner2 = banner2 | |
433 | self.compute_banner() |
|
445 | self.compute_banner() | |
434 |
|
446 | |||
435 | def compute_banner(self): |
|
447 | def compute_banner(self): | |
436 | self.banner = self.banner1 + '\n' |
|
448 | self.banner = self.banner1 + '\n' | |
437 | if self.profile: |
|
449 | if self.profile: | |
438 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
450 | self.banner += '\nIPython profile: %s\n' % self.profile | |
439 | if self.banner2: |
|
451 | if self.banner2: | |
440 |
self.banner += '\n' + self.banner2 + '\n' |
|
452 | self.banner += '\n' + self.banner2 + '\n' | |
441 |
|
453 | |||
442 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
454 | def init_encoding(self): | |
443 | # Create the namespace where the user will operate. user_ns is |
|
455 | # Get system encoding at startup time. Certain terminals (like Emacs | |
444 | # normally the only one used, and it is passed to the exec calls as |
|
456 | # under Win32 have it set to None, and we need to have a known valid | |
445 | # the locals argument. But we do carry a user_global_ns namespace |
|
457 | # encoding to use in the raw_input() method | |
446 | # given as the exec 'globals' argument, This is useful in embedding |
|
458 | try: | |
447 | # situations where the ipython shell opens in a context where the |
|
459 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
448 | # distinction between locals and globals is meaningful. For |
|
460 | except AttributeError: | |
449 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
461 | self.stdin_encoding = 'ascii' | |
450 |
|
||||
451 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
|||
452 | # level as a dict instead of a module. This is a manual fix, but I |
|
|||
453 | # should really track down where the problem is coming from. Alex |
|
|||
454 | # Schmolck reported this problem first. |
|
|||
455 |
|
||||
456 | # A useful post by Alex Martelli on this topic: |
|
|||
457 | # Re: inconsistent value from __builtins__ |
|
|||
458 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
|||
459 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
|||
460 | # Gruppen: comp.lang.python |
|
|||
461 |
|
||||
462 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
|||
463 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
|||
464 | # > <type 'dict'> |
|
|||
465 | # > >>> print type(__builtins__) |
|
|||
466 | # > <type 'module'> |
|
|||
467 | # > Is this difference in return value intentional? |
|
|||
468 |
|
462 | |||
469 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
463 | def init_syntax_highlighting(self): | |
470 | # or a module, and it's been that way for a long time. Whether it's |
|
464 | # Python source parser/formatter for syntax highlighting | |
471 | # intentional (or sensible), I don't know. In any case, the idea is |
|
465 | pyformat = PyColorize.Parser().format | |
472 | # that if you need to access the built-in namespace directly, you |
|
466 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
473 | # should start with "import __builtin__" (note, no 's') which will |
|
|||
474 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
|||
475 |
|
467 | |||
476 | # These routines return properly built dicts as needed by the rest of |
|
468 | def init_pushd_popd_magic(self): | |
477 | # the code, and can also be used by extension writers to generate |
|
469 | # for pushd/popd management | |
478 | # properly initialized namespaces. |
|
470 | try: | |
479 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
471 | self.home_dir = get_home_dir() | |
480 | user_global_ns) |
|
472 | except HomeDirError, msg: | |
|
473 | fatal(msg) | |||
481 |
|
474 | |||
482 | # Assign namespaces |
|
475 | self.dir_stack = [] | |
483 | # This is the namespace where all normal user variables live |
|
|||
484 | self.user_ns = user_ns |
|
|||
485 | self.user_global_ns = user_global_ns |
|
|||
486 |
|
476 | |||
487 | # An auxiliary namespace that checks what parts of the user_ns were |
|
477 | def init_logger(self): | |
488 | # loaded at startup, so we can list later only variables defined in |
|
478 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
489 | # actual interactive use. Since it is always a subset of user_ns, it |
|
479 | # local shortcut, this is used a LOT | |
490 | # doesn't need to be seaparately tracked in the ns_table |
|
480 | self.log = self.logger.log | |
491 | self.user_config_ns = {} |
|
481 | # template for logfile headers. It gets resolved at runtime by the | |
|
482 | # logstart method. | |||
|
483 | self.loghead_tpl = \ | |||
|
484 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |||
|
485 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |||
|
486 | #log# opts = %s | |||
|
487 | #log# args = %s | |||
|
488 | #log# It is safe to make manual edits below here. | |||
|
489 | #log#----------------------------------------------------------------------- | |||
|
490 | """ | |||
492 |
|
491 | |||
493 | # A namespace to keep track of internal data structures to prevent |
|
492 | def init_logstart(self): | |
494 | # them from cluttering user-visible stuff. Will be updated later |
|
493 | if self.logplay: | |
495 | self.internal_ns = {} |
|
494 | self.magic_logstart(self.logplay + ' append') | |
|
495 | elif self.logfile: | |||
|
496 | self.magic_logstart(self.logfile) | |||
|
497 | elif self.logstart: | |||
|
498 | self.magic_logstart() | |||
496 |
|
499 | |||
497 | # Namespace of system aliases. Each entry in the alias |
|
500 | def init_builtins(self): | |
498 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
501 | self.builtin_trap = BuiltinTrap(self) | |
499 | # of positional arguments of the alias. |
|
|||
500 | self.alias_table = {} |
|
|||
501 |
|
502 | |||
502 | # Now that FakeModule produces a real module, we've run into a nasty |
|
503 | def init_inspector(self): | |
503 | # problem: after script execution (via %run), the module where the user |
|
504 | # Object inspector | |
504 | # code ran is deleted. Now that this object is a true module (needed |
|
505 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
505 | # so docetst and other tools work correctly), the Python module |
|
506 | PyColorize.ANSICodeColors, | |
506 | # teardown mechanism runs over it, and sets to None every variable |
|
507 | 'NoColor', | |
507 | # present in that module. Top-level references to objects from the |
|
508 | self.object_info_string_level) | |
508 | # script survive, because the user_ns is updated with them. However, |
|
|||
509 | # calling functions defined in the script that use other things from |
|
|||
510 | # the script will fail, because the function's closure had references |
|
|||
511 | # to the original objects, which are now all None. So we must protect |
|
|||
512 | # these modules from deletion by keeping a cache. |
|
|||
513 | # |
|
|||
514 | # To avoid keeping stale modules around (we only need the one from the |
|
|||
515 | # last run), we use a dict keyed with the full path to the script, so |
|
|||
516 | # only the last version of the module is held in the cache. Note, |
|
|||
517 | # however, that we must cache the module *namespace contents* (their |
|
|||
518 | # __dict__). Because if we try to cache the actual modules, old ones |
|
|||
519 | # (uncached) could be destroyed while still holding references (such as |
|
|||
520 | # those held by GUI objects that tend to be long-lived)> |
|
|||
521 | # |
|
|||
522 | # The %reset command will flush this cache. See the cache_main_mod() |
|
|||
523 | # and clear_main_mod_cache() methods for details on use. |
|
|||
524 |
|
509 | |||
525 | # This is the cache used for 'main' namespaces |
|
510 | def init_prompts(self): | |
526 | self._main_ns_cache = {} |
|
511 | # Initialize cache, set in/out prompts and printing system | |
527 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
512 | self.outputcache = CachedOutput(self, | |
528 | # copying and clearing for reuse on each %run |
|
513 | self.cache_size, | |
529 | self._user_main_module = FakeModule() |
|
514 | self.pprint, | |
|
515 | input_sep = self.separate_in, | |||
|
516 | output_sep = self.separate_out, | |||
|
517 | output_sep2 = self.separate_out2, | |||
|
518 | ps1 = self.prompt_in1, | |||
|
519 | ps2 = self.prompt_in2, | |||
|
520 | ps_out = self.prompt_out, | |||
|
521 | pad_left = self.prompts_pad_left) | |||
530 |
|
522 | |||
531 | # A table holding all the namespaces IPython deals with, so that |
|
523 | # user may have over-ridden the default print hook: | |
532 | # introspection facilities can search easily. |
|
524 | try: | |
533 | self.ns_table = {'user':user_ns, |
|
525 | self.outputcache.__class__.display = self.hooks.display | |
534 | 'user_global':user_global_ns, |
|
526 | except AttributeError: | |
535 | 'alias':self.alias_table, |
|
527 | pass | |
536 | 'internal':self.internal_ns, |
|
|||
537 | 'builtin':__builtin__.__dict__ |
|
|||
538 | } |
|
|||
539 |
|
528 | |||
540 | # Similarly, track all namespaces where references can be held and that |
|
529 | def init_displayhook(self): | |
541 | # we can safely clear (so it can NOT include builtin). This one can be |
|
530 | self.display_trap = DisplayTrap(self, self.outputcache) | |
542 | # a simple list. |
|
|||
543 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
|||
544 | self.alias_table, self.internal_ns, |
|
|||
545 | self._main_ns_cache ] |
|
|||
546 |
|
531 | |||
547 |
def init_ |
|
532 | def init_reload_doctest(self): | |
548 | # We need to insert into sys.modules something that looks like a |
|
533 | # Do a proper resetting of doctest, including the necessary displayhook | |
549 | # module but which accesses the IPython namespace, for shelve and |
|
534 | # monkeypatching | |
550 | # pickle to work interactively. Normally they rely on getting |
|
535 | try: | |
551 | # everything out of __main__, but for embedding purposes each IPython |
|
536 | doctest_reload() | |
552 | # instance has its own private namespace, so we can't go shoving |
|
537 | except ImportError: | |
553 | # everything into __main__. |
|
538 | warn("doctest module does not exist.") | |
554 |
|
539 | |||
555 | # note, however, that we should only do this for non-embedded |
|
540 | #------------------------------------------------------------------------- | |
556 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
541 | # Things related to injections into the sys module | |
557 | # namespace. Embedded instances, on the other hand, should not do |
|
542 | #------------------------------------------------------------------------- | |
558 | # this because they need to manage the user local/global namespaces |
|
|||
559 | # only, but they live within a 'normal' __main__ (meaning, they |
|
|||
560 | # shouldn't overtake the execution environment of the script they're |
|
|||
561 | # embedded in). |
|
|||
562 |
|
543 | |||
563 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
544 | def save_sys_module_state(self): | |
|
545 | """Save the state of hooks in the sys module. | |||
564 |
|
|
546 | ||
|
547 | This has to be called after self.user_ns is created. | |||
|
548 | """ | |||
|
549 | self._orig_sys_module_state = {} | |||
|
550 | self._orig_sys_module_state['stdin'] = sys.stdin | |||
|
551 | self._orig_sys_module_state['stdout'] = sys.stdout | |||
|
552 | self._orig_sys_module_state['stderr'] = sys.stderr | |||
|
553 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |||
565 | try: |
|
554 | try: | |
566 | main_name = self.user_ns['__name__'] |
|
555 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
567 | except KeyError: |
|
556 | except KeyError: | |
568 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
557 | pass | |
569 | else: |
|
|||
570 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
|||
571 |
|
558 | |||
572 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
559 | def restore_sys_module_state(self): | |
573 | """Return a valid local and global user interactive namespaces. |
|
560 | """Restore the state of the sys module.""" | |
|
561 | try: | |||
|
562 | for k, v in self._orig_sys_module_state.items(): | |||
|
563 | setattr(sys, k, v) | |||
|
564 | except AttributeError: | |||
|
565 | pass | |||
|
566 | try: | |||
|
567 | delattr(sys, 'ipcompleter') | |||
|
568 | except AttributeError: | |||
|
569 | pass | |||
|
570 | # Reset what what done in self.init_sys_modules | |||
|
571 | try: | |||
|
572 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |||
|
573 | except (AttributeError, KeyError): | |||
|
574 | pass | |||
574 |
|
575 | |||
575 | This builds a dict with the minimal information needed to operate as a |
|
576 | #------------------------------------------------------------------------- | |
576 | valid IPython user namespace, which you can pass to the various |
|
577 | # Things related to hooks | |
577 | embedding classes in ipython. The default implementation returns the |
|
578 | #------------------------------------------------------------------------- | |
578 | same dict for both the locals and the globals to allow functions to |
|
|||
579 | refer to variables in the namespace. Customized implementations can |
|
|||
580 | return different dicts. The locals dictionary can actually be anything |
|
|||
581 | following the basic mapping protocol of a dict, but the globals dict |
|
|||
582 | must be a true dict, not even a subclass. It is recommended that any |
|
|||
583 | custom object for the locals namespace synchronize with the globals |
|
|||
584 | dict somehow. |
|
|||
585 |
|
579 | |||
586 | Raises TypeError if the provided globals namespace is not a true dict. |
|
580 | def init_hooks(self): | |
|
581 | # hooks holds pointers used for user-side customizations | |||
|
582 | self.hooks = Struct() | |||
587 |
|
583 | |||
588 | :Parameters: |
|
584 | self.strdispatchers = {} | |
589 | user_ns : dict-like, optional |
|
|||
590 | The current user namespace. The items in this namespace should |
|
|||
591 | be included in the output. If None, an appropriate blank |
|
|||
592 | namespace should be created. |
|
|||
593 | user_global_ns : dict, optional |
|
|||
594 | The current user global namespace. The items in this namespace |
|
|||
595 | should be included in the output. If None, an appropriate |
|
|||
596 | blank namespace should be created. |
|
|||
597 |
|
585 | |||
598 | :Returns: |
|
586 | # Set all default hooks, defined in the IPython.hooks module. | |
599 | A tuple pair of dictionary-like object to be used as the local namespace |
|
587 | import IPython.core.hooks | |
600 | of the interpreter and a dict to be used as the global namespace. |
|
588 | hooks = IPython.core.hooks | |
601 | """ |
|
589 | for hook_name in hooks.__all__: | |
|
590 | # default hooks have priority 100, i.e. low; user hooks should have | |||
|
591 | # 0-100 priority | |||
|
592 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |||
602 |
|
593 | |||
603 | if user_ns is None: |
|
594 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
604 | # Set __name__ to __main__ to better match the behavior of the |
|
595 | """set_hook(name,hook) -> sets an internal IPython hook. | |
605 | # normal interpreter. |
|
|||
606 | user_ns = {'__name__' :'__main__', |
|
|||
607 | '__builtins__' : __builtin__, |
|
|||
608 | } |
|
|||
609 | else: |
|
|||
610 | user_ns.setdefault('__name__','__main__') |
|
|||
611 | user_ns.setdefault('__builtins__',__builtin__) |
|
|||
612 |
|
|
596 | ||
613 | if user_global_ns is None: |
|
597 | IPython exposes some of its internal API as user-modifiable hooks. By | |
614 | user_global_ns = user_ns |
|
598 | adding your function to one of these hooks, you can modify IPython's | |
615 | if type(user_global_ns) is not dict: |
|
599 | behavior to call at runtime your own routines.""" | |
616 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
|||
617 | % type(user_global_ns)) |
|
|||
618 |
|
600 | |||
619 | return user_ns, user_global_ns |
|
601 | # At some point in the future, this should validate the hook before it | |
|
602 | # accepts it. Probably at least check that the hook takes the number | |||
|
603 | # of args it's supposed to. | |||
620 |
|
604 | |||
621 | def init_history(self): |
|
605 | f = new.instancemethod(hook,self,self.__class__) | |
622 | # List of input with multi-line handling. |
|
|||
623 | self.input_hist = InputList() |
|
|||
624 | # This one will hold the 'raw' input history, without any |
|
|||
625 | # pre-processing. This will allow users to retrieve the input just as |
|
|||
626 | # it was exactly typed in by the user, with %hist -r. |
|
|||
627 | self.input_hist_raw = InputList() |
|
|||
628 |
|
606 | |||
629 | # list of visited directories |
|
607 | # check if the hook is for strdispatcher first | |
630 | try: |
|
608 | if str_key is not None: | |
631 | self.dir_hist = [os.getcwd()] |
|
609 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
632 | except OSError: |
|
610 | sdp.add_s(str_key, f, priority ) | |
633 |
self. |
|
611 | self.strdispatchers[name] = sdp | |
|
612 | return | |||
|
613 | if re_key is not None: | |||
|
614 | sdp = self.strdispatchers.get(name, StrDispatch()) | |||
|
615 | sdp.add_re(re.compile(re_key), f, priority ) | |||
|
616 | self.strdispatchers[name] = sdp | |||
|
617 | return | |||
634 |
|
618 | |||
635 | # dict of output history |
|
619 | dp = getattr(self.hooks, name, None) | |
636 | self.output_hist = {} |
|
620 | if name not in IPython.core.hooks.__all__: | |
|
621 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |||
|
622 | if not dp: | |||
|
623 | dp = IPython.core.hooks.CommandChainDispatcher() | |||
637 |
|
624 | |||
638 | # Now the history file |
|
|||
639 | try: |
|
625 | try: | |
640 | histfname = 'history-%s' % self.profile |
|
626 | dp.add(f,priority) | |
641 | except AttributeError: |
|
627 | except AttributeError: | |
642 | histfname = 'history' |
|
628 | # it was not commandchain, plain old func - replace | |
643 | self.histfile = os.path.join(self.config.IPYTHONDIR, histfname) |
|
629 | dp = f | |
644 |
|
630 | |||
645 | # Fill the history zero entry, user counter starts at 1 |
|
631 | setattr(self.hooks,name, dp) | |
646 | self.input_hist.append('\n') |
|
|||
647 | self.input_hist_raw.append('\n') |
|
|||
648 |
|
632 | |||
649 | def init_encoding(self): |
|
633 | #------------------------------------------------------------------------- | |
650 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
634 | # Things related to the "main" module | |
651 | # under Win32 have it set to None, and we need to have a known valid |
|
635 | #------------------------------------------------------------------------- | |
652 | # encoding to use in the raw_input() method |
|
|||
653 | try: |
|
|||
654 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
|||
655 | except AttributeError: |
|
|||
656 | self.stdin_encoding = 'ascii' |
|
|||
657 |
|
636 | |||
658 |
def |
|
637 | def new_main_mod(self,ns=None): | |
659 | # escapes for automatic behavior on the command line |
|
638 | """Return a new 'main' module object for user code execution. | |
660 | self.ESC_SHELL = '!' |
|
639 | """ | |
661 | self.ESC_SH_CAP = '!!' |
|
640 | main_mod = self._user_main_module | |
662 | self.ESC_HELP = '?' |
|
641 | init_fakemod_dict(main_mod,ns) | |
663 | self.ESC_MAGIC = '%' |
|
642 | return main_mod | |
664 | self.ESC_QUOTE = ',' |
|
|||
665 | self.ESC_QUOTE2 = ';' |
|
|||
666 | self.ESC_PAREN = '/' |
|
|||
667 |
|
643 | |||
668 | # And their associated handlers |
|
644 | def cache_main_mod(self,ns,fname): | |
669 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
645 | """Cache a main module's namespace. | |
670 | self.ESC_QUOTE : self.handle_auto, |
|
|||
671 | self.ESC_QUOTE2 : self.handle_auto, |
|
|||
672 | self.ESC_MAGIC : self.handle_magic, |
|
|||
673 | self.ESC_HELP : self.handle_help, |
|
|||
674 | self.ESC_SHELL : self.handle_shell_escape, |
|
|||
675 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
|||
676 | } |
|
|||
677 |
|
|
646 | ||
678 | def init_syntax_highlighting(self): |
|
647 | When scripts are executed via %run, we must keep a reference to the | |
679 | # Python source parser/formatter for syntax highlighting |
|
648 | namespace of their __main__ module (a FakeModule instance) around so | |
680 | pyformat = PyColorize.Parser().format |
|
649 | that Python doesn't clear it, rendering objects defined therein | |
681 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
650 | useless. | |
682 |
|
|
651 | ||
683 | def init_hooks(self): |
|
652 | This method keeps said reference in a private dict, keyed by the | |
684 | # hooks holds pointers used for user-side customizations |
|
653 | absolute path of the module object (which corresponds to the script | |
685 | self.hooks = Struct() |
|
654 | path). This way, for multiple executions of the same script we only | |
|
655 | keep one copy of the namespace (the last one), thus preventing memory | |||
|
656 | leaks from old references while allowing the objects from the last | |||
|
657 | execution to be accessible. | |||
686 |
|
658 | |||
687 | self.strdispatchers = {} |
|
659 | Note: we can not allow the actual FakeModule instances to be deleted, | |
|
660 | because of how Python tears down modules (it hard-sets all their | |||
|
661 | references to None without regard for reference counts). This method | |||
|
662 | must therefore make a *copy* of the given namespace, to allow the | |||
|
663 | original module's __dict__ to be cleared and reused. | |||
688 |
|
664 | |||
689 | # Set all default hooks, defined in the IPython.hooks module. |
|
|||
690 | import IPython.core.hooks |
|
|||
691 | hooks = IPython.core.hooks |
|
|||
692 | for hook_name in hooks.__all__: |
|
|||
693 | # default hooks have priority 100, i.e. low; user hooks should have |
|
|||
694 | # 0-100 priority |
|
|||
695 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
|||
696 |
|
665 | |||
697 | def init_pushd_popd_magic(self): |
|
666 | Parameters | |
698 | # for pushd/popd management |
|
667 | ---------- | |
699 | try: |
|
668 | ns : a namespace (a dict, typically) | |
700 | self.home_dir = get_home_dir() |
|
|||
701 | except HomeDirError, msg: |
|
|||
702 | fatal(msg) |
|
|||
703 |
|
|
669 | ||
704 | self.dir_stack = [] |
|
670 | fname : str | |
|
671 | Filename associated with the namespace. | |||
705 |
|
|
672 | ||
706 | def init_traceback_handlers(self, custom_exceptions): |
|
673 | Examples | |
707 | # Syntax error handler. |
|
674 | -------- | |
708 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
|||
709 |
|
675 | |||
710 | # The interactive one is initialized with an offset, meaning we always |
|
676 | In [10]: import IPython | |
711 | # want to remove the topmost item in the traceback, which is our own |
|
|||
712 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
|||
713 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
|||
714 | color_scheme='NoColor', |
|
|||
715 | tb_offset = 1) |
|
|||
716 |
|
|
677 | ||
717 | # IPython itself shouldn't crash. This will produce a detailed |
|
678 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
718 | # post-mortem if it does. But we only install the crash handler for |
|
|||
719 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
|||
720 | # and lose the crash handler. This is because exceptions in the main |
|
|||
721 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
|||
722 | # and there's no point in printing crash dumps for every user exception. |
|
|||
723 | if self.isthreaded: |
|
|||
724 | ipCrashHandler = ultratb.FormattedTB() |
|
|||
725 | else: |
|
|||
726 | from IPython.core import crashhandler |
|
|||
727 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
|||
728 | self.set_crash_handler(ipCrashHandler) |
|
|||
729 |
|
|
679 | ||
730 | # and add any custom exception handlers the user may have specified |
|
680 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
731 | self.set_custom_exc(*custom_exceptions) |
|
681 | Out[12]: True | |
|
682 | """ | |||
|
683 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |||
732 |
|
684 | |||
733 |
def |
|
685 | def clear_main_mod_cache(self): | |
734 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
686 | """Clear the cache of main modules. | |
735 | # local shortcut, this is used a LOT |
|
687 | ||
736 | self.log = self.logger.log |
|
688 | Mainly for use by utilities like %reset. | |
737 | # template for logfile headers. It gets resolved at runtime by the |
|
689 | ||
738 | # logstart method. |
|
690 | Examples | |
739 | self.loghead_tpl = \ |
|
691 | -------- | |
740 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
692 | ||
741 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
693 | In [15]: import IPython | |
742 | #log# opts = %s |
|
694 | ||
743 | #log# args = %s |
|
695 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
744 | #log# It is safe to make manual edits below here. |
|
696 | ||
745 | #log#----------------------------------------------------------------------- |
|
697 | In [17]: len(_ip._main_ns_cache) > 0 | |
|
698 | Out[17]: True | |||
|
699 | ||||
|
700 | In [18]: _ip.clear_main_mod_cache() | |||
|
701 | ||||
|
702 | In [19]: len(_ip._main_ns_cache) == 0 | |||
|
703 | Out[19]: True | |||
746 | """ |
|
704 | """ | |
|
705 | self._main_ns_cache.clear() | |||
747 |
|
706 | |||
748 | def init_logstart(self): |
|
707 | #------------------------------------------------------------------------- | |
749 | if self.logplay: |
|
708 | # Things related to debugging | |
750 | self.magic_logstart(self.logplay + ' append') |
|
709 | #------------------------------------------------------------------------- | |
751 | elif self.logfile: |
|
|||
752 | self.magic_logstart(self.logfile) |
|
|||
753 | elif self.logstart: |
|
|||
754 | self.magic_logstart() |
|
|||
755 |
|
710 | |||
756 |
def init_ |
|
711 | def init_pdb(self): | |
757 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
712 | # Set calling of pdb on exceptions | |
758 | no_alias = {} |
|
713 | # self.call_pdb is a property | |
759 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
714 | self.call_pdb = self.pdb | |
760 | for key in keyword.kwlist + no_alias_magics: |
|
|||
761 | no_alias[key] = 1 |
|
|||
762 | no_alias.update(__builtin__.__dict__) |
|
|||
763 | self.no_alias = no_alias |
|
|||
764 |
|
715 | |||
765 | # Make some aliases automatically |
|
716 | def _get_call_pdb(self): | |
766 | # Prepare list of shell aliases to auto-define |
|
717 | return self._call_pdb | |
767 | if os.name == 'posix': |
|
|||
768 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
|||
769 | 'mv mv -i','rm rm -i','cp cp -i', |
|
|||
770 | 'cat cat','less less','clear clear', |
|
|||
771 | # a better ls |
|
|||
772 | 'ls ls -F', |
|
|||
773 | # long ls |
|
|||
774 | 'll ls -lF') |
|
|||
775 | # Extra ls aliases with color, which need special treatment on BSD |
|
|||
776 | # variants |
|
|||
777 | ls_extra = ( # color ls |
|
|||
778 | 'lc ls -F -o --color', |
|
|||
779 | # ls normal files only |
|
|||
780 | 'lf ls -F -o --color %l | grep ^-', |
|
|||
781 | # ls symbolic links |
|
|||
782 | 'lk ls -F -o --color %l | grep ^l', |
|
|||
783 | # directories or links to directories, |
|
|||
784 | 'ldir ls -F -o --color %l | grep /$', |
|
|||
785 | # things which are executable |
|
|||
786 | 'lx ls -F -o --color %l | grep ^-..x', |
|
|||
787 | ) |
|
|||
788 | # The BSDs don't ship GNU ls, so they don't understand the |
|
|||
789 | # --color switch out of the box |
|
|||
790 | if 'bsd' in sys.platform: |
|
|||
791 | ls_extra = ( # ls normal files only |
|
|||
792 | 'lf ls -lF | grep ^-', |
|
|||
793 | # ls symbolic links |
|
|||
794 | 'lk ls -lF | grep ^l', |
|
|||
795 | # directories or links to directories, |
|
|||
796 | 'ldir ls -lF | grep /$', |
|
|||
797 | # things which are executable |
|
|||
798 | 'lx ls -lF | grep ^-..x', |
|
|||
799 | ) |
|
|||
800 | auto_alias = auto_alias + ls_extra |
|
|||
801 | elif os.name in ['nt','dos']: |
|
|||
802 | auto_alias = ('ls dir /on', |
|
|||
803 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
|||
804 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
|||
805 | 'ren ren','cls cls','copy copy') |
|
|||
806 | else: |
|
|||
807 | auto_alias = () |
|
|||
808 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
|||
809 |
|
718 | |||
810 | # Load default aliases |
|
719 | def _set_call_pdb(self,val): | |
811 | for alias, cmd in self.auto_alias: |
|
|||
812 | self.define_alias(alias,cmd) |
|
|||
813 |
|
720 | |||
814 | # Load user aliases |
|
721 | if val not in (0,1,False,True): | |
815 | for alias in self.alias: |
|
722 | raise ValueError,'new call_pdb value must be boolean' | |
816 | self.magic_alias(alias) |
|
|||
817 |
|
723 | |||
818 | def init_builtins(self): |
|
724 | # store value in instance | |
819 | self.builtin_trap = BuiltinTrap(self) |
|
725 | self._call_pdb = val | |
820 |
|
726 | |||
821 | def init_shadow_hist(self): |
|
727 | # notify the actual exception handlers | |
|
728 | self.InteractiveTB.call_pdb = val | |||
|
729 | if self.isthreaded: | |||
822 | try: |
|
730 | try: | |
823 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") |
|
731 | self.sys_excepthook.call_pdb = val | |
824 | except exceptions.UnicodeDecodeError: |
|
732 | except: | |
825 | print "Your ipythondir can't be decoded to unicode!" |
|
733 | warn('Failed to activate pdb for threaded exception handler') | |
826 | print "Please set HOME environment variable to something that" |
|
|||
827 | print r"only has ASCII characters, e.g. c:\home" |
|
|||
828 | print "Now it is", self.config.IPYTHONDIR |
|
|||
829 | sys.exit() |
|
|||
830 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
|||
831 |
|
734 | |||
832 | def init_inspector(self): |
|
735 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
833 | # Object inspector |
|
736 | 'Control auto-activation of pdb at exceptions') | |
834 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
|||
835 | PyColorize.ANSICodeColors, |
|
|||
836 | 'NoColor', |
|
|||
837 | self.object_info_string_level) |
|
|||
838 |
|
737 | |||
839 | def init_readline(self): |
|
738 | def debugger(self,force=False): | |
840 | """Command history completion/saving/reloading.""" |
|
739 | """Call the pydb/pdb debugger. | |
841 |
|
|
740 | ||
842 | self.rl_next_input = None |
|
741 | Keywords: | |
843 | self.rl_do_indent = False |
|
|||
844 |
|
|
742 | ||
845 | if not self.readline_use: |
|
743 | - force(False): by default, this routine checks the instance call_pdb | |
|
744 | flag and does not actually invoke the debugger if the flag is false. | |||
|
745 | The 'force' option forces the debugger to activate even if the flag | |||
|
746 | is false. | |||
|
747 | """ | |||
|
748 | ||||
|
749 | if not (force or self.call_pdb): | |||
846 | return |
|
750 | return | |
847 |
|
751 | |||
848 | import IPython.utils.rlineimpl as readline |
|
752 | if not hasattr(sys,'last_traceback'): | |
|
753 | error('No traceback has been produced, nothing to debug.') | |||
|
754 | return | |||
849 |
|
755 | |||
850 | if not readline.have_readline: |
|
756 | # use pydb if available | |
851 | self.has_readline = 0 |
|
757 | if debugger.has_pydb: | |
852 | self.readline = None |
|
758 | from pydb import pm | |
853 | # no point in bugging windows users with this every time: |
|
|||
854 | warn('Readline services not available on this platform.') |
|
|||
855 | else: |
|
|||
856 | sys.modules['readline'] = readline |
|
|||
857 | import atexit |
|
|||
858 | from IPython.core.completer import IPCompleter |
|
|||
859 | self.Completer = IPCompleter(self, |
|
|||
860 | self.user_ns, |
|
|||
861 | self.user_global_ns, |
|
|||
862 | self.readline_omit__names, |
|
|||
863 | self.alias_table) |
|
|||
864 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
|||
865 | self.strdispatchers['complete_command'] = sdisp |
|
|||
866 | self.Completer.custom_completers = sdisp |
|
|||
867 | # Platform-specific configuration |
|
|||
868 | if os.name == 'nt': |
|
|||
869 | self.readline_startup_hook = readline.set_pre_input_hook |
|
|||
870 |
|
|
759 | else: | |
871 | self.readline_startup_hook = readline.set_startup_hook |
|
760 | # fallback to our internal debugger | |
|
761 | pm = lambda : self.InteractiveTB.debugger(force=True) | |||
|
762 | self.history_saving_wrapper(pm)() | |||
872 |
|
763 | |||
873 | # Load user's initrc file (readline config) |
|
764 | #------------------------------------------------------------------------- | |
874 | # Or if libedit is used, load editrc. |
|
765 | # Things related to IPython's various namespaces | |
875 | inputrc_name = os.environ.get('INPUTRC') |
|
766 | #------------------------------------------------------------------------- | |
876 | if inputrc_name is None: |
|
|||
877 | home_dir = get_home_dir() |
|
|||
878 | if home_dir is not None: |
|
|||
879 | inputrc_name = '.inputrc' |
|
|||
880 | if readline.uses_libedit: |
|
|||
881 | inputrc_name = '.editrc' |
|
|||
882 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
|||
883 | if os.path.isfile(inputrc_name): |
|
|||
884 | try: |
|
|||
885 | readline.read_init_file(inputrc_name) |
|
|||
886 | except: |
|
|||
887 | warn('Problems reading readline initialization file <%s>' |
|
|||
888 | % inputrc_name) |
|
|||
889 |
|
767 | |||
890 | self.has_readline = 1 |
|
768 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
891 | self.readline = readline |
|
769 | # Create the namespace where the user will operate. user_ns is | |
892 | # save this in sys so embedded copies can restore it properly |
|
770 | # normally the only one used, and it is passed to the exec calls as | |
893 | sys.ipcompleter = self.Completer.complete |
|
771 | # the locals argument. But we do carry a user_global_ns namespace | |
894 | self.set_completer() |
|
772 | # given as the exec 'globals' argument, This is useful in embedding | |
|
773 | # situations where the ipython shell opens in a context where the | |||
|
774 | # distinction between locals and globals is meaningful. For | |||
|
775 | # non-embedded contexts, it is just the same object as the user_ns dict. | |||
895 |
|
776 | |||
896 | # Configure readline according to user's prefs |
|
777 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
897 | # This is only done if GNU readline is being used. If libedit |
|
778 | # level as a dict instead of a module. This is a manual fix, but I | |
898 | # is being used (as on Leopard) the readline config is |
|
779 | # should really track down where the problem is coming from. Alex | |
899 | # not run as the syntax for libedit is different. |
|
780 | # Schmolck reported this problem first. | |
900 | if not readline.uses_libedit: |
|
|||
901 | for rlcommand in self.readline_parse_and_bind: |
|
|||
902 | #print "loading rl:",rlcommand # dbg |
|
|||
903 | readline.parse_and_bind(rlcommand) |
|
|||
904 |
|
781 | |||
905 | # Remove some chars from the delimiters list. If we encounter |
|
782 | # A useful post by Alex Martelli on this topic: | |
906 | # unicode chars, discard them. |
|
783 | # Re: inconsistent value from __builtins__ | |
907 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
784 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
908 | delims = delims.translate(string._idmap, |
|
785 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
909 | self.readline_remove_delims) |
|
786 | # Gruppen: comp.lang.python | |
910 | readline.set_completer_delims(delims) |
|
|||
911 | # otherwise we end up with a monster history after a while: |
|
|||
912 | readline.set_history_length(1000) |
|
|||
913 | try: |
|
|||
914 | #print '*** Reading readline history' # dbg |
|
|||
915 | readline.read_history_file(self.histfile) |
|
|||
916 | except IOError: |
|
|||
917 | pass # It doesn't exist yet. |
|
|||
918 |
|
787 | |||
919 | atexit.register(self.atexit_operations) |
|
788 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
920 | del atexit |
|
789 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
|
790 | # > <type 'dict'> | |||
|
791 | # > >>> print type(__builtins__) | |||
|
792 | # > <type 'module'> | |||
|
793 | # > Is this difference in return value intentional? | |||
921 |
|
794 | |||
922 | # Configure auto-indent for all platforms |
|
795 | # Well, it's documented that '__builtins__' can be either a dictionary | |
923 | self.set_autoindent(self.autoindent) |
|
796 | # or a module, and it's been that way for a long time. Whether it's | |
|
797 | # intentional (or sensible), I don't know. In any case, the idea is | |||
|
798 | # that if you need to access the built-in namespace directly, you | |||
|
799 | # should start with "import __builtin__" (note, no 's') which will | |||
|
800 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |||
924 |
|
801 | |||
925 | def init_prompts(self): |
|
802 | # These routines return properly built dicts as needed by the rest of | |
926 | # Initialize cache, set in/out prompts and printing system |
|
803 | # the code, and can also be used by extension writers to generate | |
927 | self.outputcache = CachedOutput(self, |
|
804 | # properly initialized namespaces. | |
928 | self.cache_size, |
|
805 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
929 | self.pprint, |
|
806 | user_global_ns) | |
930 | input_sep = self.separate_in, |
|
|||
931 | output_sep = self.separate_out, |
|
|||
932 | output_sep2 = self.separate_out2, |
|
|||
933 | ps1 = self.prompt_in1, |
|
|||
934 | ps2 = self.prompt_in2, |
|
|||
935 | ps_out = self.prompt_out, |
|
|||
936 | pad_left = self.prompts_pad_left) |
|
|||
937 |
|
807 | |||
938 | # user may have over-ridden the default print hook: |
|
808 | # Assign namespaces | |
939 | try: |
|
809 | # This is the namespace where all normal user variables live | |
940 | self.outputcache.__class__.display = self.hooks.display |
|
810 | self.user_ns = user_ns | |
941 | except AttributeError: |
|
811 | self.user_global_ns = user_global_ns | |
942 | pass |
|
|||
943 |
|
812 | |||
944 | def init_displayhook(self): |
|
813 | # An auxiliary namespace that checks what parts of the user_ns were | |
945 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
814 | # loaded at startup, so we can list later only variables defined in | |
|
815 | # actual interactive use. Since it is always a subset of user_ns, it | |||
|
816 | # doesn't need to be seaparately tracked in the ns_table | |||
|
817 | self.user_config_ns = {} | |||
|
818 | ||||
|
819 | # A namespace to keep track of internal data structures to prevent | |||
|
820 | # them from cluttering user-visible stuff. Will be updated later | |||
|
821 | self.internal_ns = {} | |||
|
822 | ||||
|
823 | # Namespace of system aliases. Each entry in the alias | |||
|
824 | # table must be a 2-tuple of the form (N,name), where N is the number | |||
|
825 | # of positional arguments of the alias. | |||
|
826 | self.alias_table = {} | |||
|
827 | ||||
|
828 | # Now that FakeModule produces a real module, we've run into a nasty | |||
|
829 | # problem: after script execution (via %run), the module where the user | |||
|
830 | # code ran is deleted. Now that this object is a true module (needed | |||
|
831 | # so docetst and other tools work correctly), the Python module | |||
|
832 | # teardown mechanism runs over it, and sets to None every variable | |||
|
833 | # present in that module. Top-level references to objects from the | |||
|
834 | # script survive, because the user_ns is updated with them. However, | |||
|
835 | # calling functions defined in the script that use other things from | |||
|
836 | # the script will fail, because the function's closure had references | |||
|
837 | # to the original objects, which are now all None. So we must protect | |||
|
838 | # these modules from deletion by keeping a cache. | |||
|
839 | # | |||
|
840 | # To avoid keeping stale modules around (we only need the one from the | |||
|
841 | # last run), we use a dict keyed with the full path to the script, so | |||
|
842 | # only the last version of the module is held in the cache. Note, | |||
|
843 | # however, that we must cache the module *namespace contents* (their | |||
|
844 | # __dict__). Because if we try to cache the actual modules, old ones | |||
|
845 | # (uncached) could be destroyed while still holding references (such as | |||
|
846 | # those held by GUI objects that tend to be long-lived)> | |||
|
847 | # | |||
|
848 | # The %reset command will flush this cache. See the cache_main_mod() | |||
|
849 | # and clear_main_mod_cache() methods for details on use. | |||
|
850 | ||||
|
851 | # This is the cache used for 'main' namespaces | |||
|
852 | self._main_ns_cache = {} | |||
|
853 | # And this is the single instance of FakeModule whose __dict__ we keep | |||
|
854 | # copying and clearing for reuse on each %run | |||
|
855 | self._user_main_module = FakeModule() | |||
|
856 | ||||
|
857 | # A table holding all the namespaces IPython deals with, so that | |||
|
858 | # introspection facilities can search easily. | |||
|
859 | self.ns_table = {'user':user_ns, | |||
|
860 | 'user_global':user_global_ns, | |||
|
861 | 'alias':self.alias_table, | |||
|
862 | 'internal':self.internal_ns, | |||
|
863 | 'builtin':__builtin__.__dict__ | |||
|
864 | } | |||
|
865 | ||||
|
866 | # Similarly, track all namespaces where references can be held and that | |||
|
867 | # we can safely clear (so it can NOT include builtin). This one can be | |||
|
868 | # a simple list. | |||
|
869 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |||
|
870 | self.alias_table, self.internal_ns, | |||
|
871 | self._main_ns_cache ] | |||
|
872 | ||||
|
873 | def init_sys_modules(self): | |||
|
874 | # We need to insert into sys.modules something that looks like a | |||
|
875 | # module but which accesses the IPython namespace, for shelve and | |||
|
876 | # pickle to work interactively. Normally they rely on getting | |||
|
877 | # everything out of __main__, but for embedding purposes each IPython | |||
|
878 | # instance has its own private namespace, so we can't go shoving | |||
|
879 | # everything into __main__. | |||
|
880 | ||||
|
881 | # note, however, that we should only do this for non-embedded | |||
|
882 | # ipythons, which really mimic the __main__.__dict__ with their own | |||
|
883 | # namespace. Embedded instances, on the other hand, should not do | |||
|
884 | # this because they need to manage the user local/global namespaces | |||
|
885 | # only, but they live within a 'normal' __main__ (meaning, they | |||
|
886 | # shouldn't overtake the execution environment of the script they're | |||
|
887 | # embedded in). | |||
|
888 | ||||
|
889 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |||
946 |
|
890 | |||
947 | def init_reload_doctest(self): |
|
|||
948 | # Do a proper resetting of doctest, including the necessary displayhook |
|
|||
949 | # monkeypatching |
|
|||
950 | try: |
|
891 | try: | |
951 | doctest_reload() |
|
892 | main_name = self.user_ns['__name__'] | |
952 |
except |
|
893 | except KeyError: | |
953 | warn("doctest module does not exist.") |
|
894 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
|
895 | else: | |||
|
896 | sys.modules[main_name] = FakeModule(self.user_ns) | |||
954 |
|
897 | |||
955 | def init_magics(self): |
|
898 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
956 | # Set user colors (don't do it in the constructor above so that it |
|
899 | """Return a valid local and global user interactive namespaces. | |
957 | # doesn't crash if colors option is invalid) |
|
|||
958 | self.magic_colors(self.colors) |
|
|||
959 |
|
|
900 | ||
960 | def init_pdb(self): |
|
901 | This builds a dict with the minimal information needed to operate as a | |
961 | # Set calling of pdb on exceptions |
|
902 | valid IPython user namespace, which you can pass to the various | |
962 | # self.call_pdb is a property |
|
903 | embedding classes in ipython. The default implementation returns the | |
963 | self.call_pdb = self.pdb |
|
904 | same dict for both the locals and the globals to allow functions to | |
|
905 | refer to variables in the namespace. Customized implementations can | |||
|
906 | return different dicts. The locals dictionary can actually be anything | |||
|
907 | following the basic mapping protocol of a dict, but the globals dict | |||
|
908 | must be a true dict, not even a subclass. It is recommended that any | |||
|
909 | custom object for the locals namespace synchronize with the globals | |||
|
910 | dict somehow. | |||
964 |
|
|
911 | ||
965 | # def init_exec_commands(self): |
|
912 | Raises TypeError if the provided globals namespace is not a true dict. | |
966 | # for cmd in self.config.EXECUTE: |
|
|||
967 | # print "execute:", cmd |
|
|||
968 | # self.api.runlines(cmd) |
|
|||
969 | # |
|
|||
970 | # batchrun = False |
|
|||
971 | # if self.config.has_key('EXECFILE'): |
|
|||
972 | # for batchfile in [path(arg) for arg in self.config.EXECFILE |
|
|||
973 | # if arg.lower().endswith('.ipy')]: |
|
|||
974 | # if not batchfile.isfile(): |
|
|||
975 | # print "No such batch file:", batchfile |
|
|||
976 | # continue |
|
|||
977 | # self.api.runlines(batchfile.text()) |
|
|||
978 | # batchrun = True |
|
|||
979 | # # without -i option, exit after running the batch file |
|
|||
980 | # if batchrun and not self.interactive: |
|
|||
981 | # self.ask_exit() |
|
|||
982 |
|
|
913 | ||
983 | # def load(self, mod): |
|
914 | :Parameters: | |
984 | # """ Load an extension. |
|
915 | user_ns : dict-like, optional | |
985 | # |
|
916 | The current user namespace. The items in this namespace should | |
986 | # Some modules should (or must) be 'load()':ed, rather than just imported. |
|
917 | be included in the output. If None, an appropriate blank | |
987 | # |
|
918 | namespace should be created. | |
988 | # Loading will do: |
|
919 | user_global_ns : dict, optional | |
989 | # |
|
920 | The current user global namespace. The items in this namespace | |
990 | # - run init_ipython(ip) |
|
921 | should be included in the output. If None, an appropriate | |
991 | # - run ipython_firstrun(ip) |
|
922 | blank namespace should be created. | |
992 | # """ |
|
923 | ||
993 | # |
|
924 | :Returns: | |
994 | # if mod in self.extensions: |
|
925 | A tuple pair of dictionary-like object to be used as the local namespace | |
995 | # # just to make sure we don't init it twice |
|
926 | of the interpreter and a dict to be used as the global namespace. | |
996 | # # note that if you 'load' a module that has already been |
|
927 | """ | |
997 | # # imported, init_ipython gets run anyway |
|
928 | ||
998 | # |
|
929 | if user_ns is None: | |
999 | # return self.extensions[mod] |
|
930 | # Set __name__ to __main__ to better match the behavior of the | |
1000 | # __import__(mod) |
|
931 | # normal interpreter. | |
1001 | # m = sys.modules[mod] |
|
932 | user_ns = {'__name__' :'__main__', | |
1002 | # if hasattr(m,'init_ipython'): |
|
933 | '__builtins__' : __builtin__, | |
1003 | # m.init_ipython(self) |
|
934 | } | |
1004 | # |
|
935 | else: | |
1005 | # if hasattr(m,'ipython_firstrun'): |
|
936 | user_ns.setdefault('__name__','__main__') | |
1006 | # already_loaded = self.db.get('firstrun_done', set()) |
|
937 | user_ns.setdefault('__builtins__',__builtin__) | |
1007 | # if mod not in already_loaded: |
|
938 | ||
1008 | # m.ipython_firstrun(self) |
|
939 | if user_global_ns is None: | |
1009 | # already_loaded.add(mod) |
|
940 | user_global_ns = user_ns | |
1010 | # self.db['firstrun_done'] = already_loaded |
|
941 | if type(user_global_ns) is not dict: | |
1011 | # |
|
942 | raise TypeError("user_global_ns must be a true dict; got %r" | |
1012 | # self.extensions[mod] = m |
|
943 | % type(user_global_ns)) | |
1013 | # return m |
|
944 | ||
|
945 | return user_ns, user_global_ns | |||
1014 |
|
946 | |||
1015 | def init_user_ns(self): |
|
947 | def init_user_ns(self): | |
1016 | """Initialize all user-visible namespaces to their minimum defaults. |
|
948 | """Initialize all user-visible namespaces to their minimum defaults. | |
1017 |
|
949 | |||
1018 | Certain history lists are also initialized here, as they effectively |
|
950 | Certain history lists are also initialized here, as they effectively | |
1019 | act as user namespaces. |
|
951 | act as user namespaces. | |
1020 |
|
952 | |||
1021 | Notes |
|
953 | Notes | |
1022 | ----- |
|
954 | ----- | |
1023 | All data structures here are only filled in, they are NOT reset by this |
|
955 | All data structures here are only filled in, they are NOT reset by this | |
1024 | method. If they were not empty before, data will simply be added to |
|
956 | method. If they were not empty before, data will simply be added to | |
1025 | therm. |
|
957 | therm. | |
1026 | """ |
|
958 | """ | |
1027 | # The user namespace MUST have a pointer to the shell itself. |
|
959 | # The user namespace MUST have a pointer to the shell itself. | |
1028 | self.user_ns[self.name] = self |
|
960 | self.user_ns[self.name] = self | |
|
961 | ||||
|
962 | # Store myself as the public api!!! | |||
|
963 | self.user_ns['_ip'] = self | |||
|
964 | ||||
|
965 | # make global variables for user access to the histories | |||
|
966 | self.user_ns['_ih'] = self.input_hist | |||
|
967 | self.user_ns['_oh'] = self.output_hist | |||
|
968 | self.user_ns['_dh'] = self.dir_hist | |||
|
969 | ||||
|
970 | # user aliases to input and output histories | |||
|
971 | self.user_ns['In'] = self.input_hist | |||
|
972 | self.user_ns['Out'] = self.output_hist | |||
|
973 | ||||
|
974 | self.user_ns['_sh'] = shadowns | |||
|
975 | ||||
|
976 | # Put 'help' in the user namespace | |||
|
977 | try: | |||
|
978 | from site import _Helper | |||
|
979 | self.user_ns['help'] = _Helper() | |||
|
980 | except ImportError: | |||
|
981 | warn('help() not available - check site.py') | |||
|
982 | ||||
|
983 | def reset(self): | |||
|
984 | """Clear all internal namespaces. | |||
|
985 | ||||
|
986 | Note that this is much more aggressive than %reset, since it clears | |||
|
987 | fully all namespaces, as well as all input/output lists. | |||
|
988 | """ | |||
|
989 | for ns in self.ns_refs_table: | |||
|
990 | ns.clear() | |||
|
991 | ||||
|
992 | # Clear input and output histories | |||
|
993 | self.input_hist[:] = [] | |||
|
994 | self.input_hist_raw[:] = [] | |||
|
995 | self.output_hist.clear() | |||
|
996 | # Restore the user namespaces to minimal usability | |||
|
997 | self.init_user_ns() | |||
|
998 | ||||
|
999 | def push(self, variables, interactive=True): | |||
|
1000 | """Inject a group of variables into the IPython user namespace. | |||
|
1001 | ||||
|
1002 | Parameters | |||
|
1003 | ---------- | |||
|
1004 | variables : dict, str or list/tuple of str | |||
|
1005 | The variables to inject into the user's namespace. If a dict, | |||
|
1006 | a simple update is done. If a str, the string is assumed to | |||
|
1007 | have variable names separated by spaces. A list/tuple of str | |||
|
1008 | can also be used to give the variable names. If just the variable | |||
|
1009 | names are give (list/tuple/str) then the variable values looked | |||
|
1010 | up in the callers frame. | |||
|
1011 | interactive : bool | |||
|
1012 | If True (default), the variables will be listed with the ``who`` | |||
|
1013 | magic. | |||
|
1014 | """ | |||
|
1015 | vdict = None | |||
|
1016 | ||||
|
1017 | # We need a dict of name/value pairs to do namespace updates. | |||
|
1018 | if isinstance(variables, dict): | |||
|
1019 | vdict = variables | |||
|
1020 | elif isinstance(variables, (basestring, list, tuple)): | |||
|
1021 | if isinstance(variables, basestring): | |||
|
1022 | vlist = variables.split() | |||
|
1023 | else: | |||
|
1024 | vlist = variables | |||
|
1025 | vdict = {} | |||
|
1026 | cf = sys._getframe(1) | |||
|
1027 | for name in vlist: | |||
|
1028 | try: | |||
|
1029 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |||
|
1030 | except: | |||
|
1031 | print ('Could not get variable %s from %s' % | |||
|
1032 | (name,cf.f_code.co_name)) | |||
|
1033 | else: | |||
|
1034 | raise ValueError('variables must be a dict/str/list/tuple') | |||
|
1035 | ||||
|
1036 | # Propagate variables to user namespace | |||
|
1037 | self.user_ns.update(vdict) | |||
|
1038 | ||||
|
1039 | # And configure interactive visibility | |||
|
1040 | config_ns = self.user_config_ns | |||
|
1041 | if interactive: | |||
|
1042 | for name, val in vdict.iteritems(): | |||
|
1043 | config_ns.pop(name, None) | |||
|
1044 | else: | |||
|
1045 | for name,val in vdict.iteritems(): | |||
|
1046 | config_ns[name] = val | |||
1029 |
|
1047 | |||
1030 | # Store myself as the public api!!! |
|
1048 | #------------------------------------------------------------------------- | |
1031 | self.user_ns['_ip'] = self |
|
1049 | # Things related to history management | |
|
1050 | #------------------------------------------------------------------------- | |||
1032 |
|
1051 | |||
1033 | # make global variables for user access to the histories |
|
1052 | def init_history(self): | |
1034 | self.user_ns['_ih'] = self.input_hist |
|
1053 | # List of input with multi-line handling. | |
1035 | self.user_ns['_oh'] = self.output_hist |
|
1054 | self.input_hist = InputList() | |
1036 | self.user_ns['_dh'] = self.dir_hist |
|
1055 | # This one will hold the 'raw' input history, without any | |
|
1056 | # pre-processing. This will allow users to retrieve the input just as | |||
|
1057 | # it was exactly typed in by the user, with %hist -r. | |||
|
1058 | self.input_hist_raw = InputList() | |||
1037 |
|
1059 | |||
1038 | # user aliases to input and output histories |
|
1060 | # list of visited directories | |
1039 | self.user_ns['In'] = self.input_hist |
|
1061 | try: | |
1040 | self.user_ns['Out'] = self.output_hist |
|
1062 | self.dir_hist = [os.getcwd()] | |
|
1063 | except OSError: | |||
|
1064 | self.dir_hist = [] | |||
1041 |
|
1065 | |||
1042 | self.user_ns['_sh'] = shadowns |
|
1066 | # dict of output history | |
|
1067 | self.output_hist = {} | |||
1043 |
|
1068 | |||
1044 | # Put 'help' in the user namespace |
|
1069 | # Now the history file | |
1045 | try: |
|
1070 | try: | |
1046 | from site import _Helper |
|
1071 | histfname = 'history-%s' % self.profile | |
1047 | self.user_ns['help'] = _Helper() |
|
1072 | except AttributeError: | |
1048 | except ImportError: |
|
1073 | histfname = 'history' | |
1049 | warn('help() not available - check site.py') |
|
1074 | self.histfile = os.path.join(self.config.IPYTHONDIR, histfname) | |
1050 |
|
1075 | |||
1051 | def save_sys_module_state(self): |
|
1076 | # Fill the history zero entry, user counter starts at 1 | |
1052 | """Save the state of hooks in the sys module. |
|
1077 | self.input_hist.append('\n') | |
|
1078 | self.input_hist_raw.append('\n') | |||
1053 |
|
1079 | |||
1054 | This has to be called after self.user_ns is created. |
|
1080 | def init_shadow_hist(self): | |
1055 | """ |
|
|||
1056 | self._orig_sys_module_state = {} |
|
|||
1057 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
|||
1058 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
|||
1059 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
|||
1060 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
|||
1061 | try: |
|
1081 | try: | |
1062 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
1082 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") | |
1063 |
except |
|
1083 | except exceptions.UnicodeDecodeError: | |
1064 | pass |
|
1084 | print "Your ipythondir can't be decoded to unicode!" | |
|
1085 | print "Please set HOME environment variable to something that" | |||
|
1086 | print r"only has ASCII characters, e.g. c:\home" | |||
|
1087 | print "Now it is", self.config.IPYTHONDIR | |||
|
1088 | sys.exit() | |||
|
1089 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |||
|
1090 | ||||
|
1091 | def savehist(self): | |||
|
1092 | """Save input history to a file (via readline library).""" | |||
|
1093 | ||||
|
1094 | if not self.has_readline: | |||
|
1095 | return | |||
1065 |
|
1096 | |||
1066 | def restore_sys_module_state(self): |
|
|||
1067 | """Restore the state of the sys module.""" |
|
|||
1068 | try: |
|
1097 | try: | |
1069 | for k, v in self._orig_sys_module_state.items(): |
|
1098 | self.readline.write_history_file(self.histfile) | |
1070 | setattr(sys, k, v) |
|
1099 | except: | |
1071 | except AttributeError: |
|
1100 | print 'Unable to save IPython command history to file: ' + \ | |
1072 | pass |
|
1101 | `self.histfile` | |
|
1102 | ||||
|
1103 | def reloadhist(self): | |||
|
1104 | """Reload the input history from disk file.""" | |||
|
1105 | ||||
|
1106 | if self.has_readline: | |||
1073 | try: |
|
1107 | try: | |
1074 | delattr(sys, 'ipcompleter') |
|
1108 | self.readline.clear_history() | |
|
1109 | self.readline.read_history_file(self.shell.histfile) | |||
1075 | except AttributeError: |
|
1110 | except AttributeError: | |
1076 | pass |
|
1111 | pass | |
1077 | # Reset what what done in self.init_sys_modules |
|
|||
1078 | try: |
|
|||
1079 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
|||
1080 | except (AttributeError, KeyError): |
|
|||
1081 | pass |
|
|||
1082 |
|
1112 | |||
1083 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
1113 | def history_saving_wrapper(self, func): | |
1084 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
1114 | """ Wrap func for readline history saving | |
1085 |
|
1115 | |||
1086 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
1116 | Convert func into callable that saves & restores | |
1087 | adding your function to one of these hooks, you can modify IPython's |
|
1117 | history around the call """ | |
1088 | behavior to call at runtime your own routines.""" |
|
|||
1089 |
|
1118 | |||
1090 | # At some point in the future, this should validate the hook before it |
|
1119 | if not self.has_readline: | |
1091 | # accepts it. Probably at least check that the hook takes the number |
|
1120 | return func | |
1092 | # of args it's supposed to. |
|
|||
1093 |
|
1121 | |||
1094 | f = new.instancemethod(hook,self,self.__class__) |
|
1122 | def wrapper(): | |
|
1123 | self.savehist() | |||
|
1124 | try: | |||
|
1125 | func() | |||
|
1126 | finally: | |||
|
1127 | readline.read_history_file(self.histfile) | |||
|
1128 | return wrapper | |||
1095 |
|
1129 | |||
1096 | # check if the hook is for strdispatcher first |
|
1130 | #------------------------------------------------------------------------- | |
1097 | if str_key is not None: |
|
1131 | # Things related to exception handling and tracebacks (not debugging) | |
1098 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1132 | #------------------------------------------------------------------------- | |
1099 | sdp.add_s(str_key, f, priority ) |
|
|||
1100 | self.strdispatchers[name] = sdp |
|
|||
1101 | return |
|
|||
1102 | if re_key is not None: |
|
|||
1103 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
|||
1104 | sdp.add_re(re.compile(re_key), f, priority ) |
|
|||
1105 | self.strdispatchers[name] = sdp |
|
|||
1106 | return |
|
|||
1107 |
|
1133 | |||
1108 | dp = getattr(self.hooks, name, None) |
|
1134 | def init_traceback_handlers(self, custom_exceptions): | |
1109 | if name not in IPython.core.hooks.__all__: |
|
1135 | # Syntax error handler. | |
1110 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
1136 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
1111 | if not dp: |
|
|||
1112 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
|||
1113 |
|
1137 | |||
1114 | try: |
|
1138 | # The interactive one is initialized with an offset, meaning we always | |
1115 | dp.add(f,priority) |
|
1139 | # want to remove the topmost item in the traceback, which is our own | |
1116 | except AttributeError: |
|
1140 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1117 | # it was not commandchain, plain old func - replace |
|
1141 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1118 | dp = f |
|
1142 | color_scheme='NoColor', | |
|
1143 | tb_offset = 1) | |||
1119 |
|
1144 | |||
1120 | setattr(self.hooks,name, dp) |
|
1145 | # IPython itself shouldn't crash. This will produce a detailed | |
|
1146 | # post-mortem if it does. But we only install the crash handler for | |||
|
1147 | # non-threaded shells, the threaded ones use a normal verbose reporter | |||
|
1148 | # and lose the crash handler. This is because exceptions in the main | |||
|
1149 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |||
|
1150 | # and there's no point in printing crash dumps for every user exception. | |||
|
1151 | if self.isthreaded: | |||
|
1152 | ipCrashHandler = ultratb.FormattedTB() | |||
|
1153 | else: | |||
|
1154 | from IPython.core import crashhandler | |||
|
1155 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) | |||
|
1156 | self.set_crash_handler(ipCrashHandler) | |||
|
1157 | ||||
|
1158 | # and add any custom exception handlers the user may have specified | |||
|
1159 | self.set_custom_exc(*custom_exceptions) | |||
1121 |
|
1160 | |||
1122 | def set_crash_handler(self, crashHandler): |
|
1161 | def set_crash_handler(self, crashHandler): | |
1123 | """Set the IPython crash handler. |
|
1162 | """Set the IPython crash handler. | |
1124 |
|
1163 | |||
1125 | This must be a callable with a signature suitable for use as |
|
1164 | This must be a callable with a signature suitable for use as | |
1126 | sys.excepthook.""" |
|
1165 | sys.excepthook.""" | |
1127 |
|
1166 | |||
1128 | # Install the given crash handler as the Python exception hook |
|
1167 | # Install the given crash handler as the Python exception hook | |
1129 | sys.excepthook = crashHandler |
|
1168 | sys.excepthook = crashHandler | |
1130 |
|
1169 | |||
1131 | # The instance will store a pointer to this, so that runtime code |
|
1170 | # The instance will store a pointer to this, so that runtime code | |
1132 | # (such as magics) can access it. This is because during the |
|
1171 | # (such as magics) can access it. This is because during the | |
1133 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1172 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
1134 | # frameworks). |
|
1173 | # frameworks). | |
1135 | self.sys_excepthook = sys.excepthook |
|
1174 | self.sys_excepthook = sys.excepthook | |
1136 |
|
1175 | |||
1137 | def set_custom_exc(self,exc_tuple,handler): |
|
1176 | def set_custom_exc(self,exc_tuple,handler): | |
1138 | """set_custom_exc(exc_tuple,handler) |
|
1177 | """set_custom_exc(exc_tuple,handler) | |
1139 |
|
1178 | |||
1140 | Set a custom exception handler, which will be called if any of the |
|
1179 | Set a custom exception handler, which will be called if any of the | |
1141 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1180 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1142 | runcode() method. |
|
1181 | runcode() method. | |
1143 |
|
1182 | |||
1144 | Inputs: |
|
1183 | Inputs: | |
1145 |
|
1184 | |||
1146 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1185 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1147 | handler for. It is very important that you use a tuple, and NOT A |
|
1186 | handler for. It is very important that you use a tuple, and NOT A | |
1148 | LIST here, because of the way Python's except statement works. If |
|
1187 | LIST here, because of the way Python's except statement works. If | |
1149 | you only want to trap a single exception, use a singleton tuple: |
|
1188 | you only want to trap a single exception, use a singleton tuple: | |
1150 |
|
1189 | |||
1151 | exc_tuple == (MyCustomException,) |
|
1190 | exc_tuple == (MyCustomException,) | |
1152 |
|
1191 | |||
1153 | - handler: this must be defined as a function with the following |
|
1192 | - handler: this must be defined as a function with the following | |
1154 | basic interface: def my_handler(self,etype,value,tb). |
|
1193 | basic interface: def my_handler(self,etype,value,tb). | |
1155 |
|
1194 | |||
1156 | This will be made into an instance method (via new.instancemethod) |
|
1195 | This will be made into an instance method (via new.instancemethod) | |
1157 | of IPython itself, and it will be called if any of the exceptions |
|
1196 | of IPython itself, and it will be called if any of the exceptions | |
1158 | listed in the exc_tuple are caught. If the handler is None, an |
|
1197 | listed in the exc_tuple are caught. If the handler is None, an | |
1159 | internal basic one is used, which just prints basic info. |
|
1198 | internal basic one is used, which just prints basic info. | |
1160 |
|
1199 | |||
1161 | WARNING: by putting in your own exception handler into IPython's main |
|
1200 | WARNING: by putting in your own exception handler into IPython's main | |
1162 | execution loop, you run a very good chance of nasty crashes. This |
|
1201 | execution loop, you run a very good chance of nasty crashes. This | |
1163 | facility should only be used if you really know what you are doing.""" |
|
1202 | facility should only be used if you really know what you are doing.""" | |
1164 |
|
1203 | |||
1165 | assert type(exc_tuple)==type(()) , \ |
|
1204 | assert type(exc_tuple)==type(()) , \ | |
1166 | "The custom exceptions must be given AS A TUPLE." |
|
1205 | "The custom exceptions must be given AS A TUPLE." | |
1167 |
|
1206 | |||
1168 | def dummy_handler(self,etype,value,tb): |
|
1207 | def dummy_handler(self,etype,value,tb): | |
1169 | print '*** Simple custom exception handler ***' |
|
1208 | print '*** Simple custom exception handler ***' | |
1170 | print 'Exception type :',etype |
|
1209 | print 'Exception type :',etype | |
1171 | print 'Exception value:',value |
|
1210 | print 'Exception value:',value | |
1172 | print 'Traceback :',tb |
|
1211 | print 'Traceback :',tb | |
1173 | print 'Source code :','\n'.join(self.buffer) |
|
1212 | print 'Source code :','\n'.join(self.buffer) | |
1174 |
|
1213 | |||
1175 | if handler is None: handler = dummy_handler |
|
1214 | if handler is None: handler = dummy_handler | |
1176 |
|
1215 | |||
1177 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1216 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1178 | self.custom_exceptions = exc_tuple |
|
1217 | self.custom_exceptions = exc_tuple | |
1179 |
|
1218 | |||
1180 | def set_custom_completer(self,completer,pos=0): |
|
1219 | def excepthook(self, etype, value, tb): | |
1181 | """set_custom_completer(completer,pos=0) |
|
1220 | """One more defense for GUI apps that call sys.excepthook. | |
1182 |
|
||||
1183 | Adds a new custom completer function. |
|
|||
1184 |
|
||||
1185 | The position argument (defaults to 0) is the index in the completers |
|
|||
1186 | list where you want the completer to be inserted.""" |
|
|||
1187 |
|
||||
1188 | newcomp = new.instancemethod(completer,self.Completer, |
|
|||
1189 | self.Completer.__class__) |
|
|||
1190 | self.Completer.matchers.insert(pos,newcomp) |
|
|||
1191 |
|
||||
1192 | def set_completer(self): |
|
|||
1193 | """reset readline's completer to be our own.""" |
|
|||
1194 | self.readline.set_completer(self.Completer.complete) |
|
|||
1195 |
|
||||
1196 | def _get_call_pdb(self): |
|
|||
1197 | return self._call_pdb |
|
|||
1198 |
|
||||
1199 | def _set_call_pdb(self,val): |
|
|||
1200 |
|
||||
1201 | if val not in (0,1,False,True): |
|
|||
1202 | raise ValueError,'new call_pdb value must be boolean' |
|
|||
1203 |
|
||||
1204 | # store value in instance |
|
|||
1205 | self._call_pdb = val |
|
|||
1206 |
|
||||
1207 | # notify the actual exception handlers |
|
|||
1208 | self.InteractiveTB.call_pdb = val |
|
|||
1209 | if self.isthreaded: |
|
|||
1210 | try: |
|
|||
1211 | self.sys_excepthook.call_pdb = val |
|
|||
1212 | except: |
|
|||
1213 | warn('Failed to activate pdb for threaded exception handler') |
|
|||
1214 |
|
||||
1215 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
|||
1216 | 'Control auto-activation of pdb at exceptions') |
|
|||
1217 |
|
||||
1218 | def magic(self,arg_s): |
|
|||
1219 | """Call a magic function by name. |
|
|||
1220 |
|
||||
1221 | Input: a string containing the name of the magic function to call and any |
|
|||
1222 | additional arguments to be passed to the magic. |
|
|||
1223 |
|
||||
1224 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
|||
1225 | prompt: |
|
|||
1226 |
|
||||
1227 | In[1]: %name -opt foo bar |
|
|||
1228 |
|
||||
1229 | To call a magic without arguments, simply use magic('name'). |
|
|||
1230 |
|
||||
1231 | This provides a proper Python function to call IPython's magics in any |
|
|||
1232 | valid Python code you can type at the interpreter, including loops and |
|
|||
1233 | compound statements. |
|
|||
1234 | """ |
|
|||
1235 |
|
||||
1236 | args = arg_s.split(' ',1) |
|
|||
1237 | magic_name = args[0] |
|
|||
1238 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
|||
1239 |
|
||||
1240 | try: |
|
|||
1241 | magic_args = args[1] |
|
|||
1242 | except IndexError: |
|
|||
1243 | magic_args = '' |
|
|||
1244 | fn = getattr(self,'magic_'+magic_name,None) |
|
|||
1245 | if fn is None: |
|
|||
1246 | error("Magic function `%s` not found." % magic_name) |
|
|||
1247 | else: |
|
|||
1248 | magic_args = self.var_expand(magic_args,1) |
|
|||
1249 | with nested(self.builtin_trap, self.display_trap): |
|
|||
1250 | return fn(magic_args) |
|
|||
1251 | # return result |
|
|||
1252 |
|
|
1221 | ||
1253 | def define_magic(self, magicname, func): |
|
1222 | GUI frameworks like wxPython trap exceptions and call | |
1254 | """Expose own function as magic function for ipython |
|
1223 | sys.excepthook themselves. I guess this is a feature that | |
|
1224 | enables them to keep running after exceptions that would | |||
|
1225 | otherwise kill their mainloop. This is a bother for IPython | |||
|
1226 | which excepts to catch all of the program exceptions with a try: | |||
|
1227 | except: statement. | |||
1255 |
|
1228 | |||
1256 | def foo_impl(self,parameter_s=''): |
|
1229 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1257 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1230 | any app directly invokes sys.excepthook, it will look to the user like | |
1258 | print 'Magic function. Passed parameter is between < >:' |
|
1231 | IPython crashed. In order to work around this, we can disable the | |
1259 | print '<%s>' % parameter_s |
|
1232 | CrashHandler and replace it with this excepthook instead, which prints a | |
1260 | print 'The self object is:',self |
|
1233 | regular traceback using our InteractiveTB. In this fashion, apps which | |
|
1234 | call sys.excepthook will generate a regular-looking exception from | |||
|
1235 | IPython, and the CrashHandler will only be triggered by real IPython | |||
|
1236 | crashes. | |||
1261 |
|
1237 | |||
1262 | self.define_magic('foo',foo_impl) |
|
1238 | This hook should be used sparingly, only in places which are not likely | |
|
1239 | to be true IPython errors. | |||
1263 |
|
|
1240 | """ | |
|
1241 | self.showtraceback((etype,value,tb),tb_offset=0) | |||
1264 |
|
1242 | |||
1265 | import new |
|
1243 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1266 | im = new.instancemethod(func,self, self.__class__) |
|
1244 | """Display the exception that just occurred. | |
1267 | old = getattr(self, "magic_" + magicname, None) |
|
|||
1268 | setattr(self, "magic_" + magicname, im) |
|
|||
1269 | return old |
|
|||
1270 |
|
||||
1271 | def define_macro(self, name, themacro): |
|
|||
1272 | """Define a new macro |
|
|||
1273 |
|
1245 | |||
1274 | Parameters |
|
1246 | If nothing is known about the exception, this is the method which | |
1275 | ---------- |
|
1247 | should be used throughout the code for presenting user tracebacks, | |
1276 | name : str |
|
1248 | rather than directly invoking the InteractiveTB object. | |
1277 | The name of the macro. |
|
|||
1278 | themacro : str or Macro |
|
|||
1279 | The action to do upon invoking the macro. If a string, a new |
|
|||
1280 | Macro object is created by passing the string to it. |
|
|||
1281 | """ |
|
|||
1282 |
|
1249 | |||
1283 | from IPython.core import macro |
|
1250 | A specific showsyntaxerror() also exists, but this method can take | |
|
1251 | care of calling it if needed, so unless you are explicitly catching a | |||
|
1252 | SyntaxError exception, don't try to analyze the stack manually and | |||
|
1253 | simply call this method.""" | |||
1284 |
|
1254 | |||
1285 | if isinstance(themacro, basestring): |
|
|||
1286 | themacro = macro.Macro(themacro) |
|
|||
1287 | if not isinstance(themacro, macro.Macro): |
|
|||
1288 | raise ValueError('A macro must be a string or a Macro instance.') |
|
|||
1289 | self.user_ns[name] = themacro |
|
|||
1290 |
|
1255 | |||
1291 | def define_alias(self, name, cmd): |
|
1256 | # Though this won't be called by syntax errors in the input line, | |
1292 | """ Define a new alias.""" |
|
1257 | # there may be SyntaxError cases whith imported code. | |
1293 |
|
1258 | |||
1294 | if callable(cmd): |
|
1259 | try: | |
1295 | self.alias_table[name] = cmd |
|
1260 | if exc_tuple is None: | |
1296 | from IPython.core import shadowns |
|
1261 | etype, value, tb = sys.exc_info() | |
1297 | setattr(shadowns, name, cmd) |
|
1262 | else: | |
1298 | return |
|
1263 | etype, value, tb = exc_tuple | |
1299 |
|
1264 | |||
1300 | if isinstance(cmd, basestring): |
|
1265 | if etype is SyntaxError: | |
1301 | nargs = cmd.count('%s') |
|
1266 | self.showsyntaxerror(filename) | |
1302 | if nargs>0 and cmd.find('%l')>=0: |
|
1267 | elif etype is UsageError: | |
1303 | raise Exception('The %s and %l specifiers are mutually ' |
|
1268 | print "UsageError:", value | |
1304 | 'exclusive in alias definitions.') |
|
1269 | else: | |
|
1270 | # WARNING: these variables are somewhat deprecated and not | |||
|
1271 | # necessarily safe to use in a threaded environment, but tools | |||
|
1272 | # like pdb depend on their existence, so let's set them. If we | |||
|
1273 | # find problems in the field, we'll need to revisit their use. | |||
|
1274 | sys.last_type = etype | |||
|
1275 | sys.last_value = value | |||
|
1276 | sys.last_traceback = tb | |||
1305 |
|
1277 | |||
1306 | self.alias_table[name] = (nargs,cmd) |
|
1278 | if etype in self.custom_exceptions: | |
1307 | return |
|
1279 | self.CustomTB(etype,value,tb) | |
|
1280 | else: | |||
|
1281 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |||
|
1282 | if self.InteractiveTB.call_pdb and self.has_readline: | |||
|
1283 | # pdb mucks up readline, fix it back | |||
|
1284 | self.set_completer() | |||
|
1285 | except KeyboardInterrupt: | |||
|
1286 | self.write("\nKeyboardInterrupt\n") | |||
1308 |
|
1287 | |||
1309 | self.alias_table[name] = cmd |
|
1288 | def showsyntaxerror(self, filename=None): | |
|
1289 | """Display the syntax error that just occurred. | |||
1310 |
|
|
1290 | ||
1311 | def ipalias(self,arg_s): |
|
1291 | This doesn't display a stack trace because there isn't one. | |
1312 | """Call an alias by name. |
|
|||
1313 |
|
1292 | |||
1314 | Input: a string containing the name of the alias to call and any |
|
1293 | If a filename is given, it is stuffed in the exception instead | |
1315 | additional arguments to be passed to the magic. |
|
1294 | of what was there before (because Python's parser always uses | |
|
1295 | "<string>" when reading from a string). | |||
|
1296 | """ | |||
|
1297 | etype, value, last_traceback = sys.exc_info() | |||
1316 |
|
1298 | |||
1317 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1299 | # See note about these variables in showtraceback() below | |
1318 | prompt: |
|
1300 | sys.last_type = etype | |
|
1301 | sys.last_value = value | |||
|
1302 | sys.last_traceback = last_traceback | |||
1319 |
|
1303 | |||
1320 | In[1]: name -opt foo bar |
|
1304 | if filename and etype is SyntaxError: | |
|
1305 | # Work hard to stuff the correct filename in the exception | |||
|
1306 | try: | |||
|
1307 | msg, (dummy_filename, lineno, offset, line) = value | |||
|
1308 | except: | |||
|
1309 | # Not the format we expect; leave it alone | |||
|
1310 | pass | |||
|
1311 | else: | |||
|
1312 | # Stuff in the right filename | |||
|
1313 | try: | |||
|
1314 | # Assume SyntaxError is a class exception | |||
|
1315 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |||
|
1316 | except: | |||
|
1317 | # If that failed, assume SyntaxError is a string | |||
|
1318 | value = msg, (filename, lineno, offset, line) | |||
|
1319 | self.SyntaxTB(etype,value,[]) | |||
1321 |
|
1320 | |||
1322 | To call an alias without arguments, simply use ipalias('name'). |
|
1321 | def edit_syntax_error(self): | |
|
1322 | """The bottom half of the syntax error handler called in the main loop. | |||
1323 |
|
1323 | |||
1324 | This provides a proper Python function to call IPython's aliases in any |
|
1324 | Loop until syntax error is fixed or user cancels. | |
1325 | valid Python code you can type at the interpreter, including loops and |
|
1325 | """ | |
1326 | compound statements. It is added by IPython to the Python builtin |
|
|||
1327 | namespace upon initialization.""" |
|
|||
1328 |
|
1326 | |||
1329 | args = arg_s.split(' ',1) |
|
1327 | while self.SyntaxTB.last_syntax_error: | |
1330 | alias_name = args[0] |
|
1328 | # copy and clear last_syntax_error | |
|
1329 | err = self.SyntaxTB.clear_err_state() | |||
|
1330 | if not self._should_recompile(err): | |||
|
1331 | return | |||
1331 | try: |
|
1332 | try: | |
1332 | alias_args = args[1] |
|
1333 | # may set last_syntax_error again if a SyntaxError is raised | |
1333 | except IndexError: |
|
1334 | self.safe_execfile(err.filename,self.user_ns) | |
1334 | alias_args = '' |
|
1335 | except: | |
1335 | if alias_name in self.alias_table: |
|
1336 | self.showtraceback() | |
1336 | self.call_alias(alias_name,alias_args) |
|
|||
1337 | else: |
|
1337 | else: | |
1338 | error("Alias `%s` not found." % alias_name) |
|
1338 | try: | |
1339 |
|
1339 | f = file(err.filename) | ||
1340 | def system(self, cmd): |
|
1340 | try: | |
1341 | """Make a system call, using IPython.""" |
|
1341 | # This should be inside a display_trap block and I | |
1342 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1342 | # think it is. | |
|
1343 | sys.displayhook(f.read()) | |||
|
1344 | finally: | |||
|
1345 | f.close() | |||
|
1346 | except: | |||
|
1347 | self.showtraceback() | |||
1343 |
|
1348 | |||
1344 |
def |
|
1349 | def _should_recompile(self,e): | |
1345 | """Execute a normal python statement in user namespace.""" |
|
1350 | """Utility routine for edit_syntax_error""" | |
1346 | with nested(self.builtin_trap, self.display_trap): |
|
|||
1347 | exec cmd in self.user_global_ns, self.user_ns |
|
|||
1348 |
|
1351 | |||
1349 | def ev(self, expr): |
|
1352 | if e.filename in ('<ipython console>','<input>','<string>', | |
1350 | """Evaluate python expression expr in user namespace. |
|
1353 | '<console>','<BackgroundJob compilation>', | |
|
1354 | None): | |||
1351 |
|
1355 | |||
1352 | Returns the result of evaluation |
|
1356 | return False | |
1353 |
|
|
1357 | try: | |
1354 | with nested(self.builtin_trap, self.display_trap): |
|
1358 | if (self.autoedit_syntax and | |
1355 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1359 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
|
1360 | '[Y/n] ','y')): | |||
|
1361 | return False | |||
|
1362 | except EOFError: | |||
|
1363 | return False | |||
1356 |
|
1364 | |||
1357 | def getoutput(self, cmd): |
|
1365 | def int0(x): | |
1358 | return getoutput(self.var_expand(cmd,depth=2), |
|
1366 | try: | |
1359 | header=self.system_header, |
|
1367 | return int(x) | |
1360 | verbose=self.system_verbose) |
|
1368 | except TypeError: | |
|
1369 | return 0 | |||
|
1370 | # always pass integer line and offset values to editor hook | |||
|
1371 | try: | |||
|
1372 | self.hooks.fix_error_editor(e.filename, | |||
|
1373 | int0(e.lineno),int0(e.offset),e.msg) | |||
|
1374 | except TryNext: | |||
|
1375 | warn('Could not open editor') | |||
|
1376 | return False | |||
|
1377 | return True | |||
1361 |
|
1378 | |||
1362 | def getoutputerror(self, cmd): |
|
1379 | #------------------------------------------------------------------------- | |
1363 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
1380 | # Things related to tab completion | |
1364 | header=self.system_header, |
|
1381 | #------------------------------------------------------------------------- | |
1365 | verbose=self.system_verbose) |
|
|||
1366 |
|
1382 | |||
1367 | def complete(self, text): |
|
1383 | def complete(self, text): | |
1368 | """Return a sorted list of all possible completions on text. |
|
1384 | """Return a sorted list of all possible completions on text. | |
1369 |
|
1385 | |||
1370 | Inputs: |
|
1386 | Inputs: | |
1371 |
|
1387 | |||
1372 | - text: a string of text to be completed on. |
|
1388 | - text: a string of text to be completed on. | |
1373 |
|
1389 | |||
1374 | This is a wrapper around the completion mechanism, similar to what |
|
1390 | This is a wrapper around the completion mechanism, similar to what | |
1375 | readline does at the command line when the TAB key is hit. By |
|
1391 | readline does at the command line when the TAB key is hit. By | |
1376 | exposing it as a method, it can be used by other non-readline |
|
1392 | exposing it as a method, it can be used by other non-readline | |
1377 | environments (such as GUIs) for text completion. |
|
1393 | environments (such as GUIs) for text completion. | |
1378 |
|
1394 | |||
1379 | Simple usage example: |
|
1395 | Simple usage example: | |
1380 |
|
1396 | |||
1381 | In [7]: x = 'hello' |
|
1397 | In [7]: x = 'hello' | |
1382 |
|
1398 | |||
1383 | In [8]: x |
|
1399 | In [8]: x | |
1384 | Out[8]: 'hello' |
|
1400 | Out[8]: 'hello' | |
1385 |
|
1401 | |||
1386 | In [9]: print x |
|
1402 | In [9]: print x | |
1387 | hello |
|
1403 | hello | |
1388 |
|
1404 | |||
1389 | In [10]: _ip.complete('x.l') |
|
1405 | In [10]: _ip.complete('x.l') | |
1390 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1406 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1391 | """ |
|
1407 | """ | |
1392 |
|
1408 | |||
1393 | # Inject names into __builtin__ so we can complete on the added names. |
|
1409 | # Inject names into __builtin__ so we can complete on the added names. | |
1394 | with self.builtin_trap: |
|
1410 | with self.builtin_trap: | |
1395 | complete = self.Completer.complete |
|
1411 | complete = self.Completer.complete | |
1396 | state = 0 |
|
1412 | state = 0 | |
1397 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1413 | # use a dict so we get unique keys, since ipyhton's multiple | |
1398 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1414 | # completers can return duplicates. When we make 2.4 a requirement, | |
1399 | # start using sets instead, which are faster. |
|
1415 | # start using sets instead, which are faster. | |
1400 | comps = {} |
|
1416 | comps = {} | |
1401 | while True: |
|
1417 | while True: | |
1402 | newcomp = complete(text,state,line_buffer=text) |
|
1418 | newcomp = complete(text,state,line_buffer=text) | |
1403 | if newcomp is None: |
|
1419 | if newcomp is None: | |
1404 | break |
|
1420 | break | |
1405 | comps[newcomp] = 1 |
|
1421 | comps[newcomp] = 1 | |
1406 | state += 1 |
|
1422 | state += 1 | |
1407 | outcomps = comps.keys() |
|
1423 | outcomps = comps.keys() | |
1408 | outcomps.sort() |
|
1424 | outcomps.sort() | |
1409 | #print "T:",text,"OC:",outcomps # dbg |
|
1425 | #print "T:",text,"OC:",outcomps # dbg | |
1410 | #print "vars:",self.user_ns.keys() |
|
1426 | #print "vars:",self.user_ns.keys() | |
1411 | return outcomps |
|
1427 | return outcomps | |
1412 |
|
1428 | |||
1413 |
def set_completer |
|
1429 | def set_custom_completer(self,completer,pos=0): | |
1414 | if frame: |
|
1430 | """set_custom_completer(completer,pos=0) | |
1415 | self.Completer.namespace = frame.f_locals |
|
1431 | ||
1416 | self.Completer.global_namespace = frame.f_globals |
|
1432 | Adds a new custom completer function. | |
|
1433 | ||||
|
1434 | The position argument (defaults to 0) is the index in the completers | |||
|
1435 | list where you want the completer to be inserted.""" | |||
|
1436 | ||||
|
1437 | newcomp = new.instancemethod(completer,self.Completer, | |||
|
1438 | self.Completer.__class__) | |||
|
1439 | self.Completer.matchers.insert(pos,newcomp) | |||
|
1440 | ||||
|
1441 | def set_completer(self): | |||
|
1442 | """reset readline's completer to be our own.""" | |||
|
1443 | self.readline.set_completer(self.Completer.complete) | |||
|
1444 | ||||
|
1445 | #------------------------------------------------------------------------- | |||
|
1446 | # Things related to readline | |||
|
1447 | #------------------------------------------------------------------------- | |||
|
1448 | ||||
|
1449 | def init_readline(self): | |||
|
1450 | """Command history completion/saving/reloading.""" | |||
|
1451 | ||||
|
1452 | self.rl_next_input = None | |||
|
1453 | self.rl_do_indent = False | |||
|
1454 | ||||
|
1455 | if not self.readline_use: | |||
|
1456 | return | |||
|
1457 | ||||
|
1458 | import IPython.utils.rlineimpl as readline | |||
|
1459 | ||||
|
1460 | if not readline.have_readline: | |||
|
1461 | self.has_readline = 0 | |||
|
1462 | self.readline = None | |||
|
1463 | # no point in bugging windows users with this every time: | |||
|
1464 | warn('Readline services not available on this platform.') | |||
|
1465 | else: | |||
|
1466 | sys.modules['readline'] = readline | |||
|
1467 | import atexit | |||
|
1468 | from IPython.core.completer import IPCompleter | |||
|
1469 | self.Completer = IPCompleter(self, | |||
|
1470 | self.user_ns, | |||
|
1471 | self.user_global_ns, | |||
|
1472 | self.readline_omit__names, | |||
|
1473 | self.alias_table) | |||
|
1474 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |||
|
1475 | self.strdispatchers['complete_command'] = sdisp | |||
|
1476 | self.Completer.custom_completers = sdisp | |||
|
1477 | # Platform-specific configuration | |||
|
1478 | if os.name == 'nt': | |||
|
1479 | self.readline_startup_hook = readline.set_pre_input_hook | |||
1417 | else: |
|
1480 | else: | |
1418 | self.Completer.namespace = self.user_ns |
|
1481 | self.readline_startup_hook = readline.set_startup_hook | |
1419 | self.Completer.global_namespace = self.user_global_ns |
|
|||
1420 |
|
1482 | |||
1421 | def init_auto_alias(self): |
|
1483 | # Load user's initrc file (readline config) | |
1422 | """Define some aliases automatically. |
|
1484 | # Or if libedit is used, load editrc. | |
|
1485 | inputrc_name = os.environ.get('INPUTRC') | |||
|
1486 | if inputrc_name is None: | |||
|
1487 | home_dir = get_home_dir() | |||
|
1488 | if home_dir is not None: | |||
|
1489 | inputrc_name = '.inputrc' | |||
|
1490 | if readline.uses_libedit: | |||
|
1491 | inputrc_name = '.editrc' | |||
|
1492 | inputrc_name = os.path.join(home_dir, inputrc_name) | |||
|
1493 | if os.path.isfile(inputrc_name): | |||
|
1494 | try: | |||
|
1495 | readline.read_init_file(inputrc_name) | |||
|
1496 | except: | |||
|
1497 | warn('Problems reading readline initialization file <%s>' | |||
|
1498 | % inputrc_name) | |||
1423 |
|
1499 | |||
1424 | These are ALL parameter-less aliases""" |
|
1500 | self.has_readline = 1 | |
|
1501 | self.readline = readline | |||
|
1502 | # save this in sys so embedded copies can restore it properly | |||
|
1503 | sys.ipcompleter = self.Completer.complete | |||
|
1504 | self.set_completer() | |||
1425 |
|
1505 | |||
1426 | for alias,cmd in self.auto_alias: |
|
1506 | # Configure readline according to user's prefs | |
1427 | self.define_alias(alias,cmd) |
|
1507 | # This is only done if GNU readline is being used. If libedit | |
|
1508 | # is being used (as on Leopard) the readline config is | |||
|
1509 | # not run as the syntax for libedit is different. | |||
|
1510 | if not readline.uses_libedit: | |||
|
1511 | for rlcommand in self.readline_parse_and_bind: | |||
|
1512 | #print "loading rl:",rlcommand # dbg | |||
|
1513 | readline.parse_and_bind(rlcommand) | |||
1428 |
|
1514 | |||
1429 | def alias_table_validate(self,verbose=0): |
|
1515 | # Remove some chars from the delimiters list. If we encounter | |
1430 | """Update information about the alias table. |
|
1516 | # unicode chars, discard them. | |
|
1517 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |||
|
1518 | delims = delims.translate(string._idmap, | |||
|
1519 | self.readline_remove_delims) | |||
|
1520 | readline.set_completer_delims(delims) | |||
|
1521 | # otherwise we end up with a monster history after a while: | |||
|
1522 | readline.set_history_length(1000) | |||
|
1523 | try: | |||
|
1524 | #print '*** Reading readline history' # dbg | |||
|
1525 | readline.read_history_file(self.histfile) | |||
|
1526 | except IOError: | |||
|
1527 | pass # It doesn't exist yet. | |||
1431 |
|
1528 | |||
1432 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1529 | atexit.register(self.atexit_operations) | |
|
1530 | del atexit | |||
1433 |
|
1531 | |||
1434 | no_alias = self.no_alias |
|
1532 | # Configure auto-indent for all platforms | |
1435 | for k in self.alias_table.keys(): |
|
1533 | self.set_autoindent(self.autoindent) | |
1436 | if k in no_alias: |
|
|||
1437 | del self.alias_table[k] |
|
|||
1438 | if verbose: |
|
|||
1439 | print ("Deleting alias <%s>, it's a Python " |
|
|||
1440 | "keyword or builtin." % k) |
|
|||
1441 |
|
1534 | |||
1442 | def set_next_input(self, s): |
|
1535 | def set_next_input(self, s): | |
1443 | """ Sets the 'default' input string for the next command line. |
|
1536 | """ Sets the 'default' input string for the next command line. | |
1444 |
|
1537 | |||
1445 | Requires readline. |
|
1538 | Requires readline. | |
1446 |
|
1539 | |||
1447 | Example: |
|
1540 | Example: | |
1448 |
|
1541 | |||
1449 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1542 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1450 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1543 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1451 | """ |
|
1544 | """ | |
1452 |
|
1545 | |||
1453 | self.rl_next_input = s |
|
1546 | self.rl_next_input = s | |
1454 |
|
1547 | |||
1455 |
def |
|
1548 | def pre_readline(self): | |
1456 | """Set the autoindent flag, checking for readline support. |
|
1549 | """readline hook to be used at the start of each line. | |
1457 |
|
1550 | |||
1458 | If called with no arguments, it acts as a toggle.""" |
|
1551 | Currently it handles auto-indent only.""" | |
1459 |
|
1552 | |||
1460 | if not self.has_readline: |
|
1553 | #debugx('self.indent_current_nsp','pre_readline:') | |
1461 | if os.name == 'posix': |
|
|||
1462 | warn("The auto-indent feature requires the readline library") |
|
|||
1463 | self.autoindent = 0 |
|
|||
1464 | return |
|
|||
1465 | if value is None: |
|
|||
1466 | self.autoindent = not self.autoindent |
|
|||
1467 | else: |
|
|||
1468 | self.autoindent = value |
|
|||
1469 |
|
1554 | |||
1470 | def atexit_operations(self): |
|
1555 | if self.rl_do_indent: | |
1471 | """This will be executed at the time of exit. |
|
1556 | self.readline.insert_text(self._indent_current_str()) | |
|
1557 | if self.rl_next_input is not None: | |||
|
1558 | self.readline.insert_text(self.rl_next_input) | |||
|
1559 | self.rl_next_input = None | |||
1472 |
|
1560 | |||
1473 | Saving of persistent data should be performed here. """ |
|
1561 | def _indent_current_str(self): | |
|
1562 | """return the current level of indentation as a string""" | |||
|
1563 | return self.indent_current_nsp * ' ' | |||
1474 |
|
1564 | |||
1475 | #print '*** IPython exit cleanup ***' # dbg |
|
1565 | #------------------------------------------------------------------------- | |
1476 | # input history |
|
1566 | # Things related to magics | |
1477 | self.savehist() |
|
1567 | #------------------------------------------------------------------------- | |
1478 |
|
1568 | |||
1479 | # Cleanup all tempfiles left around |
|
1569 | def init_magics(self): | |
1480 | for tfile in self.tempfiles: |
|
1570 | # Set user colors (don't do it in the constructor above so that it | |
1481 | try: |
|
1571 | # doesn't crash if colors option is invalid) | |
1482 | os.unlink(tfile) |
|
1572 | self.magic_colors(self.colors) | |
1483 | except OSError: |
|
|||
1484 | pass |
|
|||
1485 |
|
1573 | |||
1486 | # Clear all user namespaces to release all references cleanly. |
|
1574 | def magic(self,arg_s): | |
1487 | self.reset() |
|
1575 | """Call a magic function by name. | |
1488 |
|
|
1576 | ||
1489 | # Run user hooks |
|
1577 | Input: a string containing the name of the magic function to call and any | |
1490 | self.hooks.shutdown_hook() |
|
1578 | additional arguments to be passed to the magic. | |
1491 |
|
|
1579 | ||
1492 | def reset(self): |
|
1580 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1493 | """Clear all internal namespaces. |
|
1581 | prompt: | |
1494 |
|
1582 | |||
1495 | Note that this is much more aggressive than %reset, since it clears |
|
1583 | In[1]: %name -opt foo bar | |
1496 | fully all namespaces, as well as all input/output lists. |
|
|||
1497 | """ |
|
|||
1498 | for ns in self.ns_refs_table: |
|
|||
1499 | ns.clear() |
|
|||
1500 |
|
|
1584 | ||
1501 | # Clear input and output histories |
|
1585 | To call a magic without arguments, simply use magic('name'). | |
1502 | self.input_hist[:] = [] |
|
|||
1503 | self.input_hist_raw[:] = [] |
|
|||
1504 | self.output_hist.clear() |
|
|||
1505 | # Restore the user namespaces to minimal usability |
|
|||
1506 | self.init_user_ns() |
|
|||
1507 |
|
1586 | |||
1508 | def savehist(self): |
|
1587 | This provides a proper Python function to call IPython's magics in any | |
1509 | """Save input history to a file (via readline library).""" |
|
1588 | valid Python code you can type at the interpreter, including loops and | |
|
1589 | compound statements. | |||
|
1590 | """ | |||
1510 |
|
1591 | |||
1511 | if not self.has_readline: |
|
1592 | args = arg_s.split(' ',1) | |
1512 | return |
|
1593 | magic_name = args[0] | |
|
1594 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |||
1513 |
|
1595 | |||
1514 | try: |
|
1596 | try: | |
1515 | self.readline.write_history_file(self.histfile) |
|
1597 | magic_args = args[1] | |
1516 | except: |
|
1598 | except IndexError: | |
1517 | print 'Unable to save IPython command history to file: ' + \ |
|
1599 | magic_args = '' | |
1518 | `self.histfile` |
|
1600 | fn = getattr(self,'magic_'+magic_name,None) | |
|
1601 | if fn is None: | |||
|
1602 | error("Magic function `%s` not found." % magic_name) | |||
|
1603 | else: | |||
|
1604 | magic_args = self.var_expand(magic_args,1) | |||
|
1605 | with nested(self.builtin_trap, self.display_trap): | |||
|
1606 | return fn(magic_args) | |||
|
1607 | # return result | |||
1519 |
|
1608 | |||
1520 | def reloadhist(self): |
|
1609 | def define_magic(self, magicname, func): | |
1521 | """Reload the input history from disk file.""" |
|
1610 | """Expose own function as magic function for ipython | |
1522 |
|
1611 | |||
1523 | if self.has_readline: |
|
1612 | def foo_impl(self,parameter_s=''): | |
1524 | try: |
|
1613 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1525 | self.readline.clear_history() |
|
1614 | print 'Magic function. Passed parameter is between < >:' | |
1526 | self.readline.read_history_file(self.shell.histfile) |
|
1615 | print '<%s>' % parameter_s | |
1527 | except AttributeError: |
|
1616 | print 'The self object is:',self | |
1528 | pass |
|
|||
1529 |
|
1617 | |||
|
1618 | self.define_magic('foo',foo_impl) | |||
|
1619 | """ | |||
1530 |
|
1620 | |||
1531 | def history_saving_wrapper(self, func): |
|
1621 | import new | |
1532 | """ Wrap func for readline history saving |
|
1622 | im = new.instancemethod(func,self, self.__class__) | |
|
1623 | old = getattr(self, "magic_" + magicname, None) | |||
|
1624 | setattr(self, "magic_" + magicname, im) | |||
|
1625 | return old | |||
1533 |
|
1626 | |||
1534 | Convert func into callable that saves & restores |
|
1627 | #------------------------------------------------------------------------- | |
1535 | history around the call """ |
|
1628 | # Things related to macros | |
|
1629 | #------------------------------------------------------------------------- | |||
1536 |
|
1630 | |||
1537 | if not self.has_readline: |
|
1631 | def define_macro(self, name, themacro): | |
1538 | return func |
|
1632 | """Define a new macro | |
1539 |
|
1633 | |||
1540 |
|
|
1634 | Parameters | |
1541 | self.savehist() |
|
1635 | ---------- | |
1542 |
|
|
1636 | name : str | |
1543 |
|
|
1637 | The name of the macro. | |
1544 | finally: |
|
1638 | themacro : str or Macro | |
1545 | readline.read_history_file(self.histfile) |
|
1639 | The action to do upon invoking the macro. If a string, a new | |
1546 | return wrapper |
|
1640 | Macro object is created by passing the string to it. | |
|
1641 | """ | |||
1547 |
|
|
1642 | ||
1548 | def pre_readline(self): |
|
1643 | from IPython.core import macro | |
1549 | """readline hook to be used at the start of each line. |
|
|||
1550 |
|
1644 | |||
1551 | Currently it handles auto-indent only.""" |
|
1645 | if isinstance(themacro, basestring): | |
|
1646 | themacro = macro.Macro(themacro) | |||
|
1647 | if not isinstance(themacro, macro.Macro): | |||
|
1648 | raise ValueError('A macro must be a string or a Macro instance.') | |||
|
1649 | self.user_ns[name] = themacro | |||
1552 |
|
1650 | |||
1553 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1651 | #------------------------------------------------------------------------- | |
|
1652 | # Things related to the running of system commands | |||
|
1653 | #------------------------------------------------------------------------- | |||
1554 |
|
1654 | |||
1555 | if self.rl_do_indent: |
|
1655 | def system(self, cmd): | |
1556 | self.readline.insert_text(self.indent_current_str()) |
|
1656 | """Make a system call, using IPython.""" | |
1557 | if self.rl_next_input is not None: |
|
1657 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
1558 | self.readline.insert_text(self.rl_next_input) |
|
|||
1559 | self.rl_next_input = None |
|
|||
1560 |
|
1658 | |||
1561 | def ask_yes_no(self,prompt,default=True): |
|
1659 | #------------------------------------------------------------------------- | |
1562 | if self.quiet: |
|
1660 | # Things related to aliases | |
1563 | return True |
|
1661 | #------------------------------------------------------------------------- | |
1564 | return ask_yes_no(prompt,default) |
|
1662 | ||
|
1663 | def init_aliases(self): | |||
|
1664 | # dict of things NOT to alias (keywords, builtins and some magics) | |||
|
1665 | no_alias = {} | |||
|
1666 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |||
|
1667 | for key in keyword.kwlist + no_alias_magics: | |||
|
1668 | no_alias[key] = 1 | |||
|
1669 | no_alias.update(__builtin__.__dict__) | |||
|
1670 | self.no_alias = no_alias | |||
|
1671 | ||||
|
1672 | # Make some aliases automatically | |||
|
1673 | # Prepare list of shell aliases to auto-define | |||
|
1674 | if os.name == 'posix': | |||
|
1675 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |||
|
1676 | 'mv mv -i','rm rm -i','cp cp -i', | |||
|
1677 | 'cat cat','less less','clear clear', | |||
|
1678 | # a better ls | |||
|
1679 | 'ls ls -F', | |||
|
1680 | # long ls | |||
|
1681 | 'll ls -lF') | |||
|
1682 | # Extra ls aliases with color, which need special treatment on BSD | |||
|
1683 | # variants | |||
|
1684 | ls_extra = ( # color ls | |||
|
1685 | 'lc ls -F -o --color', | |||
|
1686 | # ls normal files only | |||
|
1687 | 'lf ls -F -o --color %l | grep ^-', | |||
|
1688 | # ls symbolic links | |||
|
1689 | 'lk ls -F -o --color %l | grep ^l', | |||
|
1690 | # directories or links to directories, | |||
|
1691 | 'ldir ls -F -o --color %l | grep /$', | |||
|
1692 | # things which are executable | |||
|
1693 | 'lx ls -F -o --color %l | grep ^-..x', | |||
|
1694 | ) | |||
|
1695 | # The BSDs don't ship GNU ls, so they don't understand the | |||
|
1696 | # --color switch out of the box | |||
|
1697 | if 'bsd' in sys.platform: | |||
|
1698 | ls_extra = ( # ls normal files only | |||
|
1699 | 'lf ls -lF | grep ^-', | |||
|
1700 | # ls symbolic links | |||
|
1701 | 'lk ls -lF | grep ^l', | |||
|
1702 | # directories or links to directories, | |||
|
1703 | 'ldir ls -lF | grep /$', | |||
|
1704 | # things which are executable | |||
|
1705 | 'lx ls -lF | grep ^-..x', | |||
|
1706 | ) | |||
|
1707 | auto_alias = auto_alias + ls_extra | |||
|
1708 | elif os.name in ['nt','dos']: | |||
|
1709 | auto_alias = ('ls dir /on', | |||
|
1710 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |||
|
1711 | 'mkdir mkdir','rmdir rmdir','echo echo', | |||
|
1712 | 'ren ren','cls cls','copy copy') | |||
|
1713 | else: | |||
|
1714 | auto_alias = () | |||
|
1715 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |||
1565 |
|
1716 | |||
1566 | def new_main_mod(self,ns=None): |
|
1717 | # Load default aliases | |
1567 | """Return a new 'main' module object for user code execution. |
|
1718 | for alias, cmd in self.auto_alias: | |
1568 | """ |
|
1719 | self.define_alias(alias,cmd) | |
1569 | main_mod = self._user_main_module |
|
|||
1570 | init_fakemod_dict(main_mod,ns) |
|
|||
1571 | return main_mod |
|
|||
1572 |
|
1720 | |||
1573 | def cache_main_mod(self,ns,fname): |
|
1721 | # Load user aliases | |
1574 | """Cache a main module's namespace. |
|
1722 | for alias in self.alias: | |
|
1723 | self.magic_alias(alias) | |||
1575 |
|
1724 | |||
1576 | When scripts are executed via %run, we must keep a reference to the |
|
1725 | def call_alias(self,alias,rest=''): | |
1577 | namespace of their __main__ module (a FakeModule instance) around so |
|
1726 | """Call an alias given its name and the rest of the line. | |
1578 | that Python doesn't clear it, rendering objects defined therein |
|
|||
1579 | useless. |
|
|||
1580 |
|
1727 | |||
1581 | This method keeps said reference in a private dict, keyed by the |
|
1728 | This is only used to provide backwards compatibility for users of | |
1582 | absolute path of the module object (which corresponds to the script |
|
1729 | ipalias(), use of which is not recommended for anymore.""" | |
1583 | path). This way, for multiple executions of the same script we only |
|
|||
1584 | keep one copy of the namespace (the last one), thus preventing memory |
|
|||
1585 | leaks from old references while allowing the objects from the last |
|
|||
1586 | execution to be accessible. |
|
|||
1587 |
|
1730 | |||
1588 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
1731 | # Now call the macro, evaluating in the user's namespace | |
1589 | because of how Python tears down modules (it hard-sets all their |
|
1732 | cmd = self.transform_alias(alias, rest) | |
1590 | references to None without regard for reference counts). This method |
|
1733 | try: | |
1591 | must therefore make a *copy* of the given namespace, to allow the |
|
1734 | self.system(cmd) | |
1592 | original module's __dict__ to be cleared and reused. |
|
1735 | except: | |
|
1736 | self.showtraceback() | |||
1593 |
|
1737 | |||
|
1738 | def define_alias(self, name, cmd): | |||
|
1739 | """ Define a new alias.""" | |||
1594 |
|
1740 | |||
1595 | Parameters |
|
1741 | if callable(cmd): | |
1596 | ---------- |
|
1742 | self.alias_table[name] = cmd | |
1597 | ns : a namespace (a dict, typically) |
|
1743 | from IPython.core import shadowns | |
|
1744 | setattr(shadowns, name, cmd) | |||
|
1745 | return | |||
1598 |
|
1746 | |||
1599 | fname : str |
|
1747 | if isinstance(cmd, basestring): | |
1600 | Filename associated with the namespace. |
|
1748 | nargs = cmd.count('%s') | |
|
1749 | if nargs>0 and cmd.find('%l')>=0: | |||
|
1750 | raise Exception('The %s and %l specifiers are mutually ' | |||
|
1751 | 'exclusive in alias definitions.') | |||
1601 |
|
1752 | |||
1602 | Examples |
|
1753 | self.alias_table[name] = (nargs,cmd) | |
1603 | -------- |
|
1754 | return | |
1604 |
|
1755 | |||
1605 | In [10]: import IPython |
|
1756 | self.alias_table[name] = cmd | |
1606 |
|
1757 | |||
1607 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1758 | def ipalias(self,arg_s): | |
|
1759 | """Call an alias by name. | |||
1608 |
|
1760 | |||
1609 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
1761 | Input: a string containing the name of the alias to call and any | |
1610 | Out[12]: True |
|
1762 | additional arguments to be passed to the magic. | |
1611 | """ |
|
|||
1612 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
|||
1613 |
|
|
1763 | ||
1614 | def clear_main_mod_cache(self): |
|
1764 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
1615 | """Clear the cache of main modules. |
|
1765 | prompt: | |
1616 |
|
1766 | |||
1617 | Mainly for use by utilities like %reset. |
|
1767 | In[1]: name -opt foo bar | |
1618 |
|
1768 | |||
1619 | Examples |
|
1769 | To call an alias without arguments, simply use ipalias('name'). | |
1620 | -------- |
|
|||
1621 |
|
1770 | |||
1622 | In [15]: import IPython |
|
1771 | This provides a proper Python function to call IPython's aliases in any | |
|
1772 | valid Python code you can type at the interpreter, including loops and | |||
|
1773 | compound statements. It is added by IPython to the Python builtin | |||
|
1774 | namespace upon initialization.""" | |||
1623 |
|
1775 | |||
1624 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1776 | args = arg_s.split(' ',1) | |
|
1777 | alias_name = args[0] | |||
|
1778 | try: | |||
|
1779 | alias_args = args[1] | |||
|
1780 | except IndexError: | |||
|
1781 | alias_args = '' | |||
|
1782 | if alias_name in self.alias_table: | |||
|
1783 | self.call_alias(alias_name,alias_args) | |||
|
1784 | else: | |||
|
1785 | error("Alias `%s` not found." % alias_name) | |||
1625 |
|
1786 | |||
1626 | In [17]: len(_ip._main_ns_cache) > 0 |
|
1787 | def expand_alias(self, line): | |
1627 | Out[17]: True |
|
1788 | """ Expand an alias in the command line | |
1628 |
|
1789 | |||
1629 | In [18]: _ip.clear_main_mod_cache() |
|
1790 | Returns the provided command line, possibly with the first word | |
|
1791 | (command) translated according to alias expansion rules. | |||
1630 |
|
1792 | |||
1631 | In [19]: len(_ip._main_ns_cache) == 0 |
|
1793 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |
1632 | Out[19]: True |
|
1794 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |
1633 | """ |
|
1795 | """ | |
1634 | self._main_ns_cache.clear() |
|
|||
1635 |
|
||||
1636 | def _should_recompile(self,e): |
|
|||
1637 | """Utility routine for edit_syntax_error""" |
|
|||
1638 |
|
||||
1639 | if e.filename in ('<ipython console>','<input>','<string>', |
|
|||
1640 | '<console>','<BackgroundJob compilation>', |
|
|||
1641 | None): |
|
|||
1642 |
|
||||
1643 | return False |
|
|||
1644 | try: |
|
|||
1645 | if (self.autoedit_syntax and |
|
|||
1646 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
|||
1647 | '[Y/n] ','y')): |
|
|||
1648 | return False |
|
|||
1649 | except EOFError: |
|
|||
1650 | return False |
|
|||
1651 |
|
1796 | |||
1652 | def int0(x): |
|
1797 | pre,fn,rest = self.split_user_input(line) | |
1653 | try: |
|
1798 | res = pre + self.expand_aliases(fn, rest) | |
1654 |
|
|
1799 | return res | |
1655 | except TypeError: |
|
|||
1656 | return 0 |
|
|||
1657 | # always pass integer line and offset values to editor hook |
|
|||
1658 | try: |
|
|||
1659 | self.hooks.fix_error_editor(e.filename, |
|
|||
1660 | int0(e.lineno),int0(e.offset),e.msg) |
|
|||
1661 | except TryNext: |
|
|||
1662 | warn('Could not open editor') |
|
|||
1663 | return False |
|
|||
1664 | return True |
|
|||
1665 |
|
1800 | |||
1666 | def edit_syntax_error(self): |
|
1801 | def expand_aliases(self, fn, rest): | |
1667 | """The bottom half of the syntax error handler called in the main loop. |
|
1802 | """Expand multiple levels of aliases: | |
1668 |
|
1803 | |||
1669 | Loop until syntax error is fixed or user cancels. |
|
1804 | if: | |
1670 | """ |
|
|||
1671 |
|
1805 | |||
1672 | while self.SyntaxTB.last_syntax_error: |
|
1806 | alias foo bar /tmp | |
1673 | # copy and clear last_syntax_error |
|
1807 | alias baz foo | |
1674 | err = self.SyntaxTB.clear_err_state() |
|
|||
1675 | if not self._should_recompile(err): |
|
|||
1676 | return |
|
|||
1677 | try: |
|
|||
1678 | # may set last_syntax_error again if a SyntaxError is raised |
|
|||
1679 | self.safe_execfile(err.filename,self.user_ns) |
|
|||
1680 | except: |
|
|||
1681 | self.showtraceback() |
|
|||
1682 | else: |
|
|||
1683 | try: |
|
|||
1684 | f = file(err.filename) |
|
|||
1685 | try: |
|
|||
1686 | # This should be inside a display_trap block and I |
|
|||
1687 | # think it is. |
|
|||
1688 | sys.displayhook(f.read()) |
|
|||
1689 | finally: |
|
|||
1690 | f.close() |
|
|||
1691 | except: |
|
|||
1692 | self.showtraceback() |
|
|||
1693 |
|
1808 | |||
1694 | def showsyntaxerror(self, filename=None): |
|
1809 | then: | |
1695 | """Display the syntax error that just occurred. |
|
|||
1696 |
|
1810 | |||
1697 | This doesn't display a stack trace because there isn't one. |
|
1811 | baz huhhahhei -> bar /tmp huhhahhei | |
1698 |
|
1812 | |||
1699 | If a filename is given, it is stuffed in the exception instead |
|
|||
1700 | of what was there before (because Python's parser always uses |
|
|||
1701 | "<string>" when reading from a string). |
|
|||
1702 | """ |
|
1813 | """ | |
1703 | etype, value, last_traceback = sys.exc_info() |
|
1814 | line = fn + " " + rest | |
1704 |
|
1815 | |||
1705 | # See note about these variables in showtraceback() below |
|
1816 | done = set() | |
1706 | sys.last_type = etype |
|
1817 | while 1: | |
1707 | sys.last_value = value |
|
1818 | pre,fn,rest = prefilter.splitUserInput(line, | |
1708 | sys.last_traceback = last_traceback |
|
1819 | prefilter.shell_line_split) | |
|
1820 | if fn in self.alias_table: | |||
|
1821 | if fn in done: | |||
|
1822 | warn("Cyclic alias definition, repeated '%s'" % fn) | |||
|
1823 | return "" | |||
|
1824 | done.add(fn) | |||
1709 |
|
1825 | |||
1710 | if filename and etype is SyntaxError: |
|
1826 | l2 = self.transform_alias(fn,rest) | |
1711 | # Work hard to stuff the correct filename in the exception |
|
1827 | # dir -> dir | |
1712 | try: |
|
1828 | # print "alias",line, "->",l2 #dbg | |
1713 | msg, (dummy_filename, lineno, offset, line) = value |
|
1829 | if l2 == line: | |
1714 | except: |
|
1830 | break | |
1715 | # Not the format we expect; leave it alone |
|
1831 | # ls -> ls -F should not recurse forever | |
1716 | pass |
|
1832 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1717 |
|
|
1833 | line = l2 | |
1718 |
|
|
1834 | break | |
1719 | try: |
|
|||
1720 | # Assume SyntaxError is a class exception |
|
|||
1721 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
|||
1722 | except: |
|
|||
1723 | # If that failed, assume SyntaxError is a string |
|
|||
1724 | value = msg, (filename, lineno, offset, line) |
|
|||
1725 | self.SyntaxTB(etype,value,[]) |
|
|||
1726 |
|
1835 | |||
1727 | def debugger(self,force=False): |
|
1836 | line=l2 | |
1728 | """Call the pydb/pdb debugger. |
|
|||
1729 |
|
1837 | |||
1730 | Keywords: |
|
|||
1731 |
|
1838 | |||
1732 | - force(False): by default, this routine checks the instance call_pdb |
|
1839 | # print "al expand to",line #dbg | |
1733 | flag and does not actually invoke the debugger if the flag is false. |
|
1840 | else: | |
1734 | The 'force' option forces the debugger to activate even if the flag |
|
1841 | break | |
1735 | is false. |
|
|||
1736 | """ |
|
|||
1737 |
|
1842 | |||
1738 | if not (force or self.call_pdb): |
|
1843 | return line | |
1739 | return |
|
|||
1740 |
|
1844 | |||
1741 | if not hasattr(sys,'last_traceback'): |
|
1845 | def transform_alias(self, alias,rest=''): | |
1742 | error('No traceback has been produced, nothing to debug.') |
|
1846 | """ Transform alias to system command string. | |
1743 | return |
|
1847 | """ | |
|
1848 | trg = self.alias_table[alias] | |||
1744 |
|
1849 | |||
1745 | # use pydb if available |
|
1850 | nargs,cmd = trg | |
1746 | if debugger.has_pydb: |
|
1851 | # print trg #dbg | |
1747 | from pydb import pm |
|
1852 | if ' ' in cmd and os.path.isfile(cmd): | |
|
1853 | cmd = '"%s"' % cmd | |||
|
1854 | ||||
|
1855 | # Expand the %l special to be the user's input line | |||
|
1856 | if cmd.find('%l') >= 0: | |||
|
1857 | cmd = cmd.replace('%l',rest) | |||
|
1858 | rest = '' | |||
|
1859 | if nargs==0: | |||
|
1860 | # Simple, argument-less aliases | |||
|
1861 | cmd = '%s %s' % (cmd,rest) | |||
1748 | else: |
|
1862 | else: | |
1749 | # fallback to our internal debugger |
|
1863 | # Handle aliases with positional arguments | |
1750 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1864 | args = rest.split(None,nargs) | |
1751 | self.history_saving_wrapper(pm)() |
|
1865 | if len(args)< nargs: | |
|
1866 | error('Alias <%s> requires %s arguments, %s given.' % | |||
|
1867 | (alias,nargs,len(args))) | |||
|
1868 | return None | |||
|
1869 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |||
|
1870 | # Now call the macro, evaluating in the user's namespace | |||
|
1871 | #print 'new command: <%r>' % cmd # dbg | |||
|
1872 | return cmd | |||
1752 |
|
1873 | |||
1753 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1874 | def init_auto_alias(self): | |
1754 | """Display the exception that just occurred. |
|
1875 | """Define some aliases automatically. | |
1755 |
|
1876 | |||
1756 | If nothing is known about the exception, this is the method which |
|
1877 | These are ALL parameter-less aliases""" | |
1757 | should be used throughout the code for presenting user tracebacks, |
|
|||
1758 | rather than directly invoking the InteractiveTB object. |
|
|||
1759 |
|
1878 | |||
1760 | A specific showsyntaxerror() also exists, but this method can take |
|
1879 | for alias,cmd in self.auto_alias: | |
1761 | care of calling it if needed, so unless you are explicitly catching a |
|
1880 | self.define_alias(alias,cmd) | |
1762 | SyntaxError exception, don't try to analyze the stack manually and |
|
|||
1763 | simply call this method.""" |
|
|||
1764 |
|
1881 | |||
|
1882 | def alias_table_validate(self,verbose=0): | |||
|
1883 | """Update information about the alias table. | |||
1765 |
|
1884 | |||
1766 | # Though this won't be called by syntax errors in the input line, |
|
1885 | In particular, make sure no Python keywords/builtins are in it.""" | |
1767 | # there may be SyntaxError cases whith imported code. |
|
|||
1768 |
|
1886 | |||
1769 | try: |
|
1887 | no_alias = self.no_alias | |
1770 | if exc_tuple is None: |
|
1888 | for k in self.alias_table.keys(): | |
1771 | etype, value, tb = sys.exc_info() |
|
1889 | if k in no_alias: | |
1772 | else: |
|
1890 | del self.alias_table[k] | |
1773 | etype, value, tb = exc_tuple |
|
1891 | if verbose: | |
|
1892 | print ("Deleting alias <%s>, it's a Python " | |||
|
1893 | "keyword or builtin." % k) | |||
1774 |
|
1894 | |||
1775 | if etype is SyntaxError: |
|
1895 | #------------------------------------------------------------------------- | |
1776 | self.showsyntaxerror(filename) |
|
1896 | # Things related to the running of code | |
1777 | elif etype is UsageError: |
|
1897 | #------------------------------------------------------------------------- | |
1778 | print "UsageError:", value |
|
|||
1779 | else: |
|
|||
1780 | # WARNING: these variables are somewhat deprecated and not |
|
|||
1781 | # necessarily safe to use in a threaded environment, but tools |
|
|||
1782 | # like pdb depend on their existence, so let's set them. If we |
|
|||
1783 | # find problems in the field, we'll need to revisit their use. |
|
|||
1784 | sys.last_type = etype |
|
|||
1785 | sys.last_value = value |
|
|||
1786 | sys.last_traceback = tb |
|
|||
1787 |
|
1898 | |||
1788 | if etype in self.custom_exceptions: |
|
1899 | def ex(self, cmd): | |
1789 | self.CustomTB(etype,value,tb) |
|
1900 | """Execute a normal python statement in user namespace.""" | |
1790 | else: |
|
1901 | with nested(self.builtin_trap, self.display_trap): | |
1791 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1902 | exec cmd in self.user_global_ns, self.user_ns | |
1792 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1903 | ||
1793 | # pdb mucks up readline, fix it back |
|
1904 | def ev(self, expr): | |
1794 | self.set_completer() |
|
1905 | """Evaluate python expression expr in user namespace. | |
1795 | except KeyboardInterrupt: |
|
1906 | ||
1796 | self.write("\nKeyboardInterrupt\n") |
|
1907 | Returns the result of evaluation | |
|
1908 | """ | |||
|
1909 | with nested(self.builtin_trap, self.display_trap): | |||
|
1910 | return eval(expr, self.user_global_ns, self.user_ns) | |||
1797 |
|
1911 | |||
1798 | def mainloop(self, banner=None): |
|
1912 | def mainloop(self, banner=None): | |
1799 | """Start the mainloop. |
|
1913 | """Start the mainloop. | |
1800 |
|
1914 | |||
1801 | If an optional banner argument is given, it will override the |
|
1915 | If an optional banner argument is given, it will override the | |
1802 | internally created default banner. |
|
1916 | internally created default banner. | |
1803 | """ |
|
1917 | """ | |
1804 |
|
1918 | |||
1805 | with nested(self.builtin_trap, self.display_trap): |
|
1919 | with nested(self.builtin_trap, self.display_trap): | |
1806 | if self.c: # Emulate Python's -c option |
|
1920 | if self.c: # Emulate Python's -c option | |
1807 | self.exec_init_cmd() |
|
1921 | self.exec_init_cmd() | |
1808 |
|
1922 | |||
1809 | if self.display_banner: |
|
1923 | if self.display_banner: | |
1810 | if banner is None: |
|
1924 | if banner is None: | |
1811 | banner = self.banner |
|
1925 | banner = self.banner | |
1812 |
|
1926 | |||
1813 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1927 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1814 | # ensure that it's in sync |
|
1928 | # ensure that it's in sync | |
1815 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1929 | if len(self.input_hist) != len (self.input_hist_raw): | |
1816 | self.input_hist_raw = InputList(self.input_hist) |
|
1930 | self.input_hist_raw = InputList(self.input_hist) | |
1817 |
|
1931 | |||
1818 | while 1: |
|
1932 | while 1: | |
1819 | try: |
|
1933 | try: | |
1820 | self.interact() |
|
1934 | self.interact() | |
1821 | #self.interact_with_readline() |
|
1935 | #self.interact_with_readline() | |
1822 | # XXX for testing of a readline-decoupled repl loop, call |
|
1936 | # XXX for testing of a readline-decoupled repl loop, call | |
1823 | # interact_with_readline above |
|
1937 | # interact_with_readline above | |
1824 | break |
|
1938 | break | |
1825 | except KeyboardInterrupt: |
|
1939 | except KeyboardInterrupt: | |
1826 | # this should not be necessary, but KeyboardInterrupt |
|
1940 | # this should not be necessary, but KeyboardInterrupt | |
1827 | # handling seems rather unpredictable... |
|
1941 | # handling seems rather unpredictable... | |
1828 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1942 | self.write("\nKeyboardInterrupt in interact()\n") | |
1829 |
|
1943 | |||
1830 | def exec_init_cmd(self): |
|
1944 | def exec_init_cmd(self): | |
1831 | """Execute a command given at the command line. |
|
1945 | """Execute a command given at the command line. | |
1832 |
|
1946 | |||
1833 | This emulates Python's -c option.""" |
|
1947 | This emulates Python's -c option.""" | |
1834 |
|
1948 | |||
1835 | #sys.argv = ['-c'] |
|
1949 | #sys.argv = ['-c'] | |
1836 | self.push_line(self.prefilter(self.c, False)) |
|
1950 | self.push_line(self.prefilter(self.c, False)) | |
1837 | if not self.interactive: |
|
1951 | if not self.interactive: | |
1838 | self.ask_exit() |
|
1952 | self.ask_exit() | |
1839 |
|
1953 | |||
1840 | def interact_prompt(self): |
|
1954 | def interact_prompt(self): | |
1841 | """ Print the prompt (in read-eval-print loop) |
|
1955 | """ Print the prompt (in read-eval-print loop) | |
1842 |
|
1956 | |||
1843 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1957 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1844 | used in standard IPython flow. |
|
1958 | used in standard IPython flow. | |
1845 | """ |
|
1959 | """ | |
1846 | if self.more: |
|
1960 | if self.more: | |
1847 | try: |
|
1961 | try: | |
1848 | prompt = self.hooks.generate_prompt(True) |
|
1962 | prompt = self.hooks.generate_prompt(True) | |
1849 | except: |
|
1963 | except: | |
1850 | self.showtraceback() |
|
1964 | self.showtraceback() | |
1851 | if self.autoindent: |
|
1965 | if self.autoindent: | |
1852 | self.rl_do_indent = True |
|
1966 | self.rl_do_indent = True | |
1853 |
|
1967 | |||
1854 | else: |
|
1968 | else: | |
1855 | try: |
|
1969 | try: | |
1856 | prompt = self.hooks.generate_prompt(False) |
|
1970 | prompt = self.hooks.generate_prompt(False) | |
1857 | except: |
|
1971 | except: | |
1858 | self.showtraceback() |
|
1972 | self.showtraceback() | |
1859 | self.write(prompt) |
|
1973 | self.write(prompt) | |
1860 |
|
1974 | |||
1861 | def interact_handle_input(self,line): |
|
1975 | def interact_handle_input(self,line): | |
1862 | """ Handle the input line (in read-eval-print loop) |
|
1976 | """ Handle the input line (in read-eval-print loop) | |
1863 |
|
1977 | |||
1864 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1978 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1865 | used in standard IPython flow. |
|
1979 | used in standard IPython flow. | |
1866 | """ |
|
1980 | """ | |
1867 | if line.lstrip() == line: |
|
1981 | if line.lstrip() == line: | |
1868 | self.shadowhist.add(line.strip()) |
|
1982 | self.shadowhist.add(line.strip()) | |
1869 | lineout = self.prefilter(line,self.more) |
|
1983 | lineout = self.prefilter(line,self.more) | |
1870 |
|
1984 | |||
1871 | if line.strip(): |
|
1985 | if line.strip(): | |
1872 | if self.more: |
|
1986 | if self.more: | |
1873 | self.input_hist_raw[-1] += '%s\n' % line |
|
1987 | self.input_hist_raw[-1] += '%s\n' % line | |
1874 | else: |
|
1988 | else: | |
1875 | self.input_hist_raw.append('%s\n' % line) |
|
1989 | self.input_hist_raw.append('%s\n' % line) | |
1876 |
|
1990 | |||
1877 |
|
1991 | |||
1878 | self.more = self.push_line(lineout) |
|
1992 | self.more = self.push_line(lineout) | |
1879 | if (self.SyntaxTB.last_syntax_error and |
|
1993 | if (self.SyntaxTB.last_syntax_error and | |
1880 | self.autoedit_syntax): |
|
1994 | self.autoedit_syntax): | |
1881 | self.edit_syntax_error() |
|
1995 | self.edit_syntax_error() | |
1882 |
|
1996 | |||
1883 | def interact_with_readline(self): |
|
1997 | def interact_with_readline(self): | |
1884 | """ Demo of using interact_handle_input, interact_prompt |
|
1998 | """ Demo of using interact_handle_input, interact_prompt | |
1885 |
|
1999 | |||
1886 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
2000 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1887 | it should work like this. |
|
2001 | it should work like this. | |
1888 | """ |
|
2002 | """ | |
1889 | self.readline_startup_hook(self.pre_readline) |
|
2003 | self.readline_startup_hook(self.pre_readline) | |
1890 | while not self.exit_now: |
|
2004 | while not self.exit_now: | |
1891 | self.interact_prompt() |
|
2005 | self.interact_prompt() | |
1892 | if self.more: |
|
2006 | if self.more: | |
1893 | self.rl_do_indent = True |
|
2007 | self.rl_do_indent = True | |
1894 | else: |
|
2008 | else: | |
1895 | self.rl_do_indent = False |
|
2009 | self.rl_do_indent = False | |
1896 | line = raw_input_original().decode(self.stdin_encoding) |
|
2010 | line = raw_input_original().decode(self.stdin_encoding) | |
1897 | self.interact_handle_input(line) |
|
2011 | self.interact_handle_input(line) | |
1898 |
|
2012 | |||
1899 | def interact(self, banner=None): |
|
2013 | def interact(self, banner=None): | |
1900 | """Closely emulate the interactive Python console.""" |
|
2014 | """Closely emulate the interactive Python console.""" | |
1901 |
|
2015 | |||
1902 | # batch run -> do not interact |
|
2016 | # batch run -> do not interact | |
1903 | if self.exit_now: |
|
2017 | if self.exit_now: | |
1904 | return |
|
2018 | return | |
1905 |
|
2019 | |||
1906 | if self.display_banner: |
|
2020 | if self.display_banner: | |
1907 | if banner is None: |
|
2021 | if banner is None: | |
1908 | banner = self.banner |
|
2022 | banner = self.banner | |
1909 | self.write(banner) |
|
2023 | self.write(banner) | |
1910 |
|
2024 | |||
1911 | more = 0 |
|
2025 | more = 0 | |
1912 |
|
2026 | |||
1913 | # Mark activity in the builtins |
|
2027 | # Mark activity in the builtins | |
1914 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
2028 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1915 |
|
2029 | |||
1916 | if self.has_readline: |
|
2030 | if self.has_readline: | |
1917 | self.readline_startup_hook(self.pre_readline) |
|
2031 | self.readline_startup_hook(self.pre_readline) | |
1918 | # exit_now is set by a call to %Exit or %Quit, through the |
|
2032 | # exit_now is set by a call to %Exit or %Quit, through the | |
1919 | # ask_exit callback. |
|
2033 | # ask_exit callback. | |
1920 |
|
2034 | |||
1921 | while not self.exit_now: |
|
2035 | while not self.exit_now: | |
1922 | self.hooks.pre_prompt_hook() |
|
2036 | self.hooks.pre_prompt_hook() | |
1923 | if more: |
|
2037 | if more: | |
1924 | try: |
|
2038 | try: | |
1925 | prompt = self.hooks.generate_prompt(True) |
|
2039 | prompt = self.hooks.generate_prompt(True) | |
1926 | except: |
|
2040 | except: | |
1927 | self.showtraceback() |
|
2041 | self.showtraceback() | |
1928 | if self.autoindent: |
|
2042 | if self.autoindent: | |
1929 | self.rl_do_indent = True |
|
2043 | self.rl_do_indent = True | |
1930 |
|
2044 | |||
1931 | else: |
|
2045 | else: | |
1932 | try: |
|
2046 | try: | |
1933 | prompt = self.hooks.generate_prompt(False) |
|
2047 | prompt = self.hooks.generate_prompt(False) | |
1934 | except: |
|
2048 | except: | |
1935 | self.showtraceback() |
|
2049 | self.showtraceback() | |
1936 | try: |
|
2050 | try: | |
1937 | line = self.raw_input(prompt, more) |
|
2051 | line = self.raw_input(prompt, more) | |
1938 | if self.exit_now: |
|
2052 | if self.exit_now: | |
1939 | # quick exit on sys.std[in|out] close |
|
2053 | # quick exit on sys.std[in|out] close | |
1940 | break |
|
2054 | break | |
1941 | if self.autoindent: |
|
2055 | if self.autoindent: | |
1942 | self.rl_do_indent = False |
|
2056 | self.rl_do_indent = False | |
1943 |
|
2057 | |||
1944 | except KeyboardInterrupt: |
|
2058 | except KeyboardInterrupt: | |
1945 | #double-guard against keyboardinterrupts during kbdint handling |
|
2059 | #double-guard against keyboardinterrupts during kbdint handling | |
1946 | try: |
|
2060 | try: | |
1947 | self.write('\nKeyboardInterrupt\n') |
|
2061 | self.write('\nKeyboardInterrupt\n') | |
1948 | self.resetbuffer() |
|
2062 | self.resetbuffer() | |
1949 | # keep cache in sync with the prompt counter: |
|
2063 | # keep cache in sync with the prompt counter: | |
1950 | self.outputcache.prompt_count -= 1 |
|
2064 | self.outputcache.prompt_count -= 1 | |
1951 |
|
2065 | |||
1952 | if self.autoindent: |
|
2066 | if self.autoindent: | |
1953 | self.indent_current_nsp = 0 |
|
2067 | self.indent_current_nsp = 0 | |
1954 | more = 0 |
|
2068 | more = 0 | |
1955 | except KeyboardInterrupt: |
|
2069 | except KeyboardInterrupt: | |
1956 | pass |
|
2070 | pass | |
1957 | except EOFError: |
|
2071 | except EOFError: | |
1958 | if self.autoindent: |
|
2072 | if self.autoindent: | |
1959 | self.rl_do_indent = False |
|
2073 | self.rl_do_indent = False | |
1960 | self.readline_startup_hook(None) |
|
2074 | self.readline_startup_hook(None) | |
1961 | self.write('\n') |
|
2075 | self.write('\n') | |
1962 | self.exit() |
|
2076 | self.exit() | |
1963 | except bdb.BdbQuit: |
|
2077 | except bdb.BdbQuit: | |
1964 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
2078 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1965 | 'Because of how pdb handles the stack, it is impossible\n' |
|
2079 | 'Because of how pdb handles the stack, it is impossible\n' | |
1966 | 'for IPython to properly format this particular exception.\n' |
|
2080 | 'for IPython to properly format this particular exception.\n' | |
1967 | 'IPython will resume normal operation.') |
|
2081 | 'IPython will resume normal operation.') | |
1968 | except: |
|
2082 | except: | |
1969 | # exceptions here are VERY RARE, but they can be triggered |
|
2083 | # exceptions here are VERY RARE, but they can be triggered | |
1970 | # asynchronously by signal handlers, for example. |
|
2084 | # asynchronously by signal handlers, for example. | |
1971 | self.showtraceback() |
|
2085 | self.showtraceback() | |
1972 | else: |
|
2086 | else: | |
1973 | more = self.push_line(line) |
|
2087 | more = self.push_line(line) | |
1974 | if (self.SyntaxTB.last_syntax_error and |
|
2088 | if (self.SyntaxTB.last_syntax_error and | |
1975 | self.autoedit_syntax): |
|
2089 | self.autoedit_syntax): | |
1976 | self.edit_syntax_error() |
|
2090 | self.edit_syntax_error() | |
1977 |
|
2091 | |||
1978 | # We are off again... |
|
2092 | # We are off again... | |
1979 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
2093 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1980 |
|
2094 | |||
1981 | def excepthook(self, etype, value, tb): |
|
2095 | def safe_execfile(self,fname,*where,**kw): | |
1982 | """One more defense for GUI apps that call sys.excepthook. |
|
2096 | """A safe version of the builtin execfile(). | |
1983 |
|
||||
1984 | GUI frameworks like wxPython trap exceptions and call |
|
|||
1985 | sys.excepthook themselves. I guess this is a feature that |
|
|||
1986 | enables them to keep running after exceptions that would |
|
|||
1987 | otherwise kill their mainloop. This is a bother for IPython |
|
|||
1988 | which excepts to catch all of the program exceptions with a try: |
|
|||
1989 | except: statement. |
|
|||
1990 |
|
||||
1991 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
|||
1992 | any app directly invokes sys.excepthook, it will look to the user like |
|
|||
1993 | IPython crashed. In order to work around this, we can disable the |
|
|||
1994 | CrashHandler and replace it with this excepthook instead, which prints a |
|
|||
1995 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
|||
1996 | call sys.excepthook will generate a regular-looking exception from |
|
|||
1997 | IPython, and the CrashHandler will only be triggered by real IPython |
|
|||
1998 | crashes. |
|
|||
1999 |
|
||||
2000 | This hook should be used sparingly, only in places which are not likely |
|
|||
2001 | to be true IPython errors. |
|
|||
2002 | """ |
|
|||
2003 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
|||
2004 |
|
||||
2005 | def expand_alias(self, line): |
|
|||
2006 | """ Expand an alias in the command line |
|
|||
2007 |
|
||||
2008 | Returns the provided command line, possibly with the first word |
|
|||
2009 | (command) translated according to alias expansion rules. |
|
|||
2010 |
|
||||
2011 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
|||
2012 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
|||
2013 | """ |
|
|||
2014 |
|
||||
2015 | pre,fn,rest = self.split_user_input(line) |
|
|||
2016 | res = pre + self.expand_aliases(fn, rest) |
|
|||
2017 | return res |
|
|||
2018 |
|
|
2097 | ||
2019 | def expand_aliases(self, fn, rest): |
|
2098 | This version will never throw an exception, and knows how to handle | |
2020 | """Expand multiple levels of aliases: |
|
2099 | ipython logs as well. | |
2021 |
|
2100 | |||
2022 | if: |
|
2101 | :Parameters: | |
|
2102 | fname : string | |||
|
2103 | Name of the file to be executed. | |||
2023 |
|
2104 | |||
2024 | alias foo bar /tmp |
|
2105 | where : tuple | |
2025 | alias baz foo |
|
2106 | One or two namespaces, passed to execfile() as (globals,locals). | |
|
2107 | If only one is given, it is passed as both. | |||
2026 |
|
2108 | |||
2027 |
|
|
2109 | :Keywords: | |
|
2110 | islog : boolean (False) | |||
2028 |
|
2111 | |||
2029 | baz huhhahhei -> bar /tmp huhhahhei |
|
2112 | quiet : boolean (True) | |
2030 |
|
2113 | |||
|
2114 | exit_ignore : boolean (False) | |||
2031 | """ |
|
2115 | """ | |
2032 | line = fn + " " + rest |
|
|||
2033 |
|
||||
2034 | done = set() |
|
|||
2035 | while 1: |
|
|||
2036 | pre,fn,rest = prefilter.splitUserInput(line, |
|
|||
2037 | prefilter.shell_line_split) |
|
|||
2038 | if fn in self.alias_table: |
|
|||
2039 | if fn in done: |
|
|||
2040 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
|||
2041 | return "" |
|
|||
2042 | done.add(fn) |
|
|||
2043 |
|
||||
2044 | l2 = self.transform_alias(fn,rest) |
|
|||
2045 | # dir -> dir |
|
|||
2046 | # print "alias",line, "->",l2 #dbg |
|
|||
2047 | if l2 == line: |
|
|||
2048 | break |
|
|||
2049 | # ls -> ls -F should not recurse forever |
|
|||
2050 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
|||
2051 | line = l2 |
|
|||
2052 | break |
|
|||
2053 |
|
2116 | |||
2054 | line=l2 |
|
2117 | def syspath_cleanup(): | |
2055 |
|
2118 | """Internal cleanup routine for sys.path.""" | ||
2056 |
|
|
2119 | if add_dname: | |
2057 | # print "al expand to",line #dbg |
|
2120 | try: | |
2058 | else: |
|
2121 | sys.path.remove(dname) | |
2059 |
|
|
2122 | except ValueError: | |
2060 |
|
2123 | # For some reason the user has already removed it, ignore. | ||
2061 | return line |
|
2124 | pass | |
2062 |
|
2125 | |||
2063 | def transform_alias(self, alias,rest=''): |
|
2126 | fname = os.path.expanduser(fname) | |
2064 | """ Transform alias to system command string. |
|
|||
2065 | """ |
|
|||
2066 | trg = self.alias_table[alias] |
|
|||
2067 |
|
2127 | |||
2068 | nargs,cmd = trg |
|
2128 | # Find things also in current directory. This is needed to mimic the | |
2069 | # print trg #dbg |
|
2129 | # behavior of running a script from the system command line, where | |
2070 | if ' ' in cmd and os.path.isfile(cmd): |
|
2130 | # Python inserts the script's directory into sys.path | |
2071 | cmd = '"%s"' % cmd |
|
2131 | dname = os.path.dirname(os.path.abspath(fname)) | |
|
2132 | add_dname = False | |||
|
2133 | if dname not in sys.path: | |||
|
2134 | sys.path.insert(0,dname) | |||
|
2135 | add_dname = True | |||
2072 |
|
2136 | |||
2073 | # Expand the %l special to be the user's input line |
|
2137 | try: | |
2074 | if cmd.find('%l') >= 0: |
|
2138 | xfile = open(fname) | |
2075 | cmd = cmd.replace('%l',rest) |
|
2139 | except: | |
2076 | rest = '' |
|
2140 | print >> Term.cerr, \ | |
2077 | if nargs==0: |
|
2141 | 'Could not open file <%s> for safe execution.' % fname | |
2078 | # Simple, argument-less aliases |
|
2142 | syspath_cleanup() | |
2079 | cmd = '%s %s' % (cmd,rest) |
|
|||
2080 | else: |
|
|||
2081 | # Handle aliases with positional arguments |
|
|||
2082 | args = rest.split(None,nargs) |
|
|||
2083 | if len(args)< nargs: |
|
|||
2084 | error('Alias <%s> requires %s arguments, %s given.' % |
|
|||
2085 | (alias,nargs,len(args))) |
|
|||
2086 |
|
|
2143 | return None | |
2087 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
|||
2088 | # Now call the macro, evaluating in the user's namespace |
|
|||
2089 | #print 'new command: <%r>' % cmd # dbg |
|
|||
2090 | return cmd |
|
|||
2091 |
|
2144 | |||
2092 | def call_alias(self,alias,rest=''): |
|
2145 | kw.setdefault('islog',0) | |
2093 | """Call an alias given its name and the rest of the line. |
|
2146 | kw.setdefault('quiet',1) | |
2094 |
|
2147 | kw.setdefault('exit_ignore',0) | ||
2095 | This is only used to provide backwards compatibility for users of |
|
|||
2096 | ipalias(), use of which is not recommended for anymore.""" |
|
|||
2097 |
|
2148 | |||
2098 | # Now call the macro, evaluating in the user's namespace |
|
2149 | first = xfile.readline() | |
2099 | cmd = self.transform_alias(alias, rest) |
|
2150 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
|
2151 | xfile.close() | |||
|
2152 | # line by line execution | |||
|
2153 | if first.startswith(loghead) or kw['islog']: | |||
|
2154 | print 'Loading log file <%s> one line at a time...' % fname | |||
|
2155 | if kw['quiet']: | |||
|
2156 | stdout_save = sys.stdout | |||
|
2157 | sys.stdout = StringIO.StringIO() | |||
2100 | try: |
|
2158 | try: | |
2101 | self.system(cmd) |
|
2159 | globs,locs = where[0:2] | |
2102 | except: |
|
2160 | except: | |
2103 | self.showtraceback() |
|
2161 | try: | |
2104 |
|
2162 | globs = locs = where[0] | ||
2105 | def indent_current_str(self): |
|
2163 | except: | |
2106 | """return the current level of indentation as a string""" |
|
2164 | globs = locs = globals() | |
2107 | return self.indent_current_nsp * ' ' |
|
2165 | badblocks = [] | |
2108 |
|
||||
2109 | def autoindent_update(self,line): |
|
|||
2110 | """Keep track of the indent level.""" |
|
|||
2111 |
|
||||
2112 | #debugx('line') |
|
|||
2113 | #debugx('self.indent_current_nsp') |
|
|||
2114 | if self.autoindent: |
|
|||
2115 | if line: |
|
|||
2116 | inisp = num_ini_spaces(line) |
|
|||
2117 | if inisp < self.indent_current_nsp: |
|
|||
2118 | self.indent_current_nsp = inisp |
|
|||
2119 |
|
2166 | |||
2120 | if line[-1] == ':': |
|
2167 | # we also need to identify indented blocks of code when replaying | |
2121 | self.indent_current_nsp += 4 |
|
2168 | # logs and put them together before passing them to an exec | |
2122 | elif dedent_re.match(line): |
|
2169 | # statement. This takes a bit of regexp and look-ahead work in the | |
2123 | self.indent_current_nsp -= 4 |
|
2170 | # file. It's easiest if we swallow the whole thing in memory | |
|
2171 | # first, and manually walk through the lines list moving the | |||
|
2172 | # counter ourselves. | |||
|
2173 | indent_re = re.compile('\s+\S') | |||
|
2174 | xfile = open(fname) | |||
|
2175 | filelines = xfile.readlines() | |||
|
2176 | xfile.close() | |||
|
2177 | nlines = len(filelines) | |||
|
2178 | lnum = 0 | |||
|
2179 | while lnum < nlines: | |||
|
2180 | line = filelines[lnum] | |||
|
2181 | lnum += 1 | |||
|
2182 | # don't re-insert logger status info into cache | |||
|
2183 | if line.startswith('#log#'): | |||
|
2184 | continue | |||
2124 | else: |
|
2185 | else: | |
2125 | self.indent_current_nsp = 0 |
|
2186 | # build a block of code (maybe a single line) for execution | |
2126 |
|
2187 | block = line | ||
2127 | def push(self, variables, interactive=True): |
|
2188 | try: | |
2128 | """Inject a group of variables into the IPython user namespace. |
|
2189 | next = filelines[lnum] # lnum has already incremented | |
2129 |
|
2190 | except: | ||
2130 | Parameters |
|
2191 | next = None | |
2131 | ---------- |
|
2192 | while next and indent_re.match(next): | |
2132 | variables : dict, str or list/tuple of str |
|
2193 | block += next | |
2133 | The variables to inject into the user's namespace. If a dict, |
|
2194 | lnum += 1 | |
2134 | a simple update is done. If a str, the string is assumed to |
|
2195 | try: | |
2135 | have variable names separated by spaces. A list/tuple of str |
|
2196 | next = filelines[lnum] | |
2136 | can also be used to give the variable names. If just the variable |
|
2197 | except: | |
2137 | names are give (list/tuple/str) then the variable values looked |
|
2198 | next = None | |
2138 | up in the callers frame. |
|
2199 | # now execute the block of one or more lines | |
2139 | interactive : bool |
|
2200 | try: | |
2140 | If True (default), the variables will be listed with the ``who`` |
|
2201 | exec block in globs,locs | |
2141 | magic. |
|
2202 | except SystemExit: | |
2142 | """ |
|
2203 | pass | |
2143 | vdict = None |
|
2204 | except: | |
|
2205 | badblocks.append(block.rstrip()) | |||
|
2206 | if kw['quiet']: # restore stdout | |||
|
2207 | sys.stdout.close() | |||
|
2208 | sys.stdout = stdout_save | |||
|
2209 | print 'Finished replaying log file <%s>' % fname | |||
|
2210 | if badblocks: | |||
|
2211 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |||
|
2212 | '<%s> reported errors:' % fname) | |||
2144 |
|
2213 | |||
2145 | # We need a dict of name/value pairs to do namespace updates. |
|
2214 | for badline in badblocks: | |
2146 | if isinstance(variables, dict): |
|
2215 | print >> sys.stderr, badline | |
2147 | vdict = variables |
|
2216 | else: # regular file execution | |
2148 | elif isinstance(variables, (basestring, list, tuple)): |
|
|||
2149 | if isinstance(variables, basestring): |
|
|||
2150 | vlist = variables.split() |
|
|||
2151 | else: |
|
|||
2152 | vlist = variables |
|
|||
2153 | vdict = {} |
|
|||
2154 | cf = sys._getframe(1) |
|
|||
2155 | for name in vlist: |
|
|||
2156 |
|
|
2217 | try: | |
2157 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
2218 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
|
2219 | # Work around a bug in Python for Windows. The bug was | |||
|
2220 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |||
|
2221 | # SVN Python as of March/07. For details, see: | |||
|
2222 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |||
|
2223 | try: | |||
|
2224 | globs,locs = where[0:2] | |||
2158 | except: |
|
2225 | except: | |
2159 | print ('Could not get variable %s from %s' % |
|
2226 | try: | |
2160 | (name,cf.f_code.co_name)) |
|
2227 | globs = locs = where[0] | |
|
2228 | except: | |||
|
2229 | globs = locs = globals() | |||
|
2230 | exec file(fname) in globs,locs | |||
2161 | else: |
|
2231 | else: | |
2162 | raise ValueError('variables must be a dict/str/list/tuple') |
|
2232 | execfile(fname,*where) | |
2163 |
|
2233 | except SyntaxError: | ||
2164 | # Propagate variables to user namespace |
|
2234 | self.showsyntaxerror() | |
2165 | self.user_ns.update(vdict) |
|
2235 | warn('Failure executing file: <%s>' % fname) | |
|
2236 | except SystemExit,status: | |||
|
2237 | # Code that correctly sets the exit status flag to success (0) | |||
|
2238 | # shouldn't be bothered with a traceback. Note that a plain | |||
|
2239 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |||
|
2240 | # will still get a traceback. Note that the structure of the | |||
|
2241 | # SystemExit exception changed between Python 2.4 and 2.5, so | |||
|
2242 | # the checks must be done in a version-dependent way. | |||
|
2243 | show = False | |||
2166 |
|
2244 | |||
2167 | # And configure interactive visibility |
|
2245 | if sys.version_info[:2] > (2,5): | |
2168 | config_ns = self.user_config_ns |
|
2246 | if status.message!=0 and not kw['exit_ignore']: | |
2169 | if interactive: |
|
2247 | show = True | |
2170 | for name, val in vdict.iteritems(): |
|
|||
2171 | config_ns.pop(name, None) |
|
|||
2172 | else: |
|
2248 | else: | |
2173 | for name,val in vdict.iteritems(): |
|
2249 | if status.code and not kw['exit_ignore']: | |
2174 | config_ns[name] = val |
|
2250 | show = True | |
|
2251 | if show: | |||
|
2252 | self.showtraceback() | |||
|
2253 | warn('Failure executing file: <%s>' % fname) | |||
|
2254 | except: | |||
|
2255 | self.showtraceback() | |||
|
2256 | warn('Failure executing file: <%s>' % fname) | |||
|
2257 | ||||
|
2258 | syspath_cleanup() | |||
2175 |
|
2259 | |||
2176 | def cleanup_ipy_script(self, script): |
|
2260 | def cleanup_ipy_script(self, script): | |
2177 | """Make a script safe for self.runlines() |
|
2261 | """Make a script safe for self.runlines() | |
2178 |
|
2262 | |||
2179 | Notes |
|
2263 | Notes | |
2180 | ----- |
|
2264 | ----- | |
2181 | This was copied over from the old ipapi and probably can be done |
|
2265 | This was copied over from the old ipapi and probably can be done | |
2182 | away with once we move to block based interpreter. |
|
2266 | away with once we move to block based interpreter. | |
2183 |
|
2267 | |||
2184 | - Removes empty lines Suffixes all indented blocks that end with |
|
2268 | - Removes empty lines Suffixes all indented blocks that end with | |
2185 | - unindented lines with empty lines |
|
2269 | - unindented lines with empty lines | |
2186 | """ |
|
2270 | """ | |
2187 |
|
2271 | |||
2188 | res = [] |
|
2272 | res = [] | |
2189 | lines = script.splitlines() |
|
2273 | lines = script.splitlines() | |
2190 |
|
2274 | |||
2191 | level = 0 |
|
2275 | level = 0 | |
2192 | for l in lines: |
|
2276 | for l in lines: | |
2193 | lstripped = l.lstrip() |
|
2277 | lstripped = l.lstrip() | |
2194 | stripped = l.strip() |
|
2278 | stripped = l.strip() | |
2195 | if not stripped: |
|
2279 | if not stripped: | |
2196 | continue |
|
2280 | continue | |
2197 | newlevel = len(l) - len(lstripped) |
|
2281 | newlevel = len(l) - len(lstripped) | |
2198 | def is_secondary_block_start(s): |
|
2282 | def is_secondary_block_start(s): | |
2199 | if not s.endswith(':'): |
|
2283 | if not s.endswith(':'): | |
2200 | return False |
|
2284 | return False | |
2201 | if (s.startswith('elif') or |
|
2285 | if (s.startswith('elif') or | |
2202 | s.startswith('else') or |
|
2286 | s.startswith('else') or | |
2203 | s.startswith('except') or |
|
2287 | s.startswith('except') or | |
2204 | s.startswith('finally')): |
|
2288 | s.startswith('finally')): | |
2205 | return True |
|
2289 | return True | |
2206 |
|
2290 | |||
2207 | if level > 0 and newlevel == 0 and \ |
|
2291 | if level > 0 and newlevel == 0 and \ | |
2208 | not is_secondary_block_start(stripped): |
|
2292 | not is_secondary_block_start(stripped): | |
2209 | # add empty line |
|
2293 | # add empty line | |
2210 | res.append('') |
|
2294 | res.append('') | |
2211 |
|
2295 | |||
2212 | res.append(l) |
|
2296 | res.append(l) | |
2213 | level = newlevel |
|
2297 | level = newlevel | |
2214 | return '\n'.join(res) + '\n' |
|
2298 | return '\n'.join(res) + '\n' | |
2215 |
|
2299 | |||
2216 | def runlines(self, lines, clean=False): |
|
2300 | def runlines(self, lines, clean=False): | |
2217 | """Run a string of one or more lines of source. |
|
2301 | """Run a string of one or more lines of source. | |
2218 |
|
2302 | |||
2219 | This method is capable of running a string containing multiple source |
|
2303 | This method is capable of running a string containing multiple source | |
2220 | lines, as if they had been entered at the IPython prompt. Since it |
|
2304 | lines, as if they had been entered at the IPython prompt. Since it | |
2221 | exposes IPython's processing machinery, the given strings can contain |
|
2305 | exposes IPython's processing machinery, the given strings can contain | |
2222 | magic calls (%magic), special shell access (!cmd), etc. |
|
2306 | magic calls (%magic), special shell access (!cmd), etc. | |
2223 | """ |
|
2307 | """ | |
2224 |
|
2308 | |||
2225 | if isinstance(lines, (list, tuple)): |
|
2309 | if isinstance(lines, (list, tuple)): | |
2226 | lines = '\n'.join(lines) |
|
2310 | lines = '\n'.join(lines) | |
2227 |
|
2311 | |||
2228 | if clean: |
|
2312 | if clean: | |
2229 | lines = self.cleanup_ipy_script(lines) |
|
2313 | lines = self.cleanup_ipy_script(lines) | |
2230 |
|
2314 | |||
2231 | # We must start with a clean buffer, in case this is run from an |
|
2315 | # We must start with a clean buffer, in case this is run from an | |
2232 | # interactive IPython session (via a magic, for example). |
|
2316 | # interactive IPython session (via a magic, for example). | |
2233 | self.resetbuffer() |
|
2317 | self.resetbuffer() | |
2234 | lines = lines.splitlines() |
|
2318 | lines = lines.splitlines() | |
2235 | more = 0 |
|
2319 | more = 0 | |
2236 |
|
2320 | |||
2237 | with nested(self.builtin_trap, self.display_trap): |
|
2321 | with nested(self.builtin_trap, self.display_trap): | |
2238 | for line in lines: |
|
2322 | for line in lines: | |
2239 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2323 | # skip blank lines so we don't mess up the prompt counter, but do | |
2240 | # NOT skip even a blank line if we are in a code block (more is |
|
2324 | # NOT skip even a blank line if we are in a code block (more is | |
2241 | # true) |
|
2325 | # true) | |
2242 |
|
2326 | |||
2243 | if line or more: |
|
2327 | if line or more: | |
2244 | # push to raw history, so hist line numbers stay in sync |
|
2328 | # push to raw history, so hist line numbers stay in sync | |
2245 | self.input_hist_raw.append("# " + line + "\n") |
|
2329 | self.input_hist_raw.append("# " + line + "\n") | |
2246 | more = self.push_line(self.prefilter(line,more)) |
|
2330 | more = self.push_line(self.prefilter(line,more)) | |
2247 | # IPython's runsource returns None if there was an error |
|
2331 | # IPython's runsource returns None if there was an error | |
2248 | # compiling the code. This allows us to stop processing right |
|
2332 | # compiling the code. This allows us to stop processing right | |
2249 | # away, so the user gets the error message at the right place. |
|
2333 | # away, so the user gets the error message at the right place. | |
2250 | if more is None: |
|
2334 | if more is None: | |
2251 | break |
|
2335 | break | |
2252 | else: |
|
2336 | else: | |
2253 | self.input_hist_raw.append("\n") |
|
2337 | self.input_hist_raw.append("\n") | |
2254 | # final newline in case the input didn't have it, so that the code |
|
2338 | # final newline in case the input didn't have it, so that the code | |
2255 | # actually does get executed |
|
2339 | # actually does get executed | |
2256 | if more: |
|
2340 | if more: | |
2257 | self.push_line('\n') |
|
2341 | self.push_line('\n') | |
2258 |
|
2342 | |||
2259 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2343 | def runsource(self, source, filename='<input>', symbol='single'): | |
2260 | """Compile and run some source in the interpreter. |
|
2344 | """Compile and run some source in the interpreter. | |
2261 |
|
2345 | |||
2262 | Arguments are as for compile_command(). |
|
2346 | Arguments are as for compile_command(). | |
2263 |
|
2347 | |||
2264 | One several things can happen: |
|
2348 | One several things can happen: | |
2265 |
|
2349 | |||
2266 | 1) The input is incorrect; compile_command() raised an |
|
2350 | 1) The input is incorrect; compile_command() raised an | |
2267 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2351 | exception (SyntaxError or OverflowError). A syntax traceback | |
2268 | will be printed by calling the showsyntaxerror() method. |
|
2352 | will be printed by calling the showsyntaxerror() method. | |
2269 |
|
2353 | |||
2270 | 2) The input is incomplete, and more input is required; |
|
2354 | 2) The input is incomplete, and more input is required; | |
2271 | compile_command() returned None. Nothing happens. |
|
2355 | compile_command() returned None. Nothing happens. | |
2272 |
|
2356 | |||
2273 | 3) The input is complete; compile_command() returned a code |
|
2357 | 3) The input is complete; compile_command() returned a code | |
2274 | object. The code is executed by calling self.runcode() (which |
|
2358 | object. The code is executed by calling self.runcode() (which | |
2275 | also handles run-time exceptions, except for SystemExit). |
|
2359 | also handles run-time exceptions, except for SystemExit). | |
2276 |
|
2360 | |||
2277 | The return value is: |
|
2361 | The return value is: | |
2278 |
|
2362 | |||
2279 | - True in case 2 |
|
2363 | - True in case 2 | |
2280 |
|
2364 | |||
2281 | - False in the other cases, unless an exception is raised, where |
|
2365 | - False in the other cases, unless an exception is raised, where | |
2282 | None is returned instead. This can be used by external callers to |
|
2366 | None is returned instead. This can be used by external callers to | |
2283 | know whether to continue feeding input or not. |
|
2367 | know whether to continue feeding input or not. | |
2284 |
|
2368 | |||
2285 | The return value can be used to decide whether to use sys.ps1 or |
|
2369 | The return value can be used to decide whether to use sys.ps1 or | |
2286 | sys.ps2 to prompt the next line.""" |
|
2370 | sys.ps2 to prompt the next line.""" | |
2287 |
|
2371 | |||
2288 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2372 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2289 | # this allows execution of indented pasted code. It is tempting |
|
2373 | # this allows execution of indented pasted code. It is tempting | |
2290 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2374 | # to add '\n' at the end of source to run commands like ' a=1' | |
2291 | # directly, but this fails for more complicated scenarios |
|
2375 | # directly, but this fails for more complicated scenarios | |
2292 | source=source.encode(self.stdin_encoding) |
|
2376 | source=source.encode(self.stdin_encoding) | |
2293 | if source[:1] in [' ', '\t']: |
|
2377 | if source[:1] in [' ', '\t']: | |
2294 | source = 'if 1:\n%s' % source |
|
2378 | source = 'if 1:\n%s' % source | |
2295 |
|
2379 | |||
2296 | try: |
|
2380 | try: | |
2297 | code = self.compile(source,filename,symbol) |
|
2381 | code = self.compile(source,filename,symbol) | |
2298 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2382 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2299 | # Case 1 |
|
2383 | # Case 1 | |
2300 | self.showsyntaxerror(filename) |
|
2384 | self.showsyntaxerror(filename) | |
2301 | return None |
|
2385 | return None | |
2302 |
|
2386 | |||
2303 | if code is None: |
|
2387 | if code is None: | |
2304 | # Case 2 |
|
2388 | # Case 2 | |
2305 | return True |
|
2389 | return True | |
2306 |
|
2390 | |||
2307 | # Case 3 |
|
2391 | # Case 3 | |
2308 | # We store the code object so that threaded shells and |
|
2392 | # We store the code object so that threaded shells and | |
2309 | # custom exception handlers can access all this info if needed. |
|
2393 | # custom exception handlers can access all this info if needed. | |
2310 | # The source corresponding to this can be obtained from the |
|
2394 | # The source corresponding to this can be obtained from the | |
2311 | # buffer attribute as '\n'.join(self.buffer). |
|
2395 | # buffer attribute as '\n'.join(self.buffer). | |
2312 | self.code_to_run = code |
|
2396 | self.code_to_run = code | |
2313 | # now actually execute the code object |
|
2397 | # now actually execute the code object | |
2314 | if self.runcode(code) == 0: |
|
2398 | if self.runcode(code) == 0: | |
2315 | return False |
|
2399 | return False | |
2316 | else: |
|
2400 | else: | |
2317 | return None |
|
2401 | return None | |
2318 |
|
2402 | |||
2319 | def runcode(self,code_obj): |
|
2403 | def runcode(self,code_obj): | |
2320 | """Execute a code object. |
|
2404 | """Execute a code object. | |
2321 |
|
2405 | |||
2322 | When an exception occurs, self.showtraceback() is called to display a |
|
2406 | When an exception occurs, self.showtraceback() is called to display a | |
2323 | traceback. |
|
2407 | traceback. | |
2324 |
|
2408 | |||
2325 | Return value: a flag indicating whether the code to be run completed |
|
2409 | Return value: a flag indicating whether the code to be run completed | |
2326 | successfully: |
|
2410 | successfully: | |
2327 |
|
2411 | |||
2328 | - 0: successful execution. |
|
2412 | - 0: successful execution. | |
2329 | - 1: an error occurred. |
|
2413 | - 1: an error occurred. | |
2330 | """ |
|
2414 | """ | |
2331 |
|
2415 | |||
2332 | # Set our own excepthook in case the user code tries to call it |
|
2416 | # Set our own excepthook in case the user code tries to call it | |
2333 | # directly, so that the IPython crash handler doesn't get triggered |
|
2417 | # directly, so that the IPython crash handler doesn't get triggered | |
2334 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2418 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2335 |
|
2419 | |||
2336 | # we save the original sys.excepthook in the instance, in case config |
|
2420 | # we save the original sys.excepthook in the instance, in case config | |
2337 | # code (such as magics) needs access to it. |
|
2421 | # code (such as magics) needs access to it. | |
2338 | self.sys_excepthook = old_excepthook |
|
2422 | self.sys_excepthook = old_excepthook | |
2339 | outflag = 1 # happens in more places, so it's easier as default |
|
2423 | outflag = 1 # happens in more places, so it's easier as default | |
2340 | try: |
|
2424 | try: | |
2341 | try: |
|
2425 | try: | |
2342 | self.hooks.pre_runcode_hook() |
|
2426 | self.hooks.pre_runcode_hook() | |
2343 | exec code_obj in self.user_global_ns, self.user_ns |
|
2427 | exec code_obj in self.user_global_ns, self.user_ns | |
2344 | finally: |
|
2428 | finally: | |
2345 | # Reset our crash handler in place |
|
2429 | # Reset our crash handler in place | |
2346 | sys.excepthook = old_excepthook |
|
2430 | sys.excepthook = old_excepthook | |
2347 | except SystemExit: |
|
2431 | except SystemExit: | |
2348 | self.resetbuffer() |
|
2432 | self.resetbuffer() | |
2349 | self.showtraceback() |
|
2433 | self.showtraceback() | |
2350 | warn("Type %exit or %quit to exit IPython " |
|
2434 | warn("Type %exit or %quit to exit IPython " | |
2351 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2435 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2352 | except self.custom_exceptions: |
|
2436 | except self.custom_exceptions: | |
2353 | etype,value,tb = sys.exc_info() |
|
2437 | etype,value,tb = sys.exc_info() | |
2354 | self.CustomTB(etype,value,tb) |
|
2438 | self.CustomTB(etype,value,tb) | |
2355 | except: |
|
2439 | except: | |
2356 | self.showtraceback() |
|
2440 | self.showtraceback() | |
2357 | else: |
|
2441 | else: | |
2358 | outflag = 0 |
|
2442 | outflag = 0 | |
2359 | if softspace(sys.stdout, 0): |
|
2443 | if softspace(sys.stdout, 0): | |
2360 |
|
2444 | |||
2361 | # Flush out code object which has been run (and source) |
|
2445 | # Flush out code object which has been run (and source) | |
2362 | self.code_to_run = None |
|
2446 | self.code_to_run = None | |
2363 | return outflag |
|
2447 | return outflag | |
2364 |
|
2448 | |||
2365 | def push_line(self, line): |
|
2449 | def push_line(self, line): | |
2366 | """Push a line to the interpreter. |
|
2450 | """Push a line to the interpreter. | |
2367 |
|
2451 | |||
2368 | The line should not have a trailing newline; it may have |
|
2452 | The line should not have a trailing newline; it may have | |
2369 | internal newlines. The line is appended to a buffer and the |
|
2453 | internal newlines. The line is appended to a buffer and the | |
2370 | interpreter's runsource() method is called with the |
|
2454 | interpreter's runsource() method is called with the | |
2371 | concatenated contents of the buffer as source. If this |
|
2455 | concatenated contents of the buffer as source. If this | |
2372 | indicates that the command was executed or invalid, the buffer |
|
2456 | indicates that the command was executed or invalid, the buffer | |
2373 | is reset; otherwise, the command is incomplete, and the buffer |
|
2457 | is reset; otherwise, the command is incomplete, and the buffer | |
2374 | is left as it was after the line was appended. The return |
|
2458 | is left as it was after the line was appended. The return | |
2375 | value is 1 if more input is required, 0 if the line was dealt |
|
2459 | value is 1 if more input is required, 0 if the line was dealt | |
2376 | with in some way (this is the same as runsource()). |
|
2460 | with in some way (this is the same as runsource()). | |
2377 | """ |
|
2461 | """ | |
2378 |
|
2462 | |||
2379 | # autoindent management should be done here, and not in the |
|
2463 | # autoindent management should be done here, and not in the | |
2380 | # interactive loop, since that one is only seen by keyboard input. We |
|
2464 | # interactive loop, since that one is only seen by keyboard input. We | |
2381 | # need this done correctly even for code run via runlines (which uses |
|
2465 | # need this done correctly even for code run via runlines (which uses | |
2382 | # push). |
|
2466 | # push). | |
2383 |
|
2467 | |||
2384 | #print 'push line: <%s>' % line # dbg |
|
2468 | #print 'push line: <%s>' % line # dbg | |
2385 | for subline in line.splitlines(): |
|
2469 | for subline in line.splitlines(): | |
2386 | self.autoindent_update(subline) |
|
2470 | self._autoindent_update(subline) | |
2387 | self.buffer.append(line) |
|
2471 | self.buffer.append(line) | |
2388 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2472 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2389 | if not more: |
|
2473 | if not more: | |
2390 | self.resetbuffer() |
|
2474 | self.resetbuffer() | |
2391 | return more |
|
2475 | return more | |
2392 |
|
2476 | |||
|
2477 | def _autoindent_update(self,line): | |||
|
2478 | """Keep track of the indent level.""" | |||
|
2479 | ||||
|
2480 | #debugx('line') | |||
|
2481 | #debugx('self.indent_current_nsp') | |||
|
2482 | if self.autoindent: | |||
|
2483 | if line: | |||
|
2484 | inisp = num_ini_spaces(line) | |||
|
2485 | if inisp < self.indent_current_nsp: | |||
|
2486 | self.indent_current_nsp = inisp | |||
|
2487 | ||||
|
2488 | if line[-1] == ':': | |||
|
2489 | self.indent_current_nsp += 4 | |||
|
2490 | elif dedent_re.match(line): | |||
|
2491 | self.indent_current_nsp -= 4 | |||
|
2492 | else: | |||
|
2493 | self.indent_current_nsp = 0 | |||
|
2494 | ||||
2393 | def split_user_input(self, line): |
|
2495 | def split_user_input(self, line): | |
2394 | # This is really a hold-over to support ipapi and some extensions |
|
2496 | # This is really a hold-over to support ipapi and some extensions | |
2395 | return prefilter.splitUserInput(line) |
|
2497 | return prefilter.splitUserInput(line) | |
2396 |
|
2498 | |||
2397 | def resetbuffer(self): |
|
2499 | def resetbuffer(self): | |
2398 | """Reset the input buffer.""" |
|
2500 | """Reset the input buffer.""" | |
2399 | self.buffer[:] = [] |
|
2501 | self.buffer[:] = [] | |
2400 |
|
2502 | |||
2401 | def raw_input(self,prompt='',continue_prompt=False): |
|
2503 | def raw_input(self,prompt='',continue_prompt=False): | |
2402 | """Write a prompt and read a line. |
|
2504 | """Write a prompt and read a line. | |
2403 |
|
2505 | |||
2404 | The returned line does not include the trailing newline. |
|
2506 | The returned line does not include the trailing newline. | |
2405 | When the user enters the EOF key sequence, EOFError is raised. |
|
2507 | When the user enters the EOF key sequence, EOFError is raised. | |
2406 |
|
2508 | |||
2407 | Optional inputs: |
|
2509 | Optional inputs: | |
2408 |
|
2510 | |||
2409 | - prompt(''): a string to be printed to prompt the user. |
|
2511 | - prompt(''): a string to be printed to prompt the user. | |
2410 |
|
2512 | |||
2411 | - continue_prompt(False): whether this line is the first one or a |
|
2513 | - continue_prompt(False): whether this line is the first one or a | |
2412 | continuation in a sequence of inputs. |
|
2514 | continuation in a sequence of inputs. | |
2413 | """ |
|
2515 | """ | |
2414 |
|
2516 | |||
2415 | # Code run by the user may have modified the readline completer state. |
|
2517 | # Code run by the user may have modified the readline completer state. | |
2416 | # We must ensure that our completer is back in place. |
|
2518 | # We must ensure that our completer is back in place. | |
2417 | if self.has_readline: |
|
2519 | if self.has_readline: | |
2418 | self.set_completer() |
|
2520 | self.set_completer() | |
2419 |
|
2521 | |||
2420 | try: |
|
2522 | try: | |
2421 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2523 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2422 | except ValueError: |
|
2524 | except ValueError: | |
2423 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2525 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2424 | " or sys.stdout.close()!\nExiting IPython!") |
|
2526 | " or sys.stdout.close()!\nExiting IPython!") | |
2425 | self.ask_exit() |
|
2527 | self.ask_exit() | |
2426 | return "" |
|
2528 | return "" | |
2427 |
|
2529 | |||
2428 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2530 | # Try to be reasonably smart about not re-indenting pasted input more | |
2429 | # than necessary. We do this by trimming out the auto-indent initial |
|
2531 | # than necessary. We do this by trimming out the auto-indent initial | |
2430 | # spaces, if the user's actual input started itself with whitespace. |
|
2532 | # spaces, if the user's actual input started itself with whitespace. | |
2431 | #debugx('self.buffer[-1]') |
|
2533 | #debugx('self.buffer[-1]') | |
|
2534 | ||||
|
2535 | if self.autoindent: | |||
|
2536 | if num_ini_spaces(line) > self.indent_current_nsp: | |||
|
2537 | line = line[self.indent_current_nsp:] | |||
|
2538 | self.indent_current_nsp = 0 | |||
|
2539 | ||||
|
2540 | # store the unfiltered input before the user has any chance to modify | |||
|
2541 | # it. | |||
|
2542 | if line.strip(): | |||
|
2543 | if continue_prompt: | |||
|
2544 | self.input_hist_raw[-1] += '%s\n' % line | |||
|
2545 | if self.has_readline: # and some config option is set? | |||
|
2546 | try: | |||
|
2547 | histlen = self.readline.get_current_history_length() | |||
|
2548 | if histlen > 1: | |||
|
2549 | newhist = self.input_hist_raw[-1].rstrip() | |||
|
2550 | self.readline.remove_history_item(histlen-1) | |||
|
2551 | self.readline.replace_history_item(histlen-2, | |||
|
2552 | newhist.encode(self.stdin_encoding)) | |||
|
2553 | except AttributeError: | |||
|
2554 | pass # re{move,place}_history_item are new in 2.4. | |||
|
2555 | else: | |||
|
2556 | self.input_hist_raw.append('%s\n' % line) | |||
|
2557 | # only entries starting at first column go to shadow history | |||
|
2558 | if line.lstrip() == line: | |||
|
2559 | self.shadowhist.add(line.strip()) | |||
|
2560 | elif not continue_prompt: | |||
|
2561 | self.input_hist_raw.append('\n') | |||
|
2562 | try: | |||
|
2563 | lineout = self.prefilter(line,continue_prompt) | |||
|
2564 | except: | |||
|
2565 | # blanket except, in case a user-defined prefilter crashes, so it | |||
|
2566 | # can't take all of ipython with it. | |||
|
2567 | self.showtraceback() | |||
|
2568 | return '' | |||
|
2569 | else: | |||
|
2570 | return lineout | |||
|
2571 | ||||
|
2572 | # def init_exec_commands(self): | |||
|
2573 | # for cmd in self.config.EXECUTE: | |||
|
2574 | # print "execute:", cmd | |||
|
2575 | # self.api.runlines(cmd) | |||
|
2576 | # | |||
|
2577 | # batchrun = False | |||
|
2578 | # if self.config.has_key('EXECFILE'): | |||
|
2579 | # for batchfile in [path(arg) for arg in self.config.EXECFILE | |||
|
2580 | # if arg.lower().endswith('.ipy')]: | |||
|
2581 | # if not batchfile.isfile(): | |||
|
2582 | # print "No such batch file:", batchfile | |||
|
2583 | # continue | |||
|
2584 | # self.api.runlines(batchfile.text()) | |||
|
2585 | # batchrun = True | |||
|
2586 | # # without -i option, exit after running the batch file | |||
|
2587 | # if batchrun and not self.interactive: | |||
|
2588 | # self.ask_exit() | |||
|
2589 | ||||
|
2590 | # def load(self, mod): | |||
|
2591 | # """ Load an extension. | |||
|
2592 | # | |||
|
2593 | # Some modules should (or must) be 'load()':ed, rather than just imported. | |||
|
2594 | # | |||
|
2595 | # Loading will do: | |||
|
2596 | # | |||
|
2597 | # - run init_ipython(ip) | |||
|
2598 | # - run ipython_firstrun(ip) | |||
|
2599 | # """ | |||
|
2600 | # | |||
|
2601 | # if mod in self.extensions: | |||
|
2602 | # # just to make sure we don't init it twice | |||
|
2603 | # # note that if you 'load' a module that has already been | |||
|
2604 | # # imported, init_ipython gets run anyway | |||
|
2605 | # | |||
|
2606 | # return self.extensions[mod] | |||
|
2607 | # __import__(mod) | |||
|
2608 | # m = sys.modules[mod] | |||
|
2609 | # if hasattr(m,'init_ipython'): | |||
|
2610 | # m.init_ipython(self) | |||
|
2611 | # | |||
|
2612 | # if hasattr(m,'ipython_firstrun'): | |||
|
2613 | # already_loaded = self.db.get('firstrun_done', set()) | |||
|
2614 | # if mod not in already_loaded: | |||
|
2615 | # m.ipython_firstrun(self) | |||
|
2616 | # already_loaded.add(mod) | |||
|
2617 | # self.db['firstrun_done'] = already_loaded | |||
|
2618 | # | |||
|
2619 | # self.extensions[mod] = m | |||
|
2620 | # return m | |||
|
2621 | ||||
|
2622 | #------------------------------------------------------------------------- | |||
|
2623 | # Things related to the prefilter | |||
|
2624 | #------------------------------------------------------------------------- | |||
2432 |
|
2625 | |||
2433 | if self.autoindent: |
|
2626 | def init_handlers(self): | |
2434 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2627 | # escapes for automatic behavior on the command line | |
2435 | line = line[self.indent_current_nsp:] |
|
2628 | self.ESC_SHELL = '!' | |
2436 | self.indent_current_nsp = 0 |
|
2629 | self.ESC_SH_CAP = '!!' | |
|
2630 | self.ESC_HELP = '?' | |||
|
2631 | self.ESC_MAGIC = '%' | |||
|
2632 | self.ESC_QUOTE = ',' | |||
|
2633 | self.ESC_QUOTE2 = ';' | |||
|
2634 | self.ESC_PAREN = '/' | |||
2437 |
|
2635 | |||
2438 | # store the unfiltered input before the user has any chance to modify |
|
2636 | # And their associated handlers | |
2439 | # it. |
|
2637 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
2440 | if line.strip(): |
|
2638 | self.ESC_QUOTE : self.handle_auto, | |
2441 | if continue_prompt: |
|
2639 | self.ESC_QUOTE2 : self.handle_auto, | |
2442 | self.input_hist_raw[-1] += '%s\n' % line |
|
2640 | self.ESC_MAGIC : self.handle_magic, | |
2443 | if self.has_readline: # and some config option is set? |
|
2641 | self.ESC_HELP : self.handle_help, | |
2444 | try: |
|
2642 | self.ESC_SHELL : self.handle_shell_escape, | |
2445 | histlen = self.readline.get_current_history_length() |
|
2643 | self.ESC_SH_CAP : self.handle_shell_escape, | |
2446 |
|
|
2644 | } | |
2447 | newhist = self.input_hist_raw[-1].rstrip() |
|
|||
2448 | self.readline.remove_history_item(histlen-1) |
|
|||
2449 | self.readline.replace_history_item(histlen-2, |
|
|||
2450 | newhist.encode(self.stdin_encoding)) |
|
|||
2451 | except AttributeError: |
|
|||
2452 | pass # re{move,place}_history_item are new in 2.4. |
|
|||
2453 | else: |
|
|||
2454 | self.input_hist_raw.append('%s\n' % line) |
|
|||
2455 | # only entries starting at first column go to shadow history |
|
|||
2456 | if line.lstrip() == line: |
|
|||
2457 | self.shadowhist.add(line.strip()) |
|
|||
2458 | elif not continue_prompt: |
|
|||
2459 | self.input_hist_raw.append('\n') |
|
|||
2460 | try: |
|
|||
2461 | lineout = self.prefilter(line,continue_prompt) |
|
|||
2462 | except: |
|
|||
2463 | # blanket except, in case a user-defined prefilter crashes, so it |
|
|||
2464 | # can't take all of ipython with it. |
|
|||
2465 | self.showtraceback() |
|
|||
2466 | return '' |
|
|||
2467 | else: |
|
|||
2468 | return lineout |
|
|||
2469 |
|
2645 | |||
2470 | def _prefilter(self, line, continue_prompt): |
|
2646 | def _prefilter(self, line, continue_prompt): | |
2471 | """Calls different preprocessors, depending on the form of line.""" |
|
2647 | """Calls different preprocessors, depending on the form of line.""" | |
2472 |
|
2648 | |||
2473 | # All handlers *must* return a value, even if it's blank (''). |
|
2649 | # All handlers *must* return a value, even if it's blank (''). | |
2474 |
|
2650 | |||
2475 | # Lines are NOT logged here. Handlers should process the line as |
|
2651 | # Lines are NOT logged here. Handlers should process the line as | |
2476 | # needed, update the cache AND log it (so that the input cache array |
|
2652 | # needed, update the cache AND log it (so that the input cache array | |
2477 | # stays synced). |
|
2653 | # stays synced). | |
2478 |
|
2654 | |||
2479 | #..................................................................... |
|
2655 | #..................................................................... | |
2480 | # Code begins |
|
2656 | # Code begins | |
2481 |
|
2657 | |||
2482 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2658 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2483 |
|
2659 | |||
2484 | # save the line away in case we crash, so the post-mortem handler can |
|
2660 | # save the line away in case we crash, so the post-mortem handler can | |
2485 | # record it |
|
2661 | # record it | |
2486 | self._last_input_line = line |
|
2662 | self._last_input_line = line | |
2487 |
|
2663 | |||
2488 | #print '***line: <%s>' % line # dbg |
|
2664 | #print '***line: <%s>' % line # dbg | |
2489 |
|
2665 | |||
2490 | if not line: |
|
2666 | if not line: | |
2491 | # Return immediately on purely empty lines, so that if the user |
|
2667 | # Return immediately on purely empty lines, so that if the user | |
2492 | # previously typed some whitespace that started a continuation |
|
2668 | # previously typed some whitespace that started a continuation | |
2493 | # prompt, he can break out of that loop with just an empty line. |
|
2669 | # prompt, he can break out of that loop with just an empty line. | |
2494 | # This is how the default python prompt works. |
|
2670 | # This is how the default python prompt works. | |
2495 |
|
2671 | |||
2496 | # Only return if the accumulated input buffer was just whitespace! |
|
2672 | # Only return if the accumulated input buffer was just whitespace! | |
2497 | if ''.join(self.buffer).isspace(): |
|
2673 | if ''.join(self.buffer).isspace(): | |
2498 | self.buffer[:] = [] |
|
2674 | self.buffer[:] = [] | |
2499 | return '' |
|
2675 | return '' | |
2500 |
|
2676 | |||
2501 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2677 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2502 |
|
2678 | |||
2503 | # the input history needs to track even empty lines |
|
2679 | # the input history needs to track even empty lines | |
2504 | stripped = line.strip() |
|
2680 | stripped = line.strip() | |
2505 |
|
2681 | |||
2506 | if not stripped: |
|
2682 | if not stripped: | |
2507 | if not continue_prompt: |
|
2683 | if not continue_prompt: | |
2508 | self.outputcache.prompt_count -= 1 |
|
2684 | self.outputcache.prompt_count -= 1 | |
2509 | return self.handle_normal(line_info) |
|
2685 | return self.handle_normal(line_info) | |
2510 |
|
2686 | |||
2511 | # print '***cont',continue_prompt # dbg |
|
2687 | # print '***cont',continue_prompt # dbg | |
2512 | # special handlers are only allowed for single line statements |
|
2688 | # special handlers are only allowed for single line statements | |
2513 | if continue_prompt and not self.multi_line_specials: |
|
2689 | if continue_prompt and not self.multi_line_specials: | |
2514 | return self.handle_normal(line_info) |
|
2690 | return self.handle_normal(line_info) | |
2515 |
|
2691 | |||
2516 |
|
2692 | |||
2517 | # See whether any pre-existing handler can take care of it |
|
2693 | # See whether any pre-existing handler can take care of it | |
2518 | rewritten = self.hooks.input_prefilter(stripped) |
|
2694 | rewritten = self.hooks.input_prefilter(stripped) | |
2519 | if rewritten != stripped: # ok, some prefilter did something |
|
2695 | if rewritten != stripped: # ok, some prefilter did something | |
2520 | rewritten = line_info.pre + rewritten # add indentation |
|
2696 | rewritten = line_info.pre + rewritten # add indentation | |
2521 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2697 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2522 | continue_prompt)) |
|
2698 | continue_prompt)) | |
2523 |
|
2699 | |||
2524 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2700 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2525 |
|
2701 | |||
2526 | return prefilter.prefilter(line_info, self) |
|
2702 | return prefilter.prefilter(line_info, self) | |
2527 |
|
2703 | |||
2528 |
|
2704 | |||
2529 | def _prefilter_dumb(self, line, continue_prompt): |
|
2705 | def _prefilter_dumb(self, line, continue_prompt): | |
2530 | """simple prefilter function, for debugging""" |
|
2706 | """simple prefilter function, for debugging""" | |
2531 | return self.handle_normal(line,continue_prompt) |
|
2707 | return self.handle_normal(line,continue_prompt) | |
2532 |
|
2708 | |||
2533 |
|
2709 | |||
2534 | def multiline_prefilter(self, line, continue_prompt): |
|
2710 | def multiline_prefilter(self, line, continue_prompt): | |
2535 | """ Run _prefilter for each line of input |
|
2711 | """ Run _prefilter for each line of input | |
2536 |
|
2712 | |||
2537 | Covers cases where there are multiple lines in the user entry, |
|
2713 | Covers cases where there are multiple lines in the user entry, | |
2538 | which is the case when the user goes back to a multiline history |
|
2714 | which is the case when the user goes back to a multiline history | |
2539 | entry and presses enter. |
|
2715 | entry and presses enter. | |
2540 |
|
2716 | |||
2541 | """ |
|
2717 | """ | |
2542 | out = [] |
|
2718 | out = [] | |
2543 | for l in line.rstrip('\n').split('\n'): |
|
2719 | for l in line.rstrip('\n').split('\n'): | |
2544 | out.append(self._prefilter(l, continue_prompt)) |
|
2720 | out.append(self._prefilter(l, continue_prompt)) | |
2545 | return '\n'.join(out) |
|
2721 | return '\n'.join(out) | |
2546 |
|
2722 | |||
2547 | # Set the default prefilter() function (this can be user-overridden) |
|
2723 | # Set the default prefilter() function (this can be user-overridden) | |
2548 | prefilter = multiline_prefilter |
|
2724 | prefilter = multiline_prefilter | |
2549 |
|
2725 | |||
2550 | def handle_normal(self,line_info): |
|
2726 | def handle_normal(self,line_info): | |
2551 | """Handle normal input lines. Use as a template for handlers.""" |
|
2727 | """Handle normal input lines. Use as a template for handlers.""" | |
2552 |
|
2728 | |||
2553 | # With autoindent on, we need some way to exit the input loop, and I |
|
2729 | # With autoindent on, we need some way to exit the input loop, and I | |
2554 | # don't want to force the user to have to backspace all the way to |
|
2730 | # don't want to force the user to have to backspace all the way to | |
2555 | # clear the line. The rule will be in this case, that either two |
|
2731 | # clear the line. The rule will be in this case, that either two | |
2556 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2732 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2557 | # of a size different to the indent level, will exit the input loop. |
|
2733 | # of a size different to the indent level, will exit the input loop. | |
2558 | line = line_info.line |
|
2734 | line = line_info.line | |
2559 | continue_prompt = line_info.continue_prompt |
|
2735 | continue_prompt = line_info.continue_prompt | |
2560 |
|
2736 | |||
2561 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2737 | if (continue_prompt and self.autoindent and line.isspace() and | |
2562 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2738 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2563 | (self.buffer[-1]).isspace() )): |
|
2739 | (self.buffer[-1]).isspace() )): | |
2564 | line = '' |
|
2740 | line = '' | |
2565 |
|
2741 | |||
2566 | self.log(line,line,continue_prompt) |
|
2742 | self.log(line,line,continue_prompt) | |
2567 | return line |
|
2743 | return line | |
2568 |
|
2744 | |||
2569 | def handle_alias(self,line_info): |
|
2745 | def handle_alias(self,line_info): | |
2570 | """Handle alias input lines. """ |
|
2746 | """Handle alias input lines. """ | |
2571 | tgt = self.alias_table[line_info.iFun] |
|
2747 | tgt = self.alias_table[line_info.iFun] | |
2572 | # print "=>",tgt #dbg |
|
2748 | # print "=>",tgt #dbg | |
2573 | if callable(tgt): |
|
2749 | if callable(tgt): | |
2574 | if '$' in line_info.line: |
|
2750 | if '$' in line_info.line: | |
2575 | call_meth = '(_ip, _ip.var_expand(%s))' |
|
2751 | call_meth = '(_ip, _ip.var_expand(%s))' | |
2576 | else: |
|
2752 | else: | |
2577 | call_meth = '(_ip,%s)' |
|
2753 | call_meth = '(_ip,%s)' | |
2578 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2754 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2579 | line_info.iFun, |
|
2755 | line_info.iFun, | |
2580 | make_quoted_expr(line_info.line)) |
|
2756 | make_quoted_expr(line_info.line)) | |
2581 | else: |
|
2757 | else: | |
2582 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2758 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2583 |
|
2759 | |||
2584 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2760 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2585 | # aliases won't work in indented sections. |
|
2761 | # aliases won't work in indented sections. | |
2586 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2762 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2587 | make_quoted_expr( transformed )) |
|
2763 | make_quoted_expr( transformed )) | |
2588 |
|
2764 | |||
2589 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2765 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2590 | #print 'line out:',line_out # dbg |
|
2766 | #print 'line out:',line_out # dbg | |
2591 | return line_out |
|
2767 | return line_out | |
2592 |
|
2768 | |||
2593 | def handle_shell_escape(self, line_info): |
|
2769 | def handle_shell_escape(self, line_info): | |
2594 | """Execute the line in a shell, empty return value""" |
|
2770 | """Execute the line in a shell, empty return value""" | |
2595 | #print 'line in :', `line` # dbg |
|
2771 | #print 'line in :', `line` # dbg | |
2596 | line = line_info.line |
|
2772 | line = line_info.line | |
2597 | if line.lstrip().startswith('!!'): |
|
2773 | if line.lstrip().startswith('!!'): | |
2598 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2774 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2599 | # call to %sx and the actual command to be executed, so |
|
2775 | # call to %sx and the actual command to be executed, so | |
2600 | # handle_magic can work correctly. Note that this works even if |
|
2776 | # handle_magic can work correctly. Note that this works even if | |
2601 | # the line is indented, so it handles multi_line_specials |
|
2777 | # the line is indented, so it handles multi_line_specials | |
2602 | # properly. |
|
2778 | # properly. | |
2603 | new_rest = line.lstrip()[2:] |
|
2779 | new_rest = line.lstrip()[2:] | |
2604 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2780 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2605 | line_info.iFun = 'sx' |
|
2781 | line_info.iFun = 'sx' | |
2606 | line_info.theRest = new_rest |
|
2782 | line_info.theRest = new_rest | |
2607 | return self.handle_magic(line_info) |
|
2783 | return self.handle_magic(line_info) | |
2608 | else: |
|
2784 | else: | |
2609 | cmd = line.lstrip().lstrip('!') |
|
2785 | cmd = line.lstrip().lstrip('!') | |
2610 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2786 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2611 | make_quoted_expr(cmd)) |
|
2787 | make_quoted_expr(cmd)) | |
2612 | # update cache/log and return |
|
2788 | # update cache/log and return | |
2613 | self.log(line,line_out,line_info.continue_prompt) |
|
2789 | self.log(line,line_out,line_info.continue_prompt) | |
2614 | return line_out |
|
2790 | return line_out | |
2615 |
|
2791 | |||
2616 | def handle_magic(self, line_info): |
|
2792 | def handle_magic(self, line_info): | |
2617 | """Execute magic functions.""" |
|
2793 | """Execute magic functions.""" | |
2618 | iFun = line_info.iFun |
|
2794 | iFun = line_info.iFun | |
2619 | theRest = line_info.theRest |
|
2795 | theRest = line_info.theRest | |
2620 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2796 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2621 | make_quoted_expr(iFun + " " + theRest)) |
|
2797 | make_quoted_expr(iFun + " " + theRest)) | |
2622 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2798 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2623 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2799 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2624 | return cmd |
|
2800 | return cmd | |
2625 |
|
2801 | |||
2626 | def handle_auto(self, line_info): |
|
2802 | def handle_auto(self, line_info): | |
2627 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2803 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2628 |
|
2804 | |||
2629 | line = line_info.line |
|
2805 | line = line_info.line | |
2630 | iFun = line_info.iFun |
|
2806 | iFun = line_info.iFun | |
2631 | theRest = line_info.theRest |
|
2807 | theRest = line_info.theRest | |
2632 | pre = line_info.pre |
|
2808 | pre = line_info.pre | |
2633 | continue_prompt = line_info.continue_prompt |
|
2809 | continue_prompt = line_info.continue_prompt | |
2634 | obj = line_info.ofind(self)['obj'] |
|
2810 | obj = line_info.ofind(self)['obj'] | |
2635 |
|
2811 | |||
2636 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2812 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2637 |
|
2813 | |||
2638 | # This should only be active for single-line input! |
|
2814 | # This should only be active for single-line input! | |
2639 | if continue_prompt: |
|
2815 | if continue_prompt: | |
2640 | self.log(line,line,continue_prompt) |
|
2816 | self.log(line,line,continue_prompt) | |
2641 | return line |
|
2817 | return line | |
2642 |
|
2818 | |||
2643 | force_auto = isinstance(obj, IPyAutocall) |
|
2819 | force_auto = isinstance(obj, IPyAutocall) | |
2644 | auto_rewrite = True |
|
2820 | auto_rewrite = True | |
2645 |
|
2821 | |||
2646 | if pre == self.ESC_QUOTE: |
|
2822 | if pre == self.ESC_QUOTE: | |
2647 | # Auto-quote splitting on whitespace |
|
2823 | # Auto-quote splitting on whitespace | |
2648 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2824 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2649 | elif pre == self.ESC_QUOTE2: |
|
2825 | elif pre == self.ESC_QUOTE2: | |
2650 | # Auto-quote whole string |
|
2826 | # Auto-quote whole string | |
2651 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2827 | newcmd = '%s("%s")' % (iFun,theRest) | |
2652 | elif pre == self.ESC_PAREN: |
|
2828 | elif pre == self.ESC_PAREN: | |
2653 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2829 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2654 | else: |
|
2830 | else: | |
2655 | # Auto-paren. |
|
2831 | # Auto-paren. | |
2656 | # We only apply it to argument-less calls if the autocall |
|
2832 | # We only apply it to argument-less calls if the autocall | |
2657 | # parameter is set to 2. We only need to check that autocall is < |
|
2833 | # parameter is set to 2. We only need to check that autocall is < | |
2658 | # 2, since this function isn't called unless it's at least 1. |
|
2834 | # 2, since this function isn't called unless it's at least 1. | |
2659 | if not theRest and (self.autocall < 2) and not force_auto: |
|
2835 | if not theRest and (self.autocall < 2) and not force_auto: | |
2660 | newcmd = '%s %s' % (iFun,theRest) |
|
2836 | newcmd = '%s %s' % (iFun,theRest) | |
2661 | auto_rewrite = False |
|
2837 | auto_rewrite = False | |
2662 | else: |
|
2838 | else: | |
2663 | if not force_auto and theRest.startswith('['): |
|
2839 | if not force_auto and theRest.startswith('['): | |
2664 | if hasattr(obj,'__getitem__'): |
|
2840 | if hasattr(obj,'__getitem__'): | |
2665 | # Don't autocall in this case: item access for an object |
|
2841 | # Don't autocall in this case: item access for an object | |
2666 | # which is BOTH callable and implements __getitem__. |
|
2842 | # which is BOTH callable and implements __getitem__. | |
2667 | newcmd = '%s %s' % (iFun,theRest) |
|
2843 | newcmd = '%s %s' % (iFun,theRest) | |
2668 | auto_rewrite = False |
|
2844 | auto_rewrite = False | |
2669 | else: |
|
2845 | else: | |
2670 | # if the object doesn't support [] access, go ahead and |
|
2846 | # if the object doesn't support [] access, go ahead and | |
2671 | # autocall |
|
2847 | # autocall | |
2672 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2848 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2673 | elif theRest.endswith(';'): |
|
2849 | elif theRest.endswith(';'): | |
2674 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2850 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2675 | else: |
|
2851 | else: | |
2676 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2852 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2677 |
|
2853 | |||
2678 | if auto_rewrite: |
|
2854 | if auto_rewrite: | |
2679 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2855 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2680 |
|
2856 | |||
2681 | try: |
|
2857 | try: | |
2682 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2858 | # plain ascii works better w/ pyreadline, on some machines, so | |
2683 | # we use it and only print uncolored rewrite if we have unicode |
|
2859 | # we use it and only print uncolored rewrite if we have unicode | |
2684 | rw = str(rw) |
|
2860 | rw = str(rw) | |
2685 | print >>Term.cout, rw |
|
2861 | print >>Term.cout, rw | |
2686 | except UnicodeEncodeError: |
|
2862 | except UnicodeEncodeError: | |
2687 | print "-------------->" + newcmd |
|
2863 | print "-------------->" + newcmd | |
2688 |
|
2864 | |||
2689 | # log what is now valid Python, not the actual user input (without the |
|
2865 | # log what is now valid Python, not the actual user input (without the | |
2690 | # final newline) |
|
2866 | # final newline) | |
2691 | self.log(line,newcmd,continue_prompt) |
|
2867 | self.log(line,newcmd,continue_prompt) | |
2692 | return newcmd |
|
2868 | return newcmd | |
2693 |
|
2869 | |||
2694 | def handle_help(self, line_info): |
|
2870 | def handle_help(self, line_info): | |
2695 | """Try to get some help for the object. |
|
2871 | """Try to get some help for the object. | |
2696 |
|
2872 | |||
2697 | obj? or ?obj -> basic information. |
|
2873 | obj? or ?obj -> basic information. | |
2698 | obj?? or ??obj -> more details. |
|
2874 | obj?? or ??obj -> more details. | |
2699 | """ |
|
2875 | """ | |
2700 |
|
2876 | |||
2701 | line = line_info.line |
|
2877 | line = line_info.line | |
2702 | # We need to make sure that we don't process lines which would be |
|
2878 | # We need to make sure that we don't process lines which would be | |
2703 | # otherwise valid python, such as "x=1 # what?" |
|
2879 | # otherwise valid python, such as "x=1 # what?" | |
2704 | try: |
|
2880 | try: | |
2705 | codeop.compile_command(line) |
|
2881 | codeop.compile_command(line) | |
2706 | except SyntaxError: |
|
2882 | except SyntaxError: | |
2707 | # We should only handle as help stuff which is NOT valid syntax |
|
2883 | # We should only handle as help stuff which is NOT valid syntax | |
2708 | if line[0]==self.ESC_HELP: |
|
2884 | if line[0]==self.ESC_HELP: | |
2709 | line = line[1:] |
|
2885 | line = line[1:] | |
2710 | elif line[-1]==self.ESC_HELP: |
|
2886 | elif line[-1]==self.ESC_HELP: | |
2711 | line = line[:-1] |
|
2887 | line = line[:-1] | |
2712 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2888 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2713 | if line: |
|
2889 | if line: | |
2714 | #print 'line:<%r>' % line # dbg |
|
2890 | #print 'line:<%r>' % line # dbg | |
2715 | self.magic_pinfo(line) |
|
2891 | self.magic_pinfo(line) | |
2716 | else: |
|
2892 | else: | |
2717 | page(self.usage,screen_lines=self.usable_screen_length) |
|
2893 | page(self.usage,screen_lines=self.usable_screen_length) | |
2718 | return '' # Empty string is needed here! |
|
2894 | return '' # Empty string is needed here! | |
2719 | except: |
|
2895 | except: | |
2720 | # Pass any other exceptions through to the normal handler |
|
2896 | # Pass any other exceptions through to the normal handler | |
2721 | return self.handle_normal(line_info) |
|
2897 | return self.handle_normal(line_info) | |
2722 | else: |
|
2898 | else: | |
2723 | # If the code compiles ok, we should handle it normally |
|
2899 | # If the code compiles ok, we should handle it normally | |
2724 | return self.handle_normal(line_info) |
|
2900 | return self.handle_normal(line_info) | |
2725 |
|
2901 | |||
2726 | def handle_emacs(self, line_info): |
|
2902 | def handle_emacs(self, line_info): | |
2727 | """Handle input lines marked by python-mode.""" |
|
2903 | """Handle input lines marked by python-mode.""" | |
2728 |
|
2904 | |||
2729 | # Currently, nothing is done. Later more functionality can be added |
|
2905 | # Currently, nothing is done. Later more functionality can be added | |
2730 | # here if needed. |
|
2906 | # here if needed. | |
2731 |
|
2907 | |||
2732 | # The input cache shouldn't be updated |
|
2908 | # The input cache shouldn't be updated | |
2733 | return line_info.line |
|
2909 | return line_info.line | |
2734 |
|
2910 | |||
|
2911 | #------------------------------------------------------------------------- | |||
|
2912 | # Utilities | |||
|
2913 | #------------------------------------------------------------------------- | |||
|
2914 | ||||
|
2915 | def getoutput(self, cmd): | |||
|
2916 | return getoutput(self.var_expand(cmd,depth=2), | |||
|
2917 | header=self.system_header, | |||
|
2918 | verbose=self.system_verbose) | |||
|
2919 | ||||
|
2920 | def getoutputerror(self, cmd): | |||
|
2921 | return getoutputerror(self.var_expand(cmd,depth=2), | |||
|
2922 | header=self.system_header, | |||
|
2923 | verbose=self.system_verbose) | |||
|
2924 | ||||
2735 | def var_expand(self,cmd,depth=0): |
|
2925 | def var_expand(self,cmd,depth=0): | |
2736 | """Expand python variables in a string. |
|
2926 | """Expand python variables in a string. | |
2737 |
|
2927 | |||
2738 | The depth argument indicates how many frames above the caller should |
|
2928 | The depth argument indicates how many frames above the caller should | |
2739 | be walked to look for the local namespace where to expand variables. |
|
2929 | be walked to look for the local namespace where to expand variables. | |
2740 |
|
2930 | |||
2741 | The global namespace for expansion is always the user's interactive |
|
2931 | The global namespace for expansion is always the user's interactive | |
2742 | namespace. |
|
2932 | namespace. | |
2743 | """ |
|
2933 | """ | |
2744 |
|
2934 | |||
2745 | return str(ItplNS(cmd, |
|
2935 | return str(ItplNS(cmd, | |
2746 | self.user_ns, # globals |
|
2936 | self.user_ns, # globals | |
2747 | # Skip our own frame in searching for locals: |
|
2937 | # Skip our own frame in searching for locals: | |
2748 | sys._getframe(depth+1).f_locals # locals |
|
2938 | sys._getframe(depth+1).f_locals # locals | |
2749 | )) |
|
2939 | )) | |
2750 |
|
2940 | |||
2751 | def mktempfile(self,data=None): |
|
2941 | def mktempfile(self,data=None): | |
2752 | """Make a new tempfile and return its filename. |
|
2942 | """Make a new tempfile and return its filename. | |
2753 |
|
2943 | |||
2754 | This makes a call to tempfile.mktemp, but it registers the created |
|
2944 | This makes a call to tempfile.mktemp, but it registers the created | |
2755 | filename internally so ipython cleans it up at exit time. |
|
2945 | filename internally so ipython cleans it up at exit time. | |
2756 |
|
2946 | |||
2757 | Optional inputs: |
|
2947 | Optional inputs: | |
2758 |
|
2948 | |||
2759 | - data(None): if data is given, it gets written out to the temp file |
|
2949 | - data(None): if data is given, it gets written out to the temp file | |
2760 | immediately, and the file is closed again.""" |
|
2950 | immediately, and the file is closed again.""" | |
2761 |
|
2951 | |||
2762 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2952 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2763 | self.tempfiles.append(filename) |
|
2953 | self.tempfiles.append(filename) | |
2764 |
|
2954 | |||
2765 | if data: |
|
2955 | if data: | |
2766 | tmp_file = open(filename,'w') |
|
2956 | tmp_file = open(filename,'w') | |
2767 | tmp_file.write(data) |
|
2957 | tmp_file.write(data) | |
2768 | tmp_file.close() |
|
2958 | tmp_file.close() | |
2769 | return filename |
|
2959 | return filename | |
2770 |
|
2960 | |||
2771 | def write(self,data): |
|
2961 | def write(self,data): | |
2772 | """Write a string to the default output""" |
|
2962 | """Write a string to the default output""" | |
2773 | Term.cout.write(data) |
|
2963 | Term.cout.write(data) | |
2774 |
|
2964 | |||
2775 | def write_err(self,data): |
|
2965 | def write_err(self,data): | |
2776 | """Write a string to the default error output""" |
|
2966 | """Write a string to the default error output""" | |
2777 | Term.cerr.write(data) |
|
2967 | Term.cerr.write(data) | |
2778 |
|
2968 | |||
|
2969 | def ask_yes_no(self,prompt,default=True): | |||
|
2970 | if self.quiet: | |||
|
2971 | return True | |||
|
2972 | return ask_yes_no(prompt,default) | |||
|
2973 | ||||
|
2974 | #------------------------------------------------------------------------- | |||
|
2975 | # Things related to IPython exiting | |||
|
2976 | #------------------------------------------------------------------------- | |||
|
2977 | ||||
2779 | def ask_exit(self): |
|
2978 | def ask_exit(self): | |
2780 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2979 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2781 | self.exit_now = True |
|
2980 | self.exit_now = True | |
2782 |
|
2981 | |||
2783 | def exit(self): |
|
2982 | def exit(self): | |
2784 | """Handle interactive exit. |
|
2983 | """Handle interactive exit. | |
2785 |
|
2984 | |||
2786 | This method calls the ask_exit callback.""" |
|
2985 | This method calls the ask_exit callback.""" | |
2787 | if self.confirm_exit: |
|
2986 | if self.confirm_exit: | |
2788 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2987 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2789 | self.ask_exit() |
|
2988 | self.ask_exit() | |
2790 | else: |
|
2989 | else: | |
2791 | self.ask_exit() |
|
2990 | self.ask_exit() | |
2792 |
|
2991 | |||
2793 | def safe_execfile(self,fname,*where,**kw): |
|
2992 | def atexit_operations(self): | |
2794 | """A safe version of the builtin execfile(). |
|
2993 | """This will be executed at the time of exit. | |
2795 |
|
||||
2796 | This version will never throw an exception, and knows how to handle |
|
|||
2797 | ipython logs as well. |
|
|||
2798 |
|
||||
2799 | :Parameters: |
|
|||
2800 | fname : string |
|
|||
2801 | Name of the file to be executed. |
|
|||
2802 |
|
||||
2803 | where : tuple |
|
|||
2804 | One or two namespaces, passed to execfile() as (globals,locals). |
|
|||
2805 | If only one is given, it is passed as both. |
|
|||
2806 |
|
||||
2807 | :Keywords: |
|
|||
2808 | islog : boolean (False) |
|
|||
2809 |
|
||||
2810 | quiet : boolean (True) |
|
|||
2811 |
|
2994 | |||
2812 | exit_ignore : boolean (False) |
|
2995 | Saving of persistent data should be performed here. | |
2813 |
|
|
2996 | """ | |
|
2997 | self.savehist() | |||
2814 |
|
2998 | |||
2815 | def syspath_cleanup(): |
|
2999 | # Cleanup all tempfiles left around | |
2816 | """Internal cleanup routine for sys.path.""" |
|
3000 | for tfile in self.tempfiles: | |
2817 | if add_dname: |
|
|||
2818 |
|
|
3001 | try: | |
2819 | sys.path.remove(dname) |
|
3002 | os.unlink(tfile) | |
2820 |
|
|
3003 | except OSError: | |
2821 | # For some reason the user has already removed it, ignore. |
|
|||
2822 |
|
|
3004 | pass | |
2823 |
|
3005 | |||
2824 | fname = os.path.expanduser(fname) |
|
3006 | # Clear all user namespaces to release all references cleanly. | |
2825 |
|
3007 | self.reset() | ||
2826 | # Find things also in current directory. This is needed to mimic the |
|
|||
2827 | # behavior of running a script from the system command line, where |
|
|||
2828 | # Python inserts the script's directory into sys.path |
|
|||
2829 | dname = os.path.dirname(os.path.abspath(fname)) |
|
|||
2830 | add_dname = False |
|
|||
2831 | if dname not in sys.path: |
|
|||
2832 | sys.path.insert(0,dname) |
|
|||
2833 | add_dname = True |
|
|||
2834 |
|
||||
2835 | try: |
|
|||
2836 | xfile = open(fname) |
|
|||
2837 | except: |
|
|||
2838 | print >> Term.cerr, \ |
|
|||
2839 | 'Could not open file <%s> for safe execution.' % fname |
|
|||
2840 | syspath_cleanup() |
|
|||
2841 | return None |
|
|||
2842 |
|
3008 | |||
2843 | kw.setdefault('islog',0) |
|
3009 | # Run user hooks | |
2844 | kw.setdefault('quiet',1) |
|
3010 | self.hooks.shutdown_hook() | |
2845 | kw.setdefault('exit_ignore',0) |
|
|||
2846 |
|
3011 | |||
2847 | first = xfile.readline() |
|
3012 | def cleanup(self): | |
2848 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
3013 | self.restore_sys_module_state() | |
2849 | xfile.close() |
|
|||
2850 | # line by line execution |
|
|||
2851 | if first.startswith(loghead) or kw['islog']: |
|
|||
2852 | print 'Loading log file <%s> one line at a time...' % fname |
|
|||
2853 | if kw['quiet']: |
|
|||
2854 | stdout_save = sys.stdout |
|
|||
2855 | sys.stdout = StringIO.StringIO() |
|
|||
2856 | try: |
|
|||
2857 | globs,locs = where[0:2] |
|
|||
2858 | except: |
|
|||
2859 | try: |
|
|||
2860 | globs = locs = where[0] |
|
|||
2861 | except: |
|
|||
2862 | globs = locs = globals() |
|
|||
2863 | badblocks = [] |
|
|||
2864 |
|
3014 | |||
2865 | # we also need to identify indented blocks of code when replaying |
|
|||
2866 | # logs and put them together before passing them to an exec |
|
|||
2867 | # statement. This takes a bit of regexp and look-ahead work in the |
|
|||
2868 | # file. It's easiest if we swallow the whole thing in memory |
|
|||
2869 | # first, and manually walk through the lines list moving the |
|
|||
2870 | # counter ourselves. |
|
|||
2871 | indent_re = re.compile('\s+\S') |
|
|||
2872 | xfile = open(fname) |
|
|||
2873 | filelines = xfile.readlines() |
|
|||
2874 | xfile.close() |
|
|||
2875 | nlines = len(filelines) |
|
|||
2876 | lnum = 0 |
|
|||
2877 | while lnum < nlines: |
|
|||
2878 | line = filelines[lnum] |
|
|||
2879 | lnum += 1 |
|
|||
2880 | # don't re-insert logger status info into cache |
|
|||
2881 | if line.startswith('#log#'): |
|
|||
2882 | continue |
|
|||
2883 | else: |
|
|||
2884 | # build a block of code (maybe a single line) for execution |
|
|||
2885 | block = line |
|
|||
2886 | try: |
|
|||
2887 | next = filelines[lnum] # lnum has already incremented |
|
|||
2888 | except: |
|
|||
2889 | next = None |
|
|||
2890 | while next and indent_re.match(next): |
|
|||
2891 | block += next |
|
|||
2892 | lnum += 1 |
|
|||
2893 | try: |
|
|||
2894 | next = filelines[lnum] |
|
|||
2895 | except: |
|
|||
2896 | next = None |
|
|||
2897 | # now execute the block of one or more lines |
|
|||
2898 | try: |
|
|||
2899 | exec block in globs,locs |
|
|||
2900 | except SystemExit: |
|
|||
2901 | pass |
|
|||
2902 | except: |
|
|||
2903 | badblocks.append(block.rstrip()) |
|
|||
2904 | if kw['quiet']: # restore stdout |
|
|||
2905 | sys.stdout.close() |
|
|||
2906 | sys.stdout = stdout_save |
|
|||
2907 | print 'Finished replaying log file <%s>' % fname |
|
|||
2908 | if badblocks: |
|
|||
2909 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
|||
2910 | '<%s> reported errors:' % fname) |
|
|||
2911 |
|
3015 | |||
2912 | for badline in badblocks: |
|
|||
2913 | print >> sys.stderr, badline |
|
|||
2914 | else: # regular file execution |
|
|||
2915 | try: |
|
|||
2916 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
|||
2917 | # Work around a bug in Python for Windows. The bug was |
|
|||
2918 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
|||
2919 | # SVN Python as of March/07. For details, see: |
|
|||
2920 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
|||
2921 | try: |
|
|||
2922 | globs,locs = where[0:2] |
|
|||
2923 | except: |
|
|||
2924 | try: |
|
|||
2925 | globs = locs = where[0] |
|
|||
2926 | except: |
|
|||
2927 | globs = locs = globals() |
|
|||
2928 | exec file(fname) in globs,locs |
|
|||
2929 | else: |
|
|||
2930 | execfile(fname,*where) |
|
|||
2931 | except SyntaxError: |
|
|||
2932 | self.showsyntaxerror() |
|
|||
2933 | warn('Failure executing file: <%s>' % fname) |
|
|||
2934 | except SystemExit,status: |
|
|||
2935 | # Code that correctly sets the exit status flag to success (0) |
|
|||
2936 | # shouldn't be bothered with a traceback. Note that a plain |
|
|||
2937 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
|||
2938 | # will still get a traceback. Note that the structure of the |
|
|||
2939 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
|||
2940 | # the checks must be done in a version-dependent way. |
|
|||
2941 | show = False |
|
|||
2942 |
|
3016 | |||
2943 | if sys.version_info[:2] > (2,5): |
|
|||
2944 | if status.message!=0 and not kw['exit_ignore']: |
|
|||
2945 | show = True |
|
|||
2946 | else: |
|
|||
2947 | if status.code and not kw['exit_ignore']: |
|
|||
2948 | show = True |
|
|||
2949 | if show: |
|
|||
2950 | self.showtraceback() |
|
|||
2951 | warn('Failure executing file: <%s>' % fname) |
|
|||
2952 | except: |
|
|||
2953 | self.showtraceback() |
|
|||
2954 | warn('Failure executing file: <%s>' % fname) |
|
|||
2955 |
|
3017 | |||
2956 | syspath_cleanup() |
|
|||
2957 |
|
3018 | |||
2958 | #************************* end of file <iplib.py> ***************************** |
|
General Comments 0
You need to be logged in to leave comments.
Login now