Show More
@@ -1,388 +1,418 b'' | |||||
|
1 | """A ZMQ-based subclass of InteractiveShell. | |||
|
2 | ||||
|
3 | This code is meant to ease the refactoring of the base InteractiveShell into | |||
|
4 | something with a cleaner architecture for 2-process use, without actually | |||
|
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where | |||
|
6 | we subclass and override what we want to fix. Once this is working well, we | |||
|
7 | can go back to the base class and refactor the code for a cleaner inheritance | |||
|
8 | implementation that doesn't rely on so much monkeypatching. | |||
|
9 | ||||
|
10 | But this lets us maintain a fully working IPython as we develop the new | |||
|
11 | machinery. This should thus be thought of as scaffolding. | |||
|
12 | """ | |||
|
13 | #----------------------------------------------------------------------------- | |||
|
14 | # Imports | |||
|
15 | #----------------------------------------------------------------------------- | |||
|
16 | # Stdlib | |||
1 | import inspect |
|
17 | import inspect | |
|
18 | import os | |||
2 | import re |
|
19 | import re | |
3 | import sys |
|
20 | import sys | |
|
21 | ||||
4 | from subprocess import Popen, PIPE |
|
22 | from subprocess import Popen, PIPE | |
5 |
|
23 | |||
|
24 | # Our own | |||
6 | from IPython.core.interactiveshell import ( |
|
25 | from IPython.core.interactiveshell import ( | |
7 | InteractiveShell, InteractiveShellABC |
|
26 | InteractiveShell, InteractiveShellABC | |
8 | ) |
|
27 | ) | |
9 | from IPython.core.displayhook import DisplayHook |
|
28 | from IPython.core.displayhook import DisplayHook | |
10 | from IPython.core.macro import Macro |
|
29 | from IPython.core.macro import Macro | |
11 | from IPython.utils.path import get_py_filename |
|
30 | from IPython.utils.path import get_py_filename | |
12 | from IPython.utils.text import StringTypes |
|
31 | from IPython.utils.text import StringTypes | |
13 | from IPython.utils.traitlets import Instance, Type, Dict |
|
32 | from IPython.utils.traitlets import Instance, Type, Dict | |
14 | from IPython.utils.warn import warn |
|
33 | from IPython.utils.warn import warn | |
15 | from IPython.zmq.session import extract_header |
|
34 | from IPython.zmq.session import extract_header | |
16 | from IPython.core.payloadpage import install_payload_page |
|
35 | from IPython.core.payloadpage import install_payload_page | |
17 | from session import Session |
|
36 | from session import Session | |
18 |
|
37 | |||
|
38 | #----------------------------------------------------------------------------- | |||
|
39 | # Globals and side-effects | |||
|
40 | #----------------------------------------------------------------------------- | |||
|
41 | ||||
19 | # Install the payload version of page. |
|
42 | # Install the payload version of page. | |
20 | install_payload_page() |
|
43 | install_payload_page() | |
21 |
|
44 | |||
|
45 | #----------------------------------------------------------------------------- | |||
|
46 | # Functions and classes | |||
|
47 | #----------------------------------------------------------------------------- | |||
22 |
|
48 | |||
23 | class ZMQDisplayHook(DisplayHook): |
|
49 | class ZMQDisplayHook(DisplayHook): | |
24 |
|
50 | |||
25 | session = Instance(Session) |
|
51 | session = Instance(Session) | |
26 | pub_socket = Instance('zmq.Socket') |
|
52 | pub_socket = Instance('zmq.Socket') | |
27 | parent_header = Dict({}) |
|
53 | parent_header = Dict({}) | |
28 |
|
54 | |||
29 | def set_parent(self, parent): |
|
55 | def set_parent(self, parent): | |
30 | """Set the parent for outbound messages.""" |
|
56 | """Set the parent for outbound messages.""" | |
31 | self.parent_header = extract_header(parent) |
|
57 | self.parent_header = extract_header(parent) | |
32 |
|
58 | |||
33 | def start_displayhook(self): |
|
59 | def start_displayhook(self): | |
34 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
60 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
35 |
|
61 | |||
36 | def write_output_prompt(self): |
|
62 | def write_output_prompt(self): | |
37 | """Write the output prompt.""" |
|
63 | """Write the output prompt.""" | |
38 | if self.do_full_cache: |
|
64 | if self.do_full_cache: | |
39 | self.msg['content']['output_sep'] = self.output_sep |
|
65 | self.msg['content']['output_sep'] = self.output_sep | |
40 | self.msg['content']['prompt_string'] = str(self.prompt_out) |
|
66 | self.msg['content']['prompt_string'] = str(self.prompt_out) | |
41 | self.msg['content']['prompt_number'] = self.prompt_count |
|
67 | self.msg['content']['prompt_number'] = self.prompt_count | |
42 | self.msg['content']['output_sep2'] = self.output_sep2 |
|
68 | self.msg['content']['output_sep2'] = self.output_sep2 | |
43 |
|
69 | |||
44 | def write_result_repr(self, result_repr): |
|
70 | def write_result_repr(self, result_repr): | |
45 | self.msg['content']['data'] = result_repr |
|
71 | self.msg['content']['data'] = result_repr | |
46 |
|
72 | |||
47 | def finish_displayhook(self): |
|
73 | def finish_displayhook(self): | |
48 | """Finish up all displayhook activities.""" |
|
74 | """Finish up all displayhook activities.""" | |
49 | self.pub_socket.send_json(self.msg) |
|
75 | self.pub_socket.send_json(self.msg) | |
50 | self.msg = None |
|
76 | self.msg = None | |
51 |
|
77 | |||
52 |
|
78 | |||
53 | class ZMQInteractiveShell(InteractiveShell): |
|
79 | class ZMQInteractiveShell(InteractiveShell): | |
54 | """A subclass of InteractiveShell for ZMQ.""" |
|
80 | """A subclass of InteractiveShell for ZMQ.""" | |
55 |
|
81 | |||
56 | displayhook_class = Type(ZMQDisplayHook) |
|
82 | displayhook_class = Type(ZMQDisplayHook) | |
57 |
|
83 | |||
58 | def system(self, cmd): |
|
84 | def system(self, cmd): | |
59 | cmd = self.var_expand(cmd, depth=2) |
|
85 | cmd = self.var_expand(cmd, depth=2) | |
60 | sys.stdout.flush() |
|
86 | sys.stdout.flush() | |
61 | sys.stderr.flush() |
|
87 | sys.stderr.flush() | |
62 | p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) |
|
88 | p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) | |
63 | for line in p.stdout.read().split('\n'): |
|
89 | for line in p.stdout.read().split('\n'): | |
64 | if len(line) > 0: |
|
90 | if len(line) > 0: | |
65 | print line |
|
91 | print line | |
66 | for line in p.stderr.read().split('\n'): |
|
92 | for line in p.stderr.read().split('\n'): | |
67 | if len(line) > 0: |
|
93 | if len(line) > 0: | |
68 | print line |
|
94 | print line | |
69 | p.wait() |
|
95 | p.wait() | |
70 |
|
96 | |||
71 | def init_io(self): |
|
97 | def init_io(self): | |
72 | # This will just use sys.stdout and sys.stderr. If you want to |
|
98 | # This will just use sys.stdout and sys.stderr. If you want to | |
73 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
99 | # override sys.stdout and sys.stderr themselves, you need to do that | |
74 | # *before* instantiating this class, because Term holds onto |
|
100 | # *before* instantiating this class, because Term holds onto | |
75 | # references to the underlying streams. |
|
101 | # references to the underlying streams. | |
76 | import IPython.utils.io |
|
102 | import IPython.utils.io | |
77 | Term = IPython.utils.io.IOTerm() |
|
103 | Term = IPython.utils.io.IOTerm() | |
78 | IPython.utils.io.Term = Term |
|
104 | IPython.utils.io.Term = Term | |
79 |
|
105 | |||
80 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
106 | def magic_edit(self,parameter_s='',last_call=['','']): | |
81 | """Bring up an editor and execute the resulting code. |
|
107 | """Bring up an editor and execute the resulting code. | |
82 |
|
108 | |||
83 | Usage: |
|
109 | Usage: | |
84 | %edit [options] [args] |
|
110 | %edit [options] [args] | |
85 |
|
111 | |||
86 | %edit runs IPython's editor hook. The default version of this hook is |
|
112 | %edit runs IPython's editor hook. The default version of this hook is | |
87 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
113 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
88 | environment variable $EDITOR. If this isn't found, it will default to |
|
114 | environment variable $EDITOR. If this isn't found, it will default to | |
89 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
115 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
90 | docstring for how to change the editor hook. |
|
116 | docstring for how to change the editor hook. | |
91 |
|
117 | |||
92 | You can also set the value of this editor via the command line option |
|
118 | You can also set the value of this editor via the command line option | |
93 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
119 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
94 | specifically for IPython an editor different from your typical default |
|
120 | specifically for IPython an editor different from your typical default | |
95 | (and for Windows users who typically don't set environment variables). |
|
121 | (and for Windows users who typically don't set environment variables). | |
96 |
|
122 | |||
97 | This command allows you to conveniently edit multi-line code right in |
|
123 | This command allows you to conveniently edit multi-line code right in | |
98 | your IPython session. |
|
124 | your IPython session. | |
99 |
|
125 | |||
100 | If called without arguments, %edit opens up an empty editor with a |
|
126 | If called without arguments, %edit opens up an empty editor with a | |
101 | temporary file and will execute the contents of this file when you |
|
127 | temporary file and will execute the contents of this file when you | |
102 | close it (don't forget to save it!). |
|
128 | close it (don't forget to save it!). | |
103 |
|
129 | |||
104 |
|
130 | |||
105 | Options: |
|
131 | Options: | |
106 |
|
132 | |||
107 | -n <number>: open the editor at a specified line number. By default, |
|
133 | -n <number>: open the editor at a specified line number. By default, | |
108 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
134 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
109 | you can configure this by providing your own modified hook if your |
|
135 | you can configure this by providing your own modified hook if your | |
110 | favorite editor supports line-number specifications with a different |
|
136 | favorite editor supports line-number specifications with a different | |
111 | syntax. |
|
137 | syntax. | |
112 |
|
138 | |||
113 | -p: this will call the editor with the same data as the previous time |
|
139 | -p: this will call the editor with the same data as the previous time | |
114 | it was used, regardless of how long ago (in your current session) it |
|
140 | it was used, regardless of how long ago (in your current session) it | |
115 | was. |
|
141 | was. | |
116 |
|
142 | |||
117 | -r: use 'raw' input. This option only applies to input taken from the |
|
143 | -r: use 'raw' input. This option only applies to input taken from the | |
118 | user's history. By default, the 'processed' history is used, so that |
|
144 | user's history. By default, the 'processed' history is used, so that | |
119 | magics are loaded in their transformed version to valid Python. If |
|
145 | magics are loaded in their transformed version to valid Python. If | |
120 | this option is given, the raw input as typed as the command line is |
|
146 | this option is given, the raw input as typed as the command line is | |
121 | used instead. When you exit the editor, it will be executed by |
|
147 | used instead. When you exit the editor, it will be executed by | |
122 | IPython's own processor. |
|
148 | IPython's own processor. | |
123 |
|
149 | |||
124 | -x: do not execute the edited code immediately upon exit. This is |
|
150 | -x: do not execute the edited code immediately upon exit. This is | |
125 | mainly useful if you are editing programs which need to be called with |
|
151 | mainly useful if you are editing programs which need to be called with | |
126 | command line arguments, which you can then do using %run. |
|
152 | command line arguments, which you can then do using %run. | |
127 |
|
153 | |||
128 |
|
154 | |||
129 | Arguments: |
|
155 | Arguments: | |
130 |
|
156 | |||
131 | If arguments are given, the following possibilites exist: |
|
157 | If arguments are given, the following possibilites exist: | |
132 |
|
158 | |||
133 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
159 | - The arguments are numbers or pairs of colon-separated numbers (like | |
134 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
160 | 1 4:8 9). These are interpreted as lines of previous input to be | |
135 | loaded into the editor. The syntax is the same of the %macro command. |
|
161 | loaded into the editor. The syntax is the same of the %macro command. | |
136 |
|
162 | |||
137 | - If the argument doesn't start with a number, it is evaluated as a |
|
163 | - If the argument doesn't start with a number, it is evaluated as a | |
138 | variable and its contents loaded into the editor. You can thus edit |
|
164 | variable and its contents loaded into the editor. You can thus edit | |
139 | any string which contains python code (including the result of |
|
165 | any string which contains python code (including the result of | |
140 | previous edits). |
|
166 | previous edits). | |
141 |
|
167 | |||
142 | - If the argument is the name of an object (other than a string), |
|
168 | - If the argument is the name of an object (other than a string), | |
143 | IPython will try to locate the file where it was defined and open the |
|
169 | IPython will try to locate the file where it was defined and open the | |
144 | editor at the point where it is defined. You can use `%edit function` |
|
170 | editor at the point where it is defined. You can use `%edit function` | |
145 | to load an editor exactly at the point where 'function' is defined, |
|
171 | to load an editor exactly at the point where 'function' is defined, | |
146 | edit it and have the file be executed automatically. |
|
172 | edit it and have the file be executed automatically. | |
147 |
|
173 | |||
148 | If the object is a macro (see %macro for details), this opens up your |
|
174 | If the object is a macro (see %macro for details), this opens up your | |
149 | specified editor with a temporary file containing the macro's data. |
|
175 | specified editor with a temporary file containing the macro's data. | |
150 | Upon exit, the macro is reloaded with the contents of the file. |
|
176 | Upon exit, the macro is reloaded with the contents of the file. | |
151 |
|
177 | |||
152 | Note: opening at an exact line is only supported under Unix, and some |
|
178 | Note: opening at an exact line is only supported under Unix, and some | |
153 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
179 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
154 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
180 | '+NUMBER' parameter necessary for this feature. Good editors like | |
155 | (X)Emacs, vi, jed, pico and joe all do. |
|
181 | (X)Emacs, vi, jed, pico and joe all do. | |
156 |
|
182 | |||
157 | - If the argument is not found as a variable, IPython will look for a |
|
183 | - If the argument is not found as a variable, IPython will look for a | |
158 | file with that name (adding .py if necessary) and load it into the |
|
184 | file with that name (adding .py if necessary) and load it into the | |
159 | editor. It will execute its contents with execfile() when you exit, |
|
185 | editor. It will execute its contents with execfile() when you exit, | |
160 | loading any code in the file into your interactive namespace. |
|
186 | loading any code in the file into your interactive namespace. | |
161 |
|
187 | |||
162 | After executing your code, %edit will return as output the code you |
|
188 | After executing your code, %edit will return as output the code you | |
163 | typed in the editor (except when it was an existing file). This way |
|
189 | typed in the editor (except when it was an existing file). This way | |
164 | you can reload the code in further invocations of %edit as a variable, |
|
190 | you can reload the code in further invocations of %edit as a variable, | |
165 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
191 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
166 | the output. |
|
192 | the output. | |
167 |
|
193 | |||
168 | Note that %edit is also available through the alias %ed. |
|
194 | Note that %edit is also available through the alias %ed. | |
169 |
|
195 | |||
170 | This is an example of creating a simple function inside the editor and |
|
196 | This is an example of creating a simple function inside the editor and | |
171 | then modifying it. First, start up the editor: |
|
197 | then modifying it. First, start up the editor: | |
172 |
|
198 | |||
173 | In [1]: ed |
|
199 | In [1]: ed | |
174 | Editing... done. Executing edited code... |
|
200 | Editing... done. Executing edited code... | |
175 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
201 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
176 |
|
202 | |||
177 | We can then call the function foo(): |
|
203 | We can then call the function foo(): | |
178 |
|
204 | |||
179 | In [2]: foo() |
|
205 | In [2]: foo() | |
180 | foo() was defined in an editing session |
|
206 | foo() was defined in an editing session | |
181 |
|
207 | |||
182 | Now we edit foo. IPython automatically loads the editor with the |
|
208 | Now we edit foo. IPython automatically loads the editor with the | |
183 | (temporary) file where foo() was previously defined: |
|
209 | (temporary) file where foo() was previously defined: | |
184 |
|
210 | |||
185 | In [3]: ed foo |
|
211 | In [3]: ed foo | |
186 | Editing... done. Executing edited code... |
|
212 | Editing... done. Executing edited code... | |
187 |
|
213 | |||
188 | And if we call foo() again we get the modified version: |
|
214 | And if we call foo() again we get the modified version: | |
189 |
|
215 | |||
190 | In [4]: foo() |
|
216 | In [4]: foo() | |
191 | foo() has now been changed! |
|
217 | foo() has now been changed! | |
192 |
|
218 | |||
193 | Here is an example of how to edit a code snippet successive |
|
219 | Here is an example of how to edit a code snippet successive | |
194 | times. First we call the editor: |
|
220 | times. First we call the editor: | |
195 |
|
221 | |||
196 | In [5]: ed |
|
222 | In [5]: ed | |
197 | Editing... done. Executing edited code... |
|
223 | Editing... done. Executing edited code... | |
198 | hello |
|
224 | hello | |
199 | Out[5]: "print 'hello'n" |
|
225 | Out[5]: "print 'hello'n" | |
200 |
|
226 | |||
201 | Now we call it again with the previous output (stored in _): |
|
227 | Now we call it again with the previous output (stored in _): | |
202 |
|
228 | |||
203 | In [6]: ed _ |
|
229 | In [6]: ed _ | |
204 | Editing... done. Executing edited code... |
|
230 | Editing... done. Executing edited code... | |
205 | hello world |
|
231 | hello world | |
206 | Out[6]: "print 'hello world'n" |
|
232 | Out[6]: "print 'hello world'n" | |
207 |
|
233 | |||
208 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
234 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
209 |
|
235 | |||
210 | In [7]: ed _8 |
|
236 | In [7]: ed _8 | |
211 | Editing... done. Executing edited code... |
|
237 | Editing... done. Executing edited code... | |
212 | hello again |
|
238 | hello again | |
213 | Out[7]: "print 'hello again'n" |
|
239 | Out[7]: "print 'hello again'n" | |
214 |
|
240 | |||
215 |
|
241 | |||
216 | Changing the default editor hook: |
|
242 | Changing the default editor hook: | |
217 |
|
243 | |||
218 | If you wish to write your own editor hook, you can put it in a |
|
244 | If you wish to write your own editor hook, you can put it in a | |
219 | configuration file which you load at startup time. The default hook |
|
245 | configuration file which you load at startup time. The default hook | |
220 | is defined in the IPython.core.hooks module, and you can use that as a |
|
246 | is defined in the IPython.core.hooks module, and you can use that as a | |
221 | starting example for further modifications. That file also has |
|
247 | starting example for further modifications. That file also has | |
222 | general instructions on how to set a new hook for use once you've |
|
248 | general instructions on how to set a new hook for use once you've | |
223 | defined it.""" |
|
249 | defined it.""" | |
224 |
|
250 | |||
225 | # FIXME: This function has become a convoluted mess. It needs a |
|
251 | # FIXME: This function has become a convoluted mess. It needs a | |
226 | # ground-up rewrite with clean, simple logic. |
|
252 | # ground-up rewrite with clean, simple logic. | |
227 |
|
253 | |||
228 | def make_filename(arg): |
|
254 | def make_filename(arg): | |
229 | "Make a filename from the given args" |
|
255 | "Make a filename from the given args" | |
230 | try: |
|
256 | try: | |
231 | filename = get_py_filename(arg) |
|
257 | filename = get_py_filename(arg) | |
232 | except IOError: |
|
258 | except IOError: | |
233 | if args.endswith('.py'): |
|
259 | if args.endswith('.py'): | |
234 | filename = arg |
|
260 | filename = arg | |
235 | else: |
|
261 | else: | |
236 | filename = None |
|
262 | filename = None | |
237 | return filename |
|
263 | return filename | |
238 |
|
264 | |||
239 | # custom exceptions |
|
265 | # custom exceptions | |
240 | class DataIsObject(Exception): pass |
|
266 | class DataIsObject(Exception): pass | |
241 |
|
267 | |||
242 | opts,args = self.parse_options(parameter_s,'prn:') |
|
268 | opts,args = self.parse_options(parameter_s,'prn:') | |
243 | # Set a few locals from the options for convenience: |
|
269 | # Set a few locals from the options for convenience: | |
244 | opts_p = opts.has_key('p') |
|
270 | opts_p = opts.has_key('p') | |
245 | opts_r = opts.has_key('r') |
|
271 | opts_r = opts.has_key('r') | |
246 |
|
272 | |||
247 | # Default line number value |
|
273 | # Default line number value | |
248 | lineno = opts.get('n',None) |
|
274 | lineno = opts.get('n',None) | |
249 | if lineno is not None: |
|
275 | if lineno is not None: | |
250 | try: |
|
276 | try: | |
251 | lineno = int(lineno) |
|
277 | lineno = int(lineno) | |
252 | except: |
|
278 | except: | |
253 | warn("The -n argument must be an integer.") |
|
279 | warn("The -n argument must be an integer.") | |
254 | return |
|
280 | return | |
255 |
|
281 | |||
256 | if opts_p: |
|
282 | if opts_p: | |
257 | args = '_%s' % last_call[0] |
|
283 | args = '_%s' % last_call[0] | |
258 | if not self.shell.user_ns.has_key(args): |
|
284 | if not self.shell.user_ns.has_key(args): | |
259 | args = last_call[1] |
|
285 | args = last_call[1] | |
260 |
|
286 | |||
261 | # use last_call to remember the state of the previous call, but don't |
|
287 | # use last_call to remember the state of the previous call, but don't | |
262 | # let it be clobbered by successive '-p' calls. |
|
288 | # let it be clobbered by successive '-p' calls. | |
263 | try: |
|
289 | try: | |
264 | last_call[0] = self.shell.displayhook.prompt_count |
|
290 | last_call[0] = self.shell.displayhook.prompt_count | |
265 | if not opts_p: |
|
291 | if not opts_p: | |
266 | last_call[1] = parameter_s |
|
292 | last_call[1] = parameter_s | |
267 | except: |
|
293 | except: | |
268 | pass |
|
294 | pass | |
269 |
|
295 | |||
270 | # by default this is done with temp files, except when the given |
|
296 | # by default this is done with temp files, except when the given | |
271 | # arg is a filename |
|
297 | # arg is a filename | |
272 | use_temp = 1 |
|
298 | use_temp = 1 | |
273 |
|
299 | |||
274 | if re.match(r'\d',args): |
|
300 | if re.match(r'\d',args): | |
275 | # Mode where user specifies ranges of lines, like in %macro. |
|
301 | # Mode where user specifies ranges of lines, like in %macro. | |
276 | # This means that you can't edit files whose names begin with |
|
302 | # This means that you can't edit files whose names begin with | |
277 | # numbers this way. Tough. |
|
303 | # numbers this way. Tough. | |
278 | ranges = args.split() |
|
304 | ranges = args.split() | |
279 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
305 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
280 | elif args.endswith('.py'): |
|
306 | elif args.endswith('.py'): | |
281 | filename = make_filename(args) |
|
307 | filename = make_filename(args) | |
282 | data = '' |
|
308 | data = '' | |
283 | use_temp = 0 |
|
309 | use_temp = 0 | |
284 | elif args: |
|
310 | elif args: | |
285 | try: |
|
311 | try: | |
286 | # Load the parameter given as a variable. If not a string, |
|
312 | # Load the parameter given as a variable. If not a string, | |
287 | # process it as an object instead (below) |
|
313 | # process it as an object instead (below) | |
288 |
|
314 | |||
289 | #print '*** args',args,'type',type(args) # dbg |
|
315 | #print '*** args',args,'type',type(args) # dbg | |
290 | data = eval(args,self.shell.user_ns) |
|
316 | data = eval(args,self.shell.user_ns) | |
291 | if not type(data) in StringTypes: |
|
317 | if not type(data) in StringTypes: | |
292 | raise DataIsObject |
|
318 | raise DataIsObject | |
293 |
|
319 | |||
294 | except (NameError,SyntaxError): |
|
320 | except (NameError,SyntaxError): | |
295 | # given argument is not a variable, try as a filename |
|
321 | # given argument is not a variable, try as a filename | |
296 | filename = make_filename(args) |
|
322 | filename = make_filename(args) | |
297 | if filename is None: |
|
323 | if filename is None: | |
298 | warn("Argument given (%s) can't be found as a variable " |
|
324 | warn("Argument given (%s) can't be found as a variable " | |
299 | "or as a filename." % args) |
|
325 | "or as a filename." % args) | |
300 | return |
|
326 | return | |
301 |
|
327 | |||
302 | data = '' |
|
328 | data = '' | |
303 | use_temp = 0 |
|
329 | use_temp = 0 | |
304 | except DataIsObject: |
|
330 | except DataIsObject: | |
305 |
|
331 | |||
306 | # macros have a special edit function |
|
332 | # macros have a special edit function | |
307 | if isinstance(data,Macro): |
|
333 | if isinstance(data,Macro): | |
308 | self._edit_macro(args,data) |
|
334 | self._edit_macro(args,data) | |
309 | return |
|
335 | return | |
310 |
|
336 | |||
311 | # For objects, try to edit the file where they are defined |
|
337 | # For objects, try to edit the file where they are defined | |
312 | try: |
|
338 | try: | |
313 | filename = inspect.getabsfile(data) |
|
339 | filename = inspect.getabsfile(data) | |
314 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
340 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
315 | # class created by %edit? Try to find source |
|
341 | # class created by %edit? Try to find source | |
316 | # by looking for method definitions instead, the |
|
342 | # by looking for method definitions instead, the | |
317 | # __module__ in those classes is FakeModule. |
|
343 | # __module__ in those classes is FakeModule. | |
318 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
344 | attrs = [getattr(data, aname) for aname in dir(data)] | |
319 | for attr in attrs: |
|
345 | for attr in attrs: | |
320 | if not inspect.ismethod(attr): |
|
346 | if not inspect.ismethod(attr): | |
321 | continue |
|
347 | continue | |
322 | filename = inspect.getabsfile(attr) |
|
348 | filename = inspect.getabsfile(attr) | |
323 | if filename and 'fakemodule' not in filename.lower(): |
|
349 | if filename and 'fakemodule' not in filename.lower(): | |
324 | # change the attribute to be the edit target instead |
|
350 | # change the attribute to be the edit target instead | |
325 | data = attr |
|
351 | data = attr | |
326 | break |
|
352 | break | |
327 |
|
353 | |||
328 | datafile = 1 |
|
354 | datafile = 1 | |
329 | except TypeError: |
|
355 | except TypeError: | |
330 | filename = make_filename(args) |
|
356 | filename = make_filename(args) | |
331 | datafile = 1 |
|
357 | datafile = 1 | |
332 | warn('Could not find file where `%s` is defined.\n' |
|
358 | warn('Could not find file where `%s` is defined.\n' | |
333 | 'Opening a file named `%s`' % (args,filename)) |
|
359 | 'Opening a file named `%s`' % (args,filename)) | |
334 | # Now, make sure we can actually read the source (if it was in |
|
360 | # Now, make sure we can actually read the source (if it was in | |
335 | # a temp file it's gone by now). |
|
361 | # a temp file it's gone by now). | |
336 | if datafile: |
|
362 | if datafile: | |
337 | try: |
|
363 | try: | |
338 | if lineno is None: |
|
364 | if lineno is None: | |
339 | lineno = inspect.getsourcelines(data)[1] |
|
365 | lineno = inspect.getsourcelines(data)[1] | |
340 | except IOError: |
|
366 | except IOError: | |
341 | filename = make_filename(args) |
|
367 | filename = make_filename(args) | |
342 | if filename is None: |
|
368 | if filename is None: | |
343 | warn('The file `%s` where `%s` was defined cannot ' |
|
369 | warn('The file `%s` where `%s` was defined cannot ' | |
344 | 'be read.' % (filename,data)) |
|
370 | 'be read.' % (filename,data)) | |
345 | return |
|
371 | return | |
346 | use_temp = 0 |
|
372 | use_temp = 0 | |
347 | else: |
|
373 | else: | |
348 | data = '' |
|
374 | data = '' | |
349 |
|
375 | |||
350 | if use_temp: |
|
376 | if use_temp: | |
351 | filename = self.shell.mktempfile(data) |
|
377 | filename = self.shell.mktempfile(data) | |
352 | print 'IPython will make a temporary file named:',filename |
|
378 | print 'IPython will make a temporary file named:',filename | |
353 |
|
379 | |||
|
380 | # Make sure we send to the client an absolute path, in case the working | |||
|
381 | # directory of client and kernel don't match | |||
|
382 | filename = os.path.abspath(filename) | |||
|
383 | ||||
354 | payload = { |
|
384 | payload = { | |
355 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
385 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
356 | 'filename' : filename, |
|
386 | 'filename' : filename, | |
357 | 'line_number' : lineno |
|
387 | 'line_number' : lineno | |
358 | } |
|
388 | } | |
359 | self.payload_manager.write_payload(payload) |
|
389 | self.payload_manager.write_payload(payload) | |
360 |
|
390 | |||
361 |
|
391 | |||
362 | def _showtraceback(self, etype, evalue, stb): |
|
392 | def _showtraceback(self, etype, evalue, stb): | |
363 |
|
393 | |||
364 | exc_content = { |
|
394 | exc_content = { | |
365 | u'status' : u'error', |
|
395 | u'status' : u'error', | |
366 | u'traceback' : stb, |
|
396 | u'traceback' : stb, | |
367 | u'ename' : unicode(etype.__name__), |
|
397 | u'ename' : unicode(etype.__name__), | |
368 | u'evalue' : unicode(evalue) |
|
398 | u'evalue' : unicode(evalue) | |
369 | } |
|
399 | } | |
370 |
|
400 | |||
371 | dh = self.displayhook |
|
401 | dh = self.displayhook | |
372 | exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header) |
|
402 | exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header) | |
373 | # Send exception info over pub socket for other clients than the caller |
|
403 | # Send exception info over pub socket for other clients than the caller | |
374 | # to pick up |
|
404 | # to pick up | |
375 | dh.pub_socket.send_json(exc_msg) |
|
405 | dh.pub_socket.send_json(exc_msg) | |
376 |
|
406 | |||
377 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
407 | # FIXME - Hack: store exception info in shell object. Right now, the | |
378 | # caller is reading this info after the fact, we need to fix this logic |
|
408 | # caller is reading this info after the fact, we need to fix this logic | |
379 | # to remove this hack. |
|
409 | # to remove this hack. | |
380 | self._reply_content = exc_content |
|
410 | self._reply_content = exc_content | |
381 | # /FIXME |
|
411 | # /FIXME | |
382 |
|
412 | |||
383 | return exc_content |
|
413 | return exc_content | |
384 |
|
414 | |||
385 | def runlines(self, lines, clean=False): |
|
415 | def runlines(self, lines, clean=False): | |
386 | return InteractiveShell.runlines(self, lines, clean) |
|
416 | return InteractiveShell.runlines(self, lines, clean) | |
387 |
|
417 | |||
388 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
418 | InteractiveShellABC.register(ZMQInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now