Show More
@@ -1,526 +1,531 b'' | |||||
1 | """Implementation of code management magic functions. |
|
1 | """Implementation of code management magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Stdlib |
|
15 | # Stdlib | |
16 | import inspect |
|
16 | import inspect | |
17 | import io |
|
17 | import io | |
18 | import json |
|
18 | import json | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 | from urllib2 import urlopen |
|
21 | from urllib2 import urlopen | |
22 |
|
22 | |||
23 | # Our own packages |
|
23 | # Our own packages | |
24 | from IPython.core.error import TryNext, StdinNotImplementedError |
|
24 | from IPython.core.error import TryNext, StdinNotImplementedError, UsageError | |
25 | from IPython.core.macro import Macro |
|
25 | from IPython.core.macro import Macro | |
26 | from IPython.core.magic import Magics, magics_class, line_magic |
|
26 | from IPython.core.magic import Magics, magics_class, line_magic | |
27 | from IPython.core.oinspect import find_file, find_source_lines |
|
27 | from IPython.core.oinspect import find_file, find_source_lines | |
28 | from IPython.testing.skipdoctest import skip_doctest |
|
28 | from IPython.testing.skipdoctest import skip_doctest | |
29 | from IPython.utils import openpy |
|
29 | from IPython.utils import openpy | |
30 | from IPython.utils import py3compat |
|
30 | from IPython.utils import py3compat | |
31 | from IPython.utils.io import file_read |
|
31 | from IPython.utils.io import file_read | |
32 | from IPython.utils.path import get_py_filename, unquote_filename |
|
32 | from IPython.utils.path import get_py_filename, unquote_filename | |
33 | from IPython.utils.warn import warn |
|
33 | from IPython.utils.warn import warn | |
34 |
|
34 | |||
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 | # Magic implementation classes |
|
36 | # Magic implementation classes | |
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 |
|
38 | |||
39 | # Used for exception handling in magic_edit |
|
39 | # Used for exception handling in magic_edit | |
40 | class MacroToEdit(ValueError): pass |
|
40 | class MacroToEdit(ValueError): pass | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | @magics_class |
|
43 | @magics_class | |
44 | class CodeMagics(Magics): |
|
44 | class CodeMagics(Magics): | |
45 | """Magics related to code management (loading, saving, editing, ...).""" |
|
45 | """Magics related to code management (loading, saving, editing, ...).""" | |
46 |
|
46 | |||
47 | @line_magic |
|
47 | @line_magic | |
48 | def save(self, parameter_s=''): |
|
48 | def save(self, parameter_s=''): | |
49 | """Save a set of lines or a macro to a given filename. |
|
49 | """Save a set of lines or a macro to a given filename. | |
50 |
|
50 | |||
51 | Usage:\\ |
|
51 | Usage:\\ | |
52 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
52 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
53 |
|
53 | |||
54 | Options: |
|
54 | Options: | |
55 |
|
55 | |||
56 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
56 | -r: use 'raw' input. By default, the 'processed' history is used, | |
57 | so that magics are loaded in their transformed version to valid |
|
57 | so that magics are loaded in their transformed version to valid | |
58 | Python. If this option is given, the raw input as typed as the |
|
58 | Python. If this option is given, the raw input as typed as the | |
59 | command line is used instead. |
|
59 | command line is used instead. | |
60 |
|
60 | |||
61 | -f: force overwrite. If file exists, %save will prompt for overwrite |
|
61 | -f: force overwrite. If file exists, %save will prompt for overwrite | |
62 | unless -f is given. |
|
62 | unless -f is given. | |
63 |
|
63 | |||
64 | -a: append to the file instead of overwriting it. |
|
64 | -a: append to the file instead of overwriting it. | |
65 |
|
65 | |||
66 | This function uses the same syntax as %history for input ranges, |
|
66 | This function uses the same syntax as %history for input ranges, | |
67 | then saves the lines to the filename you specify. |
|
67 | then saves the lines to the filename you specify. | |
68 |
|
68 | |||
69 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
69 | It adds a '.py' extension to the file if you don't do so yourself, and | |
70 | it asks for confirmation before overwriting existing files. |
|
70 | it asks for confirmation before overwriting existing files. | |
71 |
|
71 | |||
72 | If `-r` option is used, the default extension is `.ipy`. |
|
72 | If `-r` option is used, the default extension is `.ipy`. | |
73 | """ |
|
73 | """ | |
74 |
|
74 | |||
75 | opts,args = self.parse_options(parameter_s,'fra',mode='list') |
|
75 | opts,args = self.parse_options(parameter_s,'fra',mode='list') | |
|
76 | if not args: | |||
|
77 | raise UsageError('Missing filename.') | |||
76 | raw = 'r' in opts |
|
78 | raw = 'r' in opts | |
77 | force = 'f' in opts |
|
79 | force = 'f' in opts | |
78 | append = 'a' in opts |
|
80 | append = 'a' in opts | |
79 | mode = 'a' if append else 'w' |
|
81 | mode = 'a' if append else 'w' | |
80 | ext = u'.ipy' if raw else u'.py' |
|
82 | ext = u'.ipy' if raw else u'.py' | |
81 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
83 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) | |
82 | if not fname.endswith((u'.py',u'.ipy')): |
|
84 | if not fname.endswith((u'.py',u'.ipy')): | |
83 | fname += ext |
|
85 | fname += ext | |
84 | file_exists = os.path.isfile(fname) |
|
86 | file_exists = os.path.isfile(fname) | |
85 | if file_exists and not force and not append: |
|
87 | if file_exists and not force and not append: | |
86 | try: |
|
88 | try: | |
87 | overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') |
|
89 | overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') | |
88 | except StdinNotImplementedError: |
|
90 | except StdinNotImplementedError: | |
89 | print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s) |
|
91 | print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s) | |
90 | return |
|
92 | return | |
91 | if not overwrite : |
|
93 | if not overwrite : | |
92 | print 'Operation cancelled.' |
|
94 | print 'Operation cancelled.' | |
93 | return |
|
95 | return | |
94 | try: |
|
96 | try: | |
95 | cmds = self.shell.find_user_code(codefrom,raw) |
|
97 | cmds = self.shell.find_user_code(codefrom,raw) | |
96 | except (TypeError, ValueError) as e: |
|
98 | except (TypeError, ValueError) as e: | |
97 | print e.args[0] |
|
99 | print e.args[0] | |
98 | return |
|
100 | return | |
99 | out = py3compat.cast_unicode(cmds) |
|
101 | out = py3compat.cast_unicode(cmds) | |
100 | with io.open(fname, mode, encoding="utf-8") as f: |
|
102 | with io.open(fname, mode, encoding="utf-8") as f: | |
101 | if not file_exists or not append: |
|
103 | if not file_exists or not append: | |
102 | f.write(u"# coding: utf-8\n") |
|
104 | f.write(u"# coding: utf-8\n") | |
103 | f.write(out) |
|
105 | f.write(out) | |
104 | # make sure we end on a newline |
|
106 | # make sure we end on a newline | |
105 | if not out.endswith(u'\n'): |
|
107 | if not out.endswith(u'\n'): | |
106 | f.write(u'\n') |
|
108 | f.write(u'\n') | |
107 | print 'The following commands were written to file `%s`:' % fname |
|
109 | print 'The following commands were written to file `%s`:' % fname | |
108 | print cmds |
|
110 | print cmds | |
109 |
|
111 | |||
110 | @line_magic |
|
112 | @line_magic | |
111 | def pastebin(self, parameter_s=''): |
|
113 | def pastebin(self, parameter_s=''): | |
112 | """Upload code to Github's Gist paste bin, returning the URL. |
|
114 | """Upload code to Github's Gist paste bin, returning the URL. | |
113 |
|
115 | |||
114 | Usage:\\ |
|
116 | Usage:\\ | |
115 | %pastebin [-d "Custom description"] 1-7 |
|
117 | %pastebin [-d "Custom description"] 1-7 | |
116 |
|
118 | |||
117 | The argument can be an input history range, a filename, or the name of a |
|
119 | The argument can be an input history range, a filename, or the name of a | |
118 | string or macro. |
|
120 | string or macro. | |
119 |
|
121 | |||
120 | Options: |
|
122 | Options: | |
121 |
|
123 | |||
122 | -d: Pass a custom description for the gist. The default will say |
|
124 | -d: Pass a custom description for the gist. The default will say | |
123 | "Pasted from IPython". |
|
125 | "Pasted from IPython". | |
124 | """ |
|
126 | """ | |
125 | opts, args = self.parse_options(parameter_s, 'd:') |
|
127 | opts, args = self.parse_options(parameter_s, 'd:') | |
126 |
|
128 | |||
127 | try: |
|
129 | try: | |
128 | code = self.shell.find_user_code(args) |
|
130 | code = self.shell.find_user_code(args) | |
129 | except (ValueError, TypeError) as e: |
|
131 | except (ValueError, TypeError) as e: | |
130 | print e.args[0] |
|
132 | print e.args[0] | |
131 | return |
|
133 | return | |
132 |
|
134 | |||
133 | post_data = json.dumps({ |
|
135 | post_data = json.dumps({ | |
134 | "description": opts.get('d', "Pasted from IPython"), |
|
136 | "description": opts.get('d', "Pasted from IPython"), | |
135 | "public": True, |
|
137 | "public": True, | |
136 | "files": { |
|
138 | "files": { | |
137 | "file1.py": { |
|
139 | "file1.py": { | |
138 | "content": code |
|
140 | "content": code | |
139 | } |
|
141 | } | |
140 | } |
|
142 | } | |
141 | }).encode('utf-8') |
|
143 | }).encode('utf-8') | |
142 |
|
144 | |||
143 | response = urlopen("https://api.github.com/gists", post_data) |
|
145 | response = urlopen("https://api.github.com/gists", post_data) | |
144 | response_data = json.loads(response.read().decode('utf-8')) |
|
146 | response_data = json.loads(response.read().decode('utf-8')) | |
145 | return response_data['html_url'] |
|
147 | return response_data['html_url'] | |
146 |
|
148 | |||
147 | @line_magic |
|
149 | @line_magic | |
148 | def loadpy(self, arg_s): |
|
150 | def loadpy(self, arg_s): | |
149 | """Alias of `%load` |
|
151 | """Alias of `%load` | |
150 |
|
152 | |||
151 | `%loadpy` has gained some flexibility and droped the requirement of a `.py` |
|
153 | `%loadpy` has gained some flexibility and droped the requirement of a `.py` | |
152 | extension. So it has been renamed simply into %load. You can look at |
|
154 | extension. So it has been renamed simply into %load. You can look at | |
153 | `%load`'s docstring for more info. |
|
155 | `%load`'s docstring for more info. | |
154 | """ |
|
156 | """ | |
155 | self.load(arg_s) |
|
157 | self.load(arg_s) | |
156 |
|
158 | |||
157 | @line_magic |
|
159 | @line_magic | |
158 | def load(self, arg_s): |
|
160 | def load(self, arg_s): | |
159 | """Load code into the current frontend. |
|
161 | """Load code into the current frontend. | |
160 |
|
162 | |||
161 | Usage:\\ |
|
163 | Usage:\\ | |
162 | %load [options] source |
|
164 | %load [options] source | |
163 |
|
165 | |||
164 | where source can be a filename, URL, input history range or macro |
|
166 | where source can be a filename, URL, input history range or macro | |
165 |
|
167 | |||
166 | Options: |
|
168 | Options: | |
167 | -------- |
|
169 | -------- | |
168 | -y : Don't ask confirmation for loading source above 200 000 characters. |
|
170 | -y : Don't ask confirmation for loading source above 200 000 characters. | |
169 |
|
171 | |||
170 | This magic command can either take a local filename, a URL, an history |
|
172 | This magic command can either take a local filename, a URL, an history | |
171 | range (see %history) or a macro as argument, it will prompt for |
|
173 | range (see %history) or a macro as argument, it will prompt for | |
172 | confirmation before loading source with more than 200 000 characters, unless |
|
174 | confirmation before loading source with more than 200 000 characters, unless | |
173 | -y flag is passed or if the frontend does not support raw_input:: |
|
175 | -y flag is passed or if the frontend does not support raw_input:: | |
174 |
|
176 | |||
175 | %load myscript.py |
|
177 | %load myscript.py | |
176 | %load 7-27 |
|
178 | %load 7-27 | |
177 | %load myMacro |
|
179 | %load myMacro | |
178 | %load http://www.example.com/myscript.py |
|
180 | %load http://www.example.com/myscript.py | |
179 | """ |
|
181 | """ | |
180 | opts,args = self.parse_options(arg_s,'y') |
|
182 | opts,args = self.parse_options(arg_s,'y') | |
|
183 | if not args: | |||
|
184 | raise UsageError('Missing filename, URL, input history range, ' | |||
|
185 | 'or macro.') | |||
181 |
|
186 | |||
182 | contents = self.shell.find_user_code(args) |
|
187 | contents = self.shell.find_user_code(args) | |
183 | l = len(contents) |
|
188 | l = len(contents) | |
184 |
|
189 | |||
185 | # 200 000 is ~ 2500 full 80 caracter lines |
|
190 | # 200 000 is ~ 2500 full 80 caracter lines | |
186 | # so in average, more than 5000 lines |
|
191 | # so in average, more than 5000 lines | |
187 | if l > 200000 and 'y' not in opts: |
|
192 | if l > 200000 and 'y' not in opts: | |
188 | try: |
|
193 | try: | |
189 | ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\ |
|
194 | ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\ | |
190 | " (%d characters). Continue (y/[N]) ?" % l), default='n' ) |
|
195 | " (%d characters). Continue (y/[N]) ?" % l), default='n' ) | |
191 | except StdinNotImplementedError: |
|
196 | except StdinNotImplementedError: | |
192 | #asume yes if raw input not implemented |
|
197 | #asume yes if raw input not implemented | |
193 | ans = True |
|
198 | ans = True | |
194 |
|
199 | |||
195 | if ans is False : |
|
200 | if ans is False : | |
196 | print 'Operation cancelled.' |
|
201 | print 'Operation cancelled.' | |
197 | return |
|
202 | return | |
198 |
|
203 | |||
199 | self.shell.set_next_input(contents) |
|
204 | self.shell.set_next_input(contents) | |
200 |
|
205 | |||
201 | @staticmethod |
|
206 | @staticmethod | |
202 | def _find_edit_target(shell, args, opts, last_call): |
|
207 | def _find_edit_target(shell, args, opts, last_call): | |
203 | """Utility method used by magic_edit to find what to edit.""" |
|
208 | """Utility method used by magic_edit to find what to edit.""" | |
204 |
|
209 | |||
205 | def make_filename(arg): |
|
210 | def make_filename(arg): | |
206 | "Make a filename from the given args" |
|
211 | "Make a filename from the given args" | |
207 | arg = unquote_filename(arg) |
|
212 | arg = unquote_filename(arg) | |
208 | try: |
|
213 | try: | |
209 | filename = get_py_filename(arg) |
|
214 | filename = get_py_filename(arg) | |
210 | except IOError: |
|
215 | except IOError: | |
211 | # If it ends with .py but doesn't already exist, assume we want |
|
216 | # If it ends with .py but doesn't already exist, assume we want | |
212 | # a new file. |
|
217 | # a new file. | |
213 | if arg.endswith('.py'): |
|
218 | if arg.endswith('.py'): | |
214 | filename = arg |
|
219 | filename = arg | |
215 | else: |
|
220 | else: | |
216 | filename = None |
|
221 | filename = None | |
217 | return filename |
|
222 | return filename | |
218 |
|
223 | |||
219 | # Set a few locals from the options for convenience: |
|
224 | # Set a few locals from the options for convenience: | |
220 | opts_prev = 'p' in opts |
|
225 | opts_prev = 'p' in opts | |
221 | opts_raw = 'r' in opts |
|
226 | opts_raw = 'r' in opts | |
222 |
|
227 | |||
223 | # custom exceptions |
|
228 | # custom exceptions | |
224 | class DataIsObject(Exception): pass |
|
229 | class DataIsObject(Exception): pass | |
225 |
|
230 | |||
226 | # Default line number value |
|
231 | # Default line number value | |
227 | lineno = opts.get('n',None) |
|
232 | lineno = opts.get('n',None) | |
228 |
|
233 | |||
229 | if opts_prev: |
|
234 | if opts_prev: | |
230 | args = '_%s' % last_call[0] |
|
235 | args = '_%s' % last_call[0] | |
231 | if args not in shell.user_ns: |
|
236 | if args not in shell.user_ns: | |
232 | args = last_call[1] |
|
237 | args = last_call[1] | |
233 |
|
238 | |||
234 | # use last_call to remember the state of the previous call, but don't |
|
239 | # use last_call to remember the state of the previous call, but don't | |
235 | # let it be clobbered by successive '-p' calls. |
|
240 | # let it be clobbered by successive '-p' calls. | |
236 | try: |
|
241 | try: | |
237 | last_call[0] = shell.displayhook.prompt_count |
|
242 | last_call[0] = shell.displayhook.prompt_count | |
238 | if not opts_prev: |
|
243 | if not opts_prev: | |
239 | last_call[1] = args |
|
244 | last_call[1] = args | |
240 | except: |
|
245 | except: | |
241 | pass |
|
246 | pass | |
242 |
|
247 | |||
243 | # by default this is done with temp files, except when the given |
|
248 | # by default this is done with temp files, except when the given | |
244 | # arg is a filename |
|
249 | # arg is a filename | |
245 | use_temp = True |
|
250 | use_temp = True | |
246 |
|
251 | |||
247 | data = '' |
|
252 | data = '' | |
248 |
|
253 | |||
249 | # First, see if the arguments should be a filename. |
|
254 | # First, see if the arguments should be a filename. | |
250 | filename = make_filename(args) |
|
255 | filename = make_filename(args) | |
251 | if filename: |
|
256 | if filename: | |
252 | use_temp = False |
|
257 | use_temp = False | |
253 | elif args: |
|
258 | elif args: | |
254 | # Mode where user specifies ranges of lines, like in %macro. |
|
259 | # Mode where user specifies ranges of lines, like in %macro. | |
255 | data = shell.extract_input_lines(args, opts_raw) |
|
260 | data = shell.extract_input_lines(args, opts_raw) | |
256 | if not data: |
|
261 | if not data: | |
257 | try: |
|
262 | try: | |
258 | # Load the parameter given as a variable. If not a string, |
|
263 | # Load the parameter given as a variable. If not a string, | |
259 | # process it as an object instead (below) |
|
264 | # process it as an object instead (below) | |
260 |
|
265 | |||
261 | #print '*** args',args,'type',type(args) # dbg |
|
266 | #print '*** args',args,'type',type(args) # dbg | |
262 | data = eval(args, shell.user_ns) |
|
267 | data = eval(args, shell.user_ns) | |
263 | if not isinstance(data, basestring): |
|
268 | if not isinstance(data, basestring): | |
264 | raise DataIsObject |
|
269 | raise DataIsObject | |
265 |
|
270 | |||
266 | except (NameError,SyntaxError): |
|
271 | except (NameError,SyntaxError): | |
267 | # given argument is not a variable, try as a filename |
|
272 | # given argument is not a variable, try as a filename | |
268 | filename = make_filename(args) |
|
273 | filename = make_filename(args) | |
269 | if filename is None: |
|
274 | if filename is None: | |
270 | warn("Argument given (%s) can't be found as a variable " |
|
275 | warn("Argument given (%s) can't be found as a variable " | |
271 | "or as a filename." % args) |
|
276 | "or as a filename." % args) | |
272 | return |
|
277 | return | |
273 | use_temp = False |
|
278 | use_temp = False | |
274 |
|
279 | |||
275 | except DataIsObject: |
|
280 | except DataIsObject: | |
276 | # macros have a special edit function |
|
281 | # macros have a special edit function | |
277 | if isinstance(data, Macro): |
|
282 | if isinstance(data, Macro): | |
278 | raise MacroToEdit(data) |
|
283 | raise MacroToEdit(data) | |
279 |
|
284 | |||
280 | # For objects, try to edit the file where they are defined |
|
285 | # For objects, try to edit the file where they are defined | |
281 | filename = find_file(data) |
|
286 | filename = find_file(data) | |
282 | if filename: |
|
287 | if filename: | |
283 | if 'fakemodule' in filename.lower() and \ |
|
288 | if 'fakemodule' in filename.lower() and \ | |
284 | inspect.isclass(data): |
|
289 | inspect.isclass(data): | |
285 | # class created by %edit? Try to find source |
|
290 | # class created by %edit? Try to find source | |
286 | # by looking for method definitions instead, the |
|
291 | # by looking for method definitions instead, the | |
287 | # __module__ in those classes is FakeModule. |
|
292 | # __module__ in those classes is FakeModule. | |
288 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
293 | attrs = [getattr(data, aname) for aname in dir(data)] | |
289 | for attr in attrs: |
|
294 | for attr in attrs: | |
290 | if not inspect.ismethod(attr): |
|
295 | if not inspect.ismethod(attr): | |
291 | continue |
|
296 | continue | |
292 | filename = find_file(attr) |
|
297 | filename = find_file(attr) | |
293 | if filename and \ |
|
298 | if filename and \ | |
294 | 'fakemodule' not in filename.lower(): |
|
299 | 'fakemodule' not in filename.lower(): | |
295 | # change the attribute to be the edit |
|
300 | # change the attribute to be the edit | |
296 | # target instead |
|
301 | # target instead | |
297 | data = attr |
|
302 | data = attr | |
298 | break |
|
303 | break | |
299 |
|
304 | |||
300 | datafile = 1 |
|
305 | datafile = 1 | |
301 | if filename is None: |
|
306 | if filename is None: | |
302 | filename = make_filename(args) |
|
307 | filename = make_filename(args) | |
303 | datafile = 1 |
|
308 | datafile = 1 | |
304 | warn('Could not find file where `%s` is defined.\n' |
|
309 | warn('Could not find file where `%s` is defined.\n' | |
305 | 'Opening a file named `%s`' % (args, filename)) |
|
310 | 'Opening a file named `%s`' % (args, filename)) | |
306 | # Now, make sure we can actually read the source (if it was |
|
311 | # Now, make sure we can actually read the source (if it was | |
307 | # in a temp file it's gone by now). |
|
312 | # in a temp file it's gone by now). | |
308 | if datafile: |
|
313 | if datafile: | |
309 | if lineno is None: |
|
314 | if lineno is None: | |
310 | lineno = find_source_lines(data) |
|
315 | lineno = find_source_lines(data) | |
311 | if lineno is None: |
|
316 | if lineno is None: | |
312 | filename = make_filename(args) |
|
317 | filename = make_filename(args) | |
313 | if filename is None: |
|
318 | if filename is None: | |
314 | warn('The file `%s` where `%s` was defined ' |
|
319 | warn('The file `%s` where `%s` was defined ' | |
315 | 'cannot be read.' % (filename, data)) |
|
320 | 'cannot be read.' % (filename, data)) | |
316 | return |
|
321 | return | |
317 | use_temp = False |
|
322 | use_temp = False | |
318 |
|
323 | |||
319 | if use_temp: |
|
324 | if use_temp: | |
320 | filename = shell.mktempfile(data) |
|
325 | filename = shell.mktempfile(data) | |
321 | print 'IPython will make a temporary file named:',filename |
|
326 | print 'IPython will make a temporary file named:',filename | |
322 |
|
327 | |||
323 | return filename, lineno, use_temp |
|
328 | return filename, lineno, use_temp | |
324 |
|
329 | |||
325 | def _edit_macro(self,mname,macro): |
|
330 | def _edit_macro(self,mname,macro): | |
326 | """open an editor with the macro data in a file""" |
|
331 | """open an editor with the macro data in a file""" | |
327 | filename = self.shell.mktempfile(macro.value) |
|
332 | filename = self.shell.mktempfile(macro.value) | |
328 | self.shell.hooks.editor(filename) |
|
333 | self.shell.hooks.editor(filename) | |
329 |
|
334 | |||
330 | # and make a new macro object, to replace the old one |
|
335 | # and make a new macro object, to replace the old one | |
331 | mfile = open(filename) |
|
336 | mfile = open(filename) | |
332 | mvalue = mfile.read() |
|
337 | mvalue = mfile.read() | |
333 | mfile.close() |
|
338 | mfile.close() | |
334 | self.shell.user_ns[mname] = Macro(mvalue) |
|
339 | self.shell.user_ns[mname] = Macro(mvalue) | |
335 |
|
340 | |||
336 | @skip_doctest |
|
341 | @skip_doctest | |
337 | @line_magic |
|
342 | @line_magic | |
338 | def edit(self, parameter_s='',last_call=['','']): |
|
343 | def edit(self, parameter_s='',last_call=['','']): | |
339 | """Bring up an editor and execute the resulting code. |
|
344 | """Bring up an editor and execute the resulting code. | |
340 |
|
345 | |||
341 | Usage: |
|
346 | Usage: | |
342 | %edit [options] [args] |
|
347 | %edit [options] [args] | |
343 |
|
348 | |||
344 | %edit runs IPython's editor hook. The default version of this hook is |
|
349 | %edit runs IPython's editor hook. The default version of this hook is | |
345 | set to call the editor specified by your $EDITOR environment variable. |
|
350 | set to call the editor specified by your $EDITOR environment variable. | |
346 | If this isn't found, it will default to vi under Linux/Unix and to |
|
351 | If this isn't found, it will default to vi under Linux/Unix and to | |
347 | notepad under Windows. See the end of this docstring for how to change |
|
352 | notepad under Windows. See the end of this docstring for how to change | |
348 | the editor hook. |
|
353 | the editor hook. | |
349 |
|
354 | |||
350 | You can also set the value of this editor via the |
|
355 | You can also set the value of this editor via the | |
351 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
356 | ``TerminalInteractiveShell.editor`` option in your configuration file. | |
352 | This is useful if you wish to use a different editor from your typical |
|
357 | This is useful if you wish to use a different editor from your typical | |
353 | default with IPython (and for Windows users who typically don't set |
|
358 | default with IPython (and for Windows users who typically don't set | |
354 | environment variables). |
|
359 | environment variables). | |
355 |
|
360 | |||
356 | This command allows you to conveniently edit multi-line code right in |
|
361 | This command allows you to conveniently edit multi-line code right in | |
357 | your IPython session. |
|
362 | your IPython session. | |
358 |
|
363 | |||
359 | If called without arguments, %edit opens up an empty editor with a |
|
364 | If called without arguments, %edit opens up an empty editor with a | |
360 | temporary file and will execute the contents of this file when you |
|
365 | temporary file and will execute the contents of this file when you | |
361 | close it (don't forget to save it!). |
|
366 | close it (don't forget to save it!). | |
362 |
|
367 | |||
363 |
|
368 | |||
364 | Options: |
|
369 | Options: | |
365 |
|
370 | |||
366 | -n <number>: open the editor at a specified line number. By default, |
|
371 | -n <number>: open the editor at a specified line number. By default, | |
367 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
372 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
368 | you can configure this by providing your own modified hook if your |
|
373 | you can configure this by providing your own modified hook if your | |
369 | favorite editor supports line-number specifications with a different |
|
374 | favorite editor supports line-number specifications with a different | |
370 | syntax. |
|
375 | syntax. | |
371 |
|
376 | |||
372 | -p: this will call the editor with the same data as the previous time |
|
377 | -p: this will call the editor with the same data as the previous time | |
373 | it was used, regardless of how long ago (in your current session) it |
|
378 | it was used, regardless of how long ago (in your current session) it | |
374 | was. |
|
379 | was. | |
375 |
|
380 | |||
376 | -r: use 'raw' input. This option only applies to input taken from the |
|
381 | -r: use 'raw' input. This option only applies to input taken from the | |
377 | user's history. By default, the 'processed' history is used, so that |
|
382 | user's history. By default, the 'processed' history is used, so that | |
378 | magics are loaded in their transformed version to valid Python. If |
|
383 | magics are loaded in their transformed version to valid Python. If | |
379 | this option is given, the raw input as typed as the command line is |
|
384 | this option is given, the raw input as typed as the command line is | |
380 | used instead. When you exit the editor, it will be executed by |
|
385 | used instead. When you exit the editor, it will be executed by | |
381 | IPython's own processor. |
|
386 | IPython's own processor. | |
382 |
|
387 | |||
383 | -x: do not execute the edited code immediately upon exit. This is |
|
388 | -x: do not execute the edited code immediately upon exit. This is | |
384 | mainly useful if you are editing programs which need to be called with |
|
389 | mainly useful if you are editing programs which need to be called with | |
385 | command line arguments, which you can then do using %run. |
|
390 | command line arguments, which you can then do using %run. | |
386 |
|
391 | |||
387 |
|
392 | |||
388 | Arguments: |
|
393 | Arguments: | |
389 |
|
394 | |||
390 | If arguments are given, the following possibilities exist: |
|
395 | If arguments are given, the following possibilities exist: | |
391 |
|
396 | |||
392 | - If the argument is a filename, IPython will load that into the |
|
397 | - If the argument is a filename, IPython will load that into the | |
393 | editor. It will execute its contents with execfile() when you exit, |
|
398 | editor. It will execute its contents with execfile() when you exit, | |
394 | loading any code in the file into your interactive namespace. |
|
399 | loading any code in the file into your interactive namespace. | |
395 |
|
400 | |||
396 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
401 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
397 | The syntax is the same as in the %history magic. |
|
402 | The syntax is the same as in the %history magic. | |
398 |
|
403 | |||
399 | - If the argument is a string variable, its contents are loaded |
|
404 | - If the argument is a string variable, its contents are loaded | |
400 | into the editor. You can thus edit any string which contains |
|
405 | into the editor. You can thus edit any string which contains | |
401 | python code (including the result of previous edits). |
|
406 | python code (including the result of previous edits). | |
402 |
|
407 | |||
403 | - If the argument is the name of an object (other than a string), |
|
408 | - If the argument is the name of an object (other than a string), | |
404 | IPython will try to locate the file where it was defined and open the |
|
409 | IPython will try to locate the file where it was defined and open the | |
405 | editor at the point where it is defined. You can use `%edit function` |
|
410 | editor at the point where it is defined. You can use `%edit function` | |
406 | to load an editor exactly at the point where 'function' is defined, |
|
411 | to load an editor exactly at the point where 'function' is defined, | |
407 | edit it and have the file be executed automatically. |
|
412 | edit it and have the file be executed automatically. | |
408 |
|
413 | |||
409 | - If the object is a macro (see %macro for details), this opens up your |
|
414 | - If the object is a macro (see %macro for details), this opens up your | |
410 | specified editor with a temporary file containing the macro's data. |
|
415 | specified editor with a temporary file containing the macro's data. | |
411 | Upon exit, the macro is reloaded with the contents of the file. |
|
416 | Upon exit, the macro is reloaded with the contents of the file. | |
412 |
|
417 | |||
413 | Note: opening at an exact line is only supported under Unix, and some |
|
418 | Note: opening at an exact line is only supported under Unix, and some | |
414 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
419 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
415 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
420 | '+NUMBER' parameter necessary for this feature. Good editors like | |
416 | (X)Emacs, vi, jed, pico and joe all do. |
|
421 | (X)Emacs, vi, jed, pico and joe all do. | |
417 |
|
422 | |||
418 | After executing your code, %edit will return as output the code you |
|
423 | After executing your code, %edit will return as output the code you | |
419 | typed in the editor (except when it was an existing file). This way |
|
424 | typed in the editor (except when it was an existing file). This way | |
420 | you can reload the code in further invocations of %edit as a variable, |
|
425 | you can reload the code in further invocations of %edit as a variable, | |
421 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
426 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
422 | the output. |
|
427 | the output. | |
423 |
|
428 | |||
424 | Note that %edit is also available through the alias %ed. |
|
429 | Note that %edit is also available through the alias %ed. | |
425 |
|
430 | |||
426 | This is an example of creating a simple function inside the editor and |
|
431 | This is an example of creating a simple function inside the editor and | |
427 | then modifying it. First, start up the editor:: |
|
432 | then modifying it. First, start up the editor:: | |
428 |
|
433 | |||
429 | In [1]: edit |
|
434 | In [1]: edit | |
430 | Editing... done. Executing edited code... |
|
435 | Editing... done. Executing edited code... | |
431 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
436 | Out[1]: 'def foo():\\n print "foo() was defined in an editing | |
432 | session"\\n' |
|
437 | session"\\n' | |
433 |
|
438 | |||
434 | We can then call the function foo():: |
|
439 | We can then call the function foo():: | |
435 |
|
440 | |||
436 | In [2]: foo() |
|
441 | In [2]: foo() | |
437 | foo() was defined in an editing session |
|
442 | foo() was defined in an editing session | |
438 |
|
443 | |||
439 | Now we edit foo. IPython automatically loads the editor with the |
|
444 | Now we edit foo. IPython automatically loads the editor with the | |
440 | (temporary) file where foo() was previously defined:: |
|
445 | (temporary) file where foo() was previously defined:: | |
441 |
|
446 | |||
442 | In [3]: edit foo |
|
447 | In [3]: edit foo | |
443 | Editing... done. Executing edited code... |
|
448 | Editing... done. Executing edited code... | |
444 |
|
449 | |||
445 | And if we call foo() again we get the modified version:: |
|
450 | And if we call foo() again we get the modified version:: | |
446 |
|
451 | |||
447 | In [4]: foo() |
|
452 | In [4]: foo() | |
448 | foo() has now been changed! |
|
453 | foo() has now been changed! | |
449 |
|
454 | |||
450 | Here is an example of how to edit a code snippet successive |
|
455 | Here is an example of how to edit a code snippet successive | |
451 | times. First we call the editor:: |
|
456 | times. First we call the editor:: | |
452 |
|
457 | |||
453 | In [5]: edit |
|
458 | In [5]: edit | |
454 | Editing... done. Executing edited code... |
|
459 | Editing... done. Executing edited code... | |
455 | hello |
|
460 | hello | |
456 | Out[5]: "print 'hello'\\n" |
|
461 | Out[5]: "print 'hello'\\n" | |
457 |
|
462 | |||
458 | Now we call it again with the previous output (stored in _):: |
|
463 | Now we call it again with the previous output (stored in _):: | |
459 |
|
464 | |||
460 | In [6]: edit _ |
|
465 | In [6]: edit _ | |
461 | Editing... done. Executing edited code... |
|
466 | Editing... done. Executing edited code... | |
462 | hello world |
|
467 | hello world | |
463 | Out[6]: "print 'hello world'\\n" |
|
468 | Out[6]: "print 'hello world'\\n" | |
464 |
|
469 | |||
465 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
470 | Now we call it with the output #8 (stored in _8, also as Out[8]):: | |
466 |
|
471 | |||
467 | In [7]: edit _8 |
|
472 | In [7]: edit _8 | |
468 | Editing... done. Executing edited code... |
|
473 | Editing... done. Executing edited code... | |
469 | hello again |
|
474 | hello again | |
470 | Out[7]: "print 'hello again'\\n" |
|
475 | Out[7]: "print 'hello again'\\n" | |
471 |
|
476 | |||
472 |
|
477 | |||
473 | Changing the default editor hook: |
|
478 | Changing the default editor hook: | |
474 |
|
479 | |||
475 | If you wish to write your own editor hook, you can put it in a |
|
480 | If you wish to write your own editor hook, you can put it in a | |
476 | configuration file which you load at startup time. The default hook |
|
481 | configuration file which you load at startup time. The default hook | |
477 | is defined in the IPython.core.hooks module, and you can use that as a |
|
482 | is defined in the IPython.core.hooks module, and you can use that as a | |
478 | starting example for further modifications. That file also has |
|
483 | starting example for further modifications. That file also has | |
479 | general instructions on how to set a new hook for use once you've |
|
484 | general instructions on how to set a new hook for use once you've | |
480 | defined it.""" |
|
485 | defined it.""" | |
481 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
486 | opts,args = self.parse_options(parameter_s,'prxn:') | |
482 |
|
487 | |||
483 | try: |
|
488 | try: | |
484 | filename, lineno, is_temp = self._find_edit_target(self.shell, |
|
489 | filename, lineno, is_temp = self._find_edit_target(self.shell, | |
485 | args, opts, last_call) |
|
490 | args, opts, last_call) | |
486 | except MacroToEdit as e: |
|
491 | except MacroToEdit as e: | |
487 | self._edit_macro(args, e.args[0]) |
|
492 | self._edit_macro(args, e.args[0]) | |
488 | return |
|
493 | return | |
489 |
|
494 | |||
490 | # do actual editing here |
|
495 | # do actual editing here | |
491 | print 'Editing...', |
|
496 | print 'Editing...', | |
492 | sys.stdout.flush() |
|
497 | sys.stdout.flush() | |
493 | try: |
|
498 | try: | |
494 | # Quote filenames that may have spaces in them |
|
499 | # Quote filenames that may have spaces in them | |
495 | if ' ' in filename: |
|
500 | if ' ' in filename: | |
496 | filename = "'%s'" % filename |
|
501 | filename = "'%s'" % filename | |
497 | self.shell.hooks.editor(filename,lineno) |
|
502 | self.shell.hooks.editor(filename,lineno) | |
498 | except TryNext: |
|
503 | except TryNext: | |
499 | warn('Could not open editor') |
|
504 | warn('Could not open editor') | |
500 | return |
|
505 | return | |
501 |
|
506 | |||
502 | # XXX TODO: should this be generalized for all string vars? |
|
507 | # XXX TODO: should this be generalized for all string vars? | |
503 | # For now, this is special-cased to blocks created by cpaste |
|
508 | # For now, this is special-cased to blocks created by cpaste | |
504 | if args.strip() == 'pasted_block': |
|
509 | if args.strip() == 'pasted_block': | |
505 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
510 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
506 |
|
511 | |||
507 | if 'x' in opts: # -x prevents actual execution |
|
512 | if 'x' in opts: # -x prevents actual execution | |
508 |
|
513 | |||
509 | else: |
|
514 | else: | |
510 | print 'done. Executing edited code...' |
|
515 | print 'done. Executing edited code...' | |
511 | if 'r' in opts: # Untranslated IPython code |
|
516 | if 'r' in opts: # Untranslated IPython code | |
512 | self.shell.run_cell(file_read(filename), |
|
517 | self.shell.run_cell(file_read(filename), | |
513 | store_history=False) |
|
518 | store_history=False) | |
514 | else: |
|
519 | else: | |
515 | self.shell.safe_execfile(filename, self.shell.user_ns, |
|
520 | self.shell.safe_execfile(filename, self.shell.user_ns, | |
516 | self.shell.user_ns) |
|
521 | self.shell.user_ns) | |
517 |
|
522 | |||
518 | if is_temp: |
|
523 | if is_temp: | |
519 | try: |
|
524 | try: | |
520 | return open(filename).read() |
|
525 | return open(filename).read() | |
521 | except IOError as msg: |
|
526 | except IOError as msg: | |
522 | if msg.filename == filename: |
|
527 | if msg.filename == filename: | |
523 | warn('File not found. Did you forget to save?') |
|
528 | warn('File not found. Did you forget to save?') | |
524 | return |
|
529 | return | |
525 | else: |
|
530 | else: | |
526 | self.shell.showtraceback() |
|
531 | self.shell.showtraceback() |
@@ -1,69 +1,76 b'' | |||||
1 | """Implementation of magic functions for the extension machinery. |
|
1 | """Implementation of magic functions for the extension machinery. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Stdlib |
|
15 | # Stdlib | |
16 | import os |
|
16 | import os | |
17 |
|
17 | |||
18 | # Our own packages |
|
18 | # Our own packages | |
|
19 | from IPython.core.error import UsageError | |||
19 | from IPython.core.magic import Magics, magics_class, line_magic |
|
20 | from IPython.core.magic import Magics, magics_class, line_magic | |
20 |
|
21 | |||
21 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
22 | # Magic implementation classes |
|
23 | # Magic implementation classes | |
23 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
24 |
|
25 | |||
25 | @magics_class |
|
26 | @magics_class | |
26 | class ExtensionMagics(Magics): |
|
27 | class ExtensionMagics(Magics): | |
27 | """Magics to manage the IPython extensions system.""" |
|
28 | """Magics to manage the IPython extensions system.""" | |
28 |
|
29 | |||
29 | @line_magic |
|
30 | @line_magic | |
30 | def install_ext(self, parameter_s=''): |
|
31 | def install_ext(self, parameter_s=''): | |
31 | """Download and install an extension from a URL, e.g.:: |
|
32 | """Download and install an extension from a URL, e.g.:: | |
32 |
|
33 | |||
33 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py |
|
34 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py | |
34 |
|
35 | |||
35 | The URL should point to an importable Python module - either a .py file |
|
36 | The URL should point to an importable Python module - either a .py file | |
36 | or a .zip file. |
|
37 | or a .zip file. | |
37 |
|
38 | |||
38 | Parameters: |
|
39 | Parameters: | |
39 |
|
40 | |||
40 | -n filename : Specify a name for the file, rather than taking it from |
|
41 | -n filename : Specify a name for the file, rather than taking it from | |
41 | the URL. |
|
42 | the URL. | |
42 | """ |
|
43 | """ | |
43 | opts, args = self.parse_options(parameter_s, 'n:') |
|
44 | opts, args = self.parse_options(parameter_s, 'n:') | |
44 | try: |
|
45 | try: | |
45 | filename = self.shell.extension_manager.install_extension(args, |
|
46 | filename = self.shell.extension_manager.install_extension(args, | |
46 | opts.get('n')) |
|
47 | opts.get('n')) | |
47 | except ValueError as e: |
|
48 | except ValueError as e: | |
48 | print e |
|
49 | print e | |
49 | return |
|
50 | return | |
50 |
|
51 | |||
51 | filename = os.path.basename(filename) |
|
52 | filename = os.path.basename(filename) | |
52 | print "Installed %s. To use it, type:" % filename |
|
53 | print "Installed %s. To use it, type:" % filename | |
53 | print " %%load_ext %s" % os.path.splitext(filename)[0] |
|
54 | print " %%load_ext %s" % os.path.splitext(filename)[0] | |
54 |
|
55 | |||
55 |
|
56 | |||
56 | @line_magic |
|
57 | @line_magic | |
57 | def load_ext(self, module_str): |
|
58 | def load_ext(self, module_str): | |
58 | """Load an IPython extension by its module name.""" |
|
59 | """Load an IPython extension by its module name.""" | |
|
60 | if not module_str: | |||
|
61 | raise UsageError('Missing module name.') | |||
59 | return self.shell.extension_manager.load_extension(module_str) |
|
62 | return self.shell.extension_manager.load_extension(module_str) | |
60 |
|
63 | |||
61 | @line_magic |
|
64 | @line_magic | |
62 | def unload_ext(self, module_str): |
|
65 | def unload_ext(self, module_str): | |
63 | """Unload an IPython extension by its module name.""" |
|
66 | """Unload an IPython extension by its module name.""" | |
|
67 | if not module_str: | |||
|
68 | raise UsageError('Missing module name.') | |||
64 | self.shell.extension_manager.unload_extension(module_str) |
|
69 | self.shell.extension_manager.unload_extension(module_str) | |
65 |
|
70 | |||
66 | @line_magic |
|
71 | @line_magic | |
67 | def reload_ext(self, module_str): |
|
72 | def reload_ext(self, module_str): | |
68 | """Reload an IPython extension by its module name.""" |
|
73 | """Reload an IPython extension by its module name.""" | |
|
74 | if not module_str: | |||
|
75 | raise UsageError('Missing module name.') | |||
69 | self.shell.extension_manager.reload_extension(module_str) |
|
76 | self.shell.extension_manager.reload_extension(module_str) |
@@ -1,700 +1,702 b'' | |||||
1 | """Implementation of namespace-related magic functions. |
|
1 | """Implementation of namespace-related magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Stdlib |
|
15 | # Stdlib | |
16 | import gc |
|
16 | import gc | |
17 | import re |
|
17 | import re | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | # Our own packages |
|
20 | # Our own packages | |
21 | from IPython.core import page |
|
21 | from IPython.core import page | |
22 | from IPython.core.error import StdinNotImplementedError |
|
22 | from IPython.core.error import StdinNotImplementedError, UsageError | |
23 | from IPython.core.magic import Magics, magics_class, line_magic |
|
23 | from IPython.core.magic import Magics, magics_class, line_magic | |
24 | from IPython.testing.skipdoctest import skip_doctest |
|
24 | from IPython.testing.skipdoctest import skip_doctest | |
25 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
25 | from IPython.utils.encoding import DEFAULT_ENCODING | |
26 | from IPython.utils.path import get_py_filename |
|
26 | from IPython.utils.path import get_py_filename | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Magic implementation classes |
|
29 | # Magic implementation classes | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | @magics_class |
|
32 | @magics_class | |
33 | class NamespaceMagics(Magics): |
|
33 | class NamespaceMagics(Magics): | |
34 | """Magics to manage various aspects of the user's namespace. |
|
34 | """Magics to manage various aspects of the user's namespace. | |
35 |
|
35 | |||
36 | These include listing variables, introspecting into them, etc. |
|
36 | These include listing variables, introspecting into them, etc. | |
37 | """ |
|
37 | """ | |
38 |
|
38 | |||
39 | @line_magic |
|
39 | @line_magic | |
40 | def pinfo(self, parameter_s='', namespaces=None): |
|
40 | def pinfo(self, parameter_s='', namespaces=None): | |
41 | """Provide detailed information about an object. |
|
41 | """Provide detailed information about an object. | |
42 |
|
42 | |||
43 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
43 | '%pinfo object' is just a synonym for object? or ?object.""" | |
44 |
|
44 | |||
45 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
45 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
46 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
46 | # detail_level: 0 -> obj? , 1 -> obj?? | |
47 | detail_level = 0 |
|
47 | detail_level = 0 | |
48 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
48 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
49 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
49 | # happen if the user types 'pinfo foo?' at the cmd line. | |
50 | pinfo,qmark1,oname,qmark2 = \ |
|
50 | pinfo,qmark1,oname,qmark2 = \ | |
51 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
51 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
52 | if pinfo or qmark1 or qmark2: |
|
52 | if pinfo or qmark1 or qmark2: | |
53 | detail_level = 1 |
|
53 | detail_level = 1 | |
54 | if "*" in oname: |
|
54 | if "*" in oname: | |
55 | self.psearch(oname) |
|
55 | self.psearch(oname) | |
56 | else: |
|
56 | else: | |
57 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
57 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
58 | namespaces=namespaces) |
|
58 | namespaces=namespaces) | |
59 |
|
59 | |||
60 | @line_magic |
|
60 | @line_magic | |
61 | def pinfo2(self, parameter_s='', namespaces=None): |
|
61 | def pinfo2(self, parameter_s='', namespaces=None): | |
62 | """Provide extra detailed information about an object. |
|
62 | """Provide extra detailed information about an object. | |
63 |
|
63 | |||
64 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
64 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
65 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
65 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
66 | namespaces=namespaces) |
|
66 | namespaces=namespaces) | |
67 |
|
67 | |||
68 | @skip_doctest |
|
68 | @skip_doctest | |
69 | @line_magic |
|
69 | @line_magic | |
70 | def pdef(self, parameter_s='', namespaces=None): |
|
70 | def pdef(self, parameter_s='', namespaces=None): | |
71 | """Print the definition header for any callable object. |
|
71 | """Print the definition header for any callable object. | |
72 |
|
72 | |||
73 | If the object is a class, print the constructor information. |
|
73 | If the object is a class, print the constructor information. | |
74 |
|
74 | |||
75 | Examples |
|
75 | Examples | |
76 | -------- |
|
76 | -------- | |
77 | :: |
|
77 | :: | |
78 |
|
78 | |||
79 | In [3]: %pdef urllib.urlopen |
|
79 | In [3]: %pdef urllib.urlopen | |
80 | urllib.urlopen(url, data=None, proxies=None) |
|
80 | urllib.urlopen(url, data=None, proxies=None) | |
81 | """ |
|
81 | """ | |
82 | self.shell._inspect('pdef',parameter_s, namespaces) |
|
82 | self.shell._inspect('pdef',parameter_s, namespaces) | |
83 |
|
83 | |||
84 | @line_magic |
|
84 | @line_magic | |
85 | def pdoc(self, parameter_s='', namespaces=None): |
|
85 | def pdoc(self, parameter_s='', namespaces=None): | |
86 | """Print the docstring for an object. |
|
86 | """Print the docstring for an object. | |
87 |
|
87 | |||
88 | If the given object is a class, it will print both the class and the |
|
88 | If the given object is a class, it will print both the class and the | |
89 | constructor docstrings.""" |
|
89 | constructor docstrings.""" | |
90 | self.shell._inspect('pdoc',parameter_s, namespaces) |
|
90 | self.shell._inspect('pdoc',parameter_s, namespaces) | |
91 |
|
91 | |||
92 | @line_magic |
|
92 | @line_magic | |
93 | def psource(self, parameter_s='', namespaces=None): |
|
93 | def psource(self, parameter_s='', namespaces=None): | |
94 | """Print (or run through pager) the source code for an object.""" |
|
94 | """Print (or run through pager) the source code for an object.""" | |
|
95 | if not parameter_s: | |||
|
96 | raise UsageError('Missing object name.') | |||
95 | self.shell._inspect('psource',parameter_s, namespaces) |
|
97 | self.shell._inspect('psource',parameter_s, namespaces) | |
96 |
|
98 | |||
97 | @line_magic |
|
99 | @line_magic | |
98 | def pfile(self, parameter_s=''): |
|
100 | def pfile(self, parameter_s=''): | |
99 | """Print (or run through pager) the file where an object is defined. |
|
101 | """Print (or run through pager) the file where an object is defined. | |
100 |
|
102 | |||
101 | The file opens at the line where the object definition begins. IPython |
|
103 | The file opens at the line where the object definition begins. IPython | |
102 | will honor the environment variable PAGER if set, and otherwise will |
|
104 | will honor the environment variable PAGER if set, and otherwise will | |
103 | do its best to print the file in a convenient form. |
|
105 | do its best to print the file in a convenient form. | |
104 |
|
106 | |||
105 | If the given argument is not an object currently defined, IPython will |
|
107 | If the given argument is not an object currently defined, IPython will | |
106 | try to interpret it as a filename (automatically adding a .py extension |
|
108 | try to interpret it as a filename (automatically adding a .py extension | |
107 | if needed). You can thus use %pfile as a syntax highlighting code |
|
109 | if needed). You can thus use %pfile as a syntax highlighting code | |
108 | viewer.""" |
|
110 | viewer.""" | |
109 |
|
111 | |||
110 | # first interpret argument as an object name |
|
112 | # first interpret argument as an object name | |
111 | out = self.shell._inspect('pfile',parameter_s) |
|
113 | out = self.shell._inspect('pfile',parameter_s) | |
112 | # if not, try the input as a filename |
|
114 | # if not, try the input as a filename | |
113 | if out == 'not found': |
|
115 | if out == 'not found': | |
114 | try: |
|
116 | try: | |
115 | filename = get_py_filename(parameter_s) |
|
117 | filename = get_py_filename(parameter_s) | |
116 | except IOError as msg: |
|
118 | except IOError as msg: | |
117 | print msg |
|
119 | print msg | |
118 | return |
|
120 | return | |
119 | page.page(self.shell.inspector.format(open(filename).read())) |
|
121 | page.page(self.shell.inspector.format(open(filename).read())) | |
120 |
|
122 | |||
121 | @line_magic |
|
123 | @line_magic | |
122 | def psearch(self, parameter_s=''): |
|
124 | def psearch(self, parameter_s=''): | |
123 | """Search for object in namespaces by wildcard. |
|
125 | """Search for object in namespaces by wildcard. | |
124 |
|
126 | |||
125 | %psearch [options] PATTERN [OBJECT TYPE] |
|
127 | %psearch [options] PATTERN [OBJECT TYPE] | |
126 |
|
128 | |||
127 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
129 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
128 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
130 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
129 | rest of the command line must be unchanged (options come first), so |
|
131 | rest of the command line must be unchanged (options come first), so | |
130 | for example the following forms are equivalent |
|
132 | for example the following forms are equivalent | |
131 |
|
133 | |||
132 | %psearch -i a* function |
|
134 | %psearch -i a* function | |
133 | -i a* function? |
|
135 | -i a* function? | |
134 | ?-i a* function |
|
136 | ?-i a* function | |
135 |
|
137 | |||
136 | Arguments: |
|
138 | Arguments: | |
137 |
|
139 | |||
138 | PATTERN |
|
140 | PATTERN | |
139 |
|
141 | |||
140 | where PATTERN is a string containing * as a wildcard similar to its |
|
142 | where PATTERN is a string containing * as a wildcard similar to its | |
141 | use in a shell. The pattern is matched in all namespaces on the |
|
143 | use in a shell. The pattern is matched in all namespaces on the | |
142 | search path. By default objects starting with a single _ are not |
|
144 | search path. By default objects starting with a single _ are not | |
143 | matched, many IPython generated objects have a single |
|
145 | matched, many IPython generated objects have a single | |
144 | underscore. The default is case insensitive matching. Matching is |
|
146 | underscore. The default is case insensitive matching. Matching is | |
145 | also done on the attributes of objects and not only on the objects |
|
147 | also done on the attributes of objects and not only on the objects | |
146 | in a module. |
|
148 | in a module. | |
147 |
|
149 | |||
148 | [OBJECT TYPE] |
|
150 | [OBJECT TYPE] | |
149 |
|
151 | |||
150 | Is the name of a python type from the types module. The name is |
|
152 | Is the name of a python type from the types module. The name is | |
151 | given in lowercase without the ending type, ex. StringType is |
|
153 | given in lowercase without the ending type, ex. StringType is | |
152 | written string. By adding a type here only objects matching the |
|
154 | written string. By adding a type here only objects matching the | |
153 | given type are matched. Using all here makes the pattern match all |
|
155 | given type are matched. Using all here makes the pattern match all | |
154 | types (this is the default). |
|
156 | types (this is the default). | |
155 |
|
157 | |||
156 | Options: |
|
158 | Options: | |
157 |
|
159 | |||
158 | -a: makes the pattern match even objects whose names start with a |
|
160 | -a: makes the pattern match even objects whose names start with a | |
159 | single underscore. These names are normally omitted from the |
|
161 | single underscore. These names are normally omitted from the | |
160 | search. |
|
162 | search. | |
161 |
|
163 | |||
162 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
164 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
163 | these options are given, the default is read from your configuration |
|
165 | these options are given, the default is read from your configuration | |
164 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
166 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
165 | If this option is not specified in your configuration file, IPython's |
|
167 | If this option is not specified in your configuration file, IPython's | |
166 | internal default is to do a case sensitive search. |
|
168 | internal default is to do a case sensitive search. | |
167 |
|
169 | |||
168 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
170 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
169 | specify can be searched in any of the following namespaces: |
|
171 | specify can be searched in any of the following namespaces: | |
170 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
172 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
171 | 'builtin' and 'user' are the search defaults. Note that you should |
|
173 | 'builtin' and 'user' are the search defaults. Note that you should | |
172 | not use quotes when specifying namespaces. |
|
174 | not use quotes when specifying namespaces. | |
173 |
|
175 | |||
174 | 'Builtin' contains the python module builtin, 'user' contains all |
|
176 | 'Builtin' contains the python module builtin, 'user' contains all | |
175 | user data, 'alias' only contain the shell aliases and no python |
|
177 | user data, 'alias' only contain the shell aliases and no python | |
176 | objects, 'internal' contains objects used by IPython. The |
|
178 | objects, 'internal' contains objects used by IPython. The | |
177 | 'user_global' namespace is only used by embedded IPython instances, |
|
179 | 'user_global' namespace is only used by embedded IPython instances, | |
178 | and it contains module-level globals. You can add namespaces to the |
|
180 | and it contains module-level globals. You can add namespaces to the | |
179 | search with -s or exclude them with -e (these options can be given |
|
181 | search with -s or exclude them with -e (these options can be given | |
180 | more than once). |
|
182 | more than once). | |
181 |
|
183 | |||
182 | Examples |
|
184 | Examples | |
183 | -------- |
|
185 | -------- | |
184 | :: |
|
186 | :: | |
185 |
|
187 | |||
186 | %psearch a* -> objects beginning with an a |
|
188 | %psearch a* -> objects beginning with an a | |
187 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
189 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
188 | %psearch a* function -> all functions beginning with an a |
|
190 | %psearch a* function -> all functions beginning with an a | |
189 | %psearch re.e* -> objects beginning with an e in module re |
|
191 | %psearch re.e* -> objects beginning with an e in module re | |
190 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
192 | %psearch r*.e* -> objects that start with e in modules starting in r | |
191 | %psearch r*.* string -> all strings in modules beginning with r |
|
193 | %psearch r*.* string -> all strings in modules beginning with r | |
192 |
|
194 | |||
193 | Case sensitive search:: |
|
195 | Case sensitive search:: | |
194 |
|
196 | |||
195 | %psearch -c a* list all object beginning with lower case a |
|
197 | %psearch -c a* list all object beginning with lower case a | |
196 |
|
198 | |||
197 | Show objects beginning with a single _:: |
|
199 | Show objects beginning with a single _:: | |
198 |
|
200 | |||
199 | %psearch -a _* list objects beginning with a single underscore |
|
201 | %psearch -a _* list objects beginning with a single underscore | |
200 | """ |
|
202 | """ | |
201 | try: |
|
203 | try: | |
202 | parameter_s.encode('ascii') |
|
204 | parameter_s.encode('ascii') | |
203 | except UnicodeEncodeError: |
|
205 | except UnicodeEncodeError: | |
204 | print 'Python identifiers can only contain ascii characters.' |
|
206 | print 'Python identifiers can only contain ascii characters.' | |
205 | return |
|
207 | return | |
206 |
|
208 | |||
207 | # default namespaces to be searched |
|
209 | # default namespaces to be searched | |
208 | def_search = ['user_local', 'user_global', 'builtin'] |
|
210 | def_search = ['user_local', 'user_global', 'builtin'] | |
209 |
|
211 | |||
210 | # Process options/args |
|
212 | # Process options/args | |
211 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
213 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
212 | opt = opts.get |
|
214 | opt = opts.get | |
213 | shell = self.shell |
|
215 | shell = self.shell | |
214 | psearch = shell.inspector.psearch |
|
216 | psearch = shell.inspector.psearch | |
215 |
|
217 | |||
216 | # select case options |
|
218 | # select case options | |
217 | if 'i' in opts: |
|
219 | if 'i' in opts: | |
218 | ignore_case = True |
|
220 | ignore_case = True | |
219 | elif 'c' in opts: |
|
221 | elif 'c' in opts: | |
220 | ignore_case = False |
|
222 | ignore_case = False | |
221 | else: |
|
223 | else: | |
222 | ignore_case = not shell.wildcards_case_sensitive |
|
224 | ignore_case = not shell.wildcards_case_sensitive | |
223 |
|
225 | |||
224 | # Build list of namespaces to search from user options |
|
226 | # Build list of namespaces to search from user options | |
225 | def_search.extend(opt('s',[])) |
|
227 | def_search.extend(opt('s',[])) | |
226 | ns_exclude = ns_exclude=opt('e',[]) |
|
228 | ns_exclude = ns_exclude=opt('e',[]) | |
227 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
229 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
228 |
|
230 | |||
229 | # Call the actual search |
|
231 | # Call the actual search | |
230 | try: |
|
232 | try: | |
231 | psearch(args,shell.ns_table,ns_search, |
|
233 | psearch(args,shell.ns_table,ns_search, | |
232 | show_all=opt('a'),ignore_case=ignore_case) |
|
234 | show_all=opt('a'),ignore_case=ignore_case) | |
233 | except: |
|
235 | except: | |
234 | shell.showtraceback() |
|
236 | shell.showtraceback() | |
235 |
|
237 | |||
236 | @skip_doctest |
|
238 | @skip_doctest | |
237 | @line_magic |
|
239 | @line_magic | |
238 | def who_ls(self, parameter_s=''): |
|
240 | def who_ls(self, parameter_s=''): | |
239 | """Return a sorted list of all interactive variables. |
|
241 | """Return a sorted list of all interactive variables. | |
240 |
|
242 | |||
241 | If arguments are given, only variables of types matching these |
|
243 | If arguments are given, only variables of types matching these | |
242 | arguments are returned. |
|
244 | arguments are returned. | |
243 |
|
245 | |||
244 | Examples |
|
246 | Examples | |
245 | -------- |
|
247 | -------- | |
246 |
|
248 | |||
247 | Define two variables and list them with who_ls:: |
|
249 | Define two variables and list them with who_ls:: | |
248 |
|
250 | |||
249 | In [1]: alpha = 123 |
|
251 | In [1]: alpha = 123 | |
250 |
|
252 | |||
251 | In [2]: beta = 'test' |
|
253 | In [2]: beta = 'test' | |
252 |
|
254 | |||
253 | In [3]: %who_ls |
|
255 | In [3]: %who_ls | |
254 | Out[3]: ['alpha', 'beta'] |
|
256 | Out[3]: ['alpha', 'beta'] | |
255 |
|
257 | |||
256 | In [4]: %who_ls int |
|
258 | In [4]: %who_ls int | |
257 | Out[4]: ['alpha'] |
|
259 | Out[4]: ['alpha'] | |
258 |
|
260 | |||
259 | In [5]: %who_ls str |
|
261 | In [5]: %who_ls str | |
260 | Out[5]: ['beta'] |
|
262 | Out[5]: ['beta'] | |
261 | """ |
|
263 | """ | |
262 |
|
264 | |||
263 | user_ns = self.shell.user_ns |
|
265 | user_ns = self.shell.user_ns | |
264 | user_ns_hidden = self.shell.user_ns_hidden |
|
266 | user_ns_hidden = self.shell.user_ns_hidden | |
265 | out = [ i for i in user_ns |
|
267 | out = [ i for i in user_ns | |
266 | if not i.startswith('_') \ |
|
268 | if not i.startswith('_') \ | |
267 | and not i in user_ns_hidden ] |
|
269 | and not i in user_ns_hidden ] | |
268 |
|
270 | |||
269 | typelist = parameter_s.split() |
|
271 | typelist = parameter_s.split() | |
270 | if typelist: |
|
272 | if typelist: | |
271 | typeset = set(typelist) |
|
273 | typeset = set(typelist) | |
272 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
274 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
273 |
|
275 | |||
274 | out.sort() |
|
276 | out.sort() | |
275 | return out |
|
277 | return out | |
276 |
|
278 | |||
277 | @skip_doctest |
|
279 | @skip_doctest | |
278 | @line_magic |
|
280 | @line_magic | |
279 | def who(self, parameter_s=''): |
|
281 | def who(self, parameter_s=''): | |
280 | """Print all interactive variables, with some minimal formatting. |
|
282 | """Print all interactive variables, with some minimal formatting. | |
281 |
|
283 | |||
282 | If any arguments are given, only variables whose type matches one of |
|
284 | If any arguments are given, only variables whose type matches one of | |
283 | these are printed. For example:: |
|
285 | these are printed. For example:: | |
284 |
|
286 | |||
285 | %who function str |
|
287 | %who function str | |
286 |
|
288 | |||
287 | will only list functions and strings, excluding all other types of |
|
289 | will only list functions and strings, excluding all other types of | |
288 | variables. To find the proper type names, simply use type(var) at a |
|
290 | variables. To find the proper type names, simply use type(var) at a | |
289 | command line to see how python prints type names. For example: |
|
291 | command line to see how python prints type names. For example: | |
290 |
|
292 | |||
291 | :: |
|
293 | :: | |
292 |
|
294 | |||
293 | In [1]: type('hello')\\ |
|
295 | In [1]: type('hello')\\ | |
294 | Out[1]: <type 'str'> |
|
296 | Out[1]: <type 'str'> | |
295 |
|
297 | |||
296 | indicates that the type name for strings is 'str'. |
|
298 | indicates that the type name for strings is 'str'. | |
297 |
|
299 | |||
298 | ``%who`` always excludes executed names loaded through your configuration |
|
300 | ``%who`` always excludes executed names loaded through your configuration | |
299 | file and things which are internal to IPython. |
|
301 | file and things which are internal to IPython. | |
300 |
|
302 | |||
301 | This is deliberate, as typically you may load many modules and the |
|
303 | This is deliberate, as typically you may load many modules and the | |
302 | purpose of %who is to show you only what you've manually defined. |
|
304 | purpose of %who is to show you only what you've manually defined. | |
303 |
|
305 | |||
304 | Examples |
|
306 | Examples | |
305 | -------- |
|
307 | -------- | |
306 |
|
308 | |||
307 | Define two variables and list them with who:: |
|
309 | Define two variables and list them with who:: | |
308 |
|
310 | |||
309 | In [1]: alpha = 123 |
|
311 | In [1]: alpha = 123 | |
310 |
|
312 | |||
311 | In [2]: beta = 'test' |
|
313 | In [2]: beta = 'test' | |
312 |
|
314 | |||
313 | In [3]: %who |
|
315 | In [3]: %who | |
314 | alpha beta |
|
316 | alpha beta | |
315 |
|
317 | |||
316 | In [4]: %who int |
|
318 | In [4]: %who int | |
317 | alpha |
|
319 | alpha | |
318 |
|
320 | |||
319 | In [5]: %who str |
|
321 | In [5]: %who str | |
320 | beta |
|
322 | beta | |
321 | """ |
|
323 | """ | |
322 |
|
324 | |||
323 | varlist = self.who_ls(parameter_s) |
|
325 | varlist = self.who_ls(parameter_s) | |
324 | if not varlist: |
|
326 | if not varlist: | |
325 | if parameter_s: |
|
327 | if parameter_s: | |
326 | print 'No variables match your requested type.' |
|
328 | print 'No variables match your requested type.' | |
327 | else: |
|
329 | else: | |
328 | print 'Interactive namespace is empty.' |
|
330 | print 'Interactive namespace is empty.' | |
329 | return |
|
331 | return | |
330 |
|
332 | |||
331 | # if we have variables, move on... |
|
333 | # if we have variables, move on... | |
332 | count = 0 |
|
334 | count = 0 | |
333 | for i in varlist: |
|
335 | for i in varlist: | |
334 | print i+'\t', |
|
336 | print i+'\t', | |
335 | count += 1 |
|
337 | count += 1 | |
336 | if count > 8: |
|
338 | if count > 8: | |
337 | count = 0 |
|
339 | count = 0 | |
338 |
|
340 | |||
339 |
|
341 | |||
340 |
|
342 | |||
341 | @skip_doctest |
|
343 | @skip_doctest | |
342 | @line_magic |
|
344 | @line_magic | |
343 | def whos(self, parameter_s=''): |
|
345 | def whos(self, parameter_s=''): | |
344 | """Like %who, but gives some extra information about each variable. |
|
346 | """Like %who, but gives some extra information about each variable. | |
345 |
|
347 | |||
346 | The same type filtering of %who can be applied here. |
|
348 | The same type filtering of %who can be applied here. | |
347 |
|
349 | |||
348 | For all variables, the type is printed. Additionally it prints: |
|
350 | For all variables, the type is printed. Additionally it prints: | |
349 |
|
351 | |||
350 | - For {},[],(): their length. |
|
352 | - For {},[],(): their length. | |
351 |
|
353 | |||
352 | - For numpy arrays, a summary with shape, number of |
|
354 | - For numpy arrays, a summary with shape, number of | |
353 | elements, typecode and size in memory. |
|
355 | elements, typecode and size in memory. | |
354 |
|
356 | |||
355 | - Everything else: a string representation, snipping their middle if |
|
357 | - Everything else: a string representation, snipping their middle if | |
356 | too long. |
|
358 | too long. | |
357 |
|
359 | |||
358 | Examples |
|
360 | Examples | |
359 | -------- |
|
361 | -------- | |
360 |
|
362 | |||
361 | Define two variables and list them with whos:: |
|
363 | Define two variables and list them with whos:: | |
362 |
|
364 | |||
363 | In [1]: alpha = 123 |
|
365 | In [1]: alpha = 123 | |
364 |
|
366 | |||
365 | In [2]: beta = 'test' |
|
367 | In [2]: beta = 'test' | |
366 |
|
368 | |||
367 | In [3]: %whos |
|
369 | In [3]: %whos | |
368 | Variable Type Data/Info |
|
370 | Variable Type Data/Info | |
369 | -------------------------------- |
|
371 | -------------------------------- | |
370 | alpha int 123 |
|
372 | alpha int 123 | |
371 | beta str test |
|
373 | beta str test | |
372 | """ |
|
374 | """ | |
373 |
|
375 | |||
374 | varnames = self.who_ls(parameter_s) |
|
376 | varnames = self.who_ls(parameter_s) | |
375 | if not varnames: |
|
377 | if not varnames: | |
376 | if parameter_s: |
|
378 | if parameter_s: | |
377 | print 'No variables match your requested type.' |
|
379 | print 'No variables match your requested type.' | |
378 | else: |
|
380 | else: | |
379 | print 'Interactive namespace is empty.' |
|
381 | print 'Interactive namespace is empty.' | |
380 | return |
|
382 | return | |
381 |
|
383 | |||
382 | # if we have variables, move on... |
|
384 | # if we have variables, move on... | |
383 |
|
385 | |||
384 | # for these types, show len() instead of data: |
|
386 | # for these types, show len() instead of data: | |
385 | seq_types = ['dict', 'list', 'tuple'] |
|
387 | seq_types = ['dict', 'list', 'tuple'] | |
386 |
|
388 | |||
387 | # for numpy arrays, display summary info |
|
389 | # for numpy arrays, display summary info | |
388 | ndarray_type = None |
|
390 | ndarray_type = None | |
389 | if 'numpy' in sys.modules: |
|
391 | if 'numpy' in sys.modules: | |
390 | try: |
|
392 | try: | |
391 | from numpy import ndarray |
|
393 | from numpy import ndarray | |
392 | except ImportError: |
|
394 | except ImportError: | |
393 | pass |
|
395 | pass | |
394 | else: |
|
396 | else: | |
395 | ndarray_type = ndarray.__name__ |
|
397 | ndarray_type = ndarray.__name__ | |
396 |
|
398 | |||
397 | # Find all variable names and types so we can figure out column sizes |
|
399 | # Find all variable names and types so we can figure out column sizes | |
398 | def get_vars(i): |
|
400 | def get_vars(i): | |
399 | return self.shell.user_ns[i] |
|
401 | return self.shell.user_ns[i] | |
400 |
|
402 | |||
401 | # some types are well known and can be shorter |
|
403 | # some types are well known and can be shorter | |
402 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
404 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
403 | def type_name(v): |
|
405 | def type_name(v): | |
404 | tn = type(v).__name__ |
|
406 | tn = type(v).__name__ | |
405 | return abbrevs.get(tn,tn) |
|
407 | return abbrevs.get(tn,tn) | |
406 |
|
408 | |||
407 | varlist = map(get_vars,varnames) |
|
409 | varlist = map(get_vars,varnames) | |
408 |
|
410 | |||
409 | typelist = [] |
|
411 | typelist = [] | |
410 | for vv in varlist: |
|
412 | for vv in varlist: | |
411 | tt = type_name(vv) |
|
413 | tt = type_name(vv) | |
412 |
|
414 | |||
413 | if tt=='instance': |
|
415 | if tt=='instance': | |
414 | typelist.append( abbrevs.get(str(vv.__class__), |
|
416 | typelist.append( abbrevs.get(str(vv.__class__), | |
415 | str(vv.__class__))) |
|
417 | str(vv.__class__))) | |
416 | else: |
|
418 | else: | |
417 | typelist.append(tt) |
|
419 | typelist.append(tt) | |
418 |
|
420 | |||
419 | # column labels and # of spaces as separator |
|
421 | # column labels and # of spaces as separator | |
420 | varlabel = 'Variable' |
|
422 | varlabel = 'Variable' | |
421 | typelabel = 'Type' |
|
423 | typelabel = 'Type' | |
422 | datalabel = 'Data/Info' |
|
424 | datalabel = 'Data/Info' | |
423 | colsep = 3 |
|
425 | colsep = 3 | |
424 | # variable format strings |
|
426 | # variable format strings | |
425 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
427 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
426 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
428 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
427 | # find the size of the columns to format the output nicely |
|
429 | # find the size of the columns to format the output nicely | |
428 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
430 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
429 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
431 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
430 | # table header |
|
432 | # table header | |
431 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
433 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
432 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
434 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
433 | # and the table itself |
|
435 | # and the table itself | |
434 | kb = 1024 |
|
436 | kb = 1024 | |
435 | Mb = 1048576 # kb**2 |
|
437 | Mb = 1048576 # kb**2 | |
436 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
438 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
437 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
439 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
438 | if vtype in seq_types: |
|
440 | if vtype in seq_types: | |
439 | print "n="+str(len(var)) |
|
441 | print "n="+str(len(var)) | |
440 | elif vtype == ndarray_type: |
|
442 | elif vtype == ndarray_type: | |
441 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
443 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
442 | if vtype==ndarray_type: |
|
444 | if vtype==ndarray_type: | |
443 | # numpy |
|
445 | # numpy | |
444 | vsize = var.size |
|
446 | vsize = var.size | |
445 | vbytes = vsize*var.itemsize |
|
447 | vbytes = vsize*var.itemsize | |
446 | vdtype = var.dtype |
|
448 | vdtype = var.dtype | |
447 |
|
449 | |||
448 | if vbytes < 100000: |
|
450 | if vbytes < 100000: | |
449 | print aformat % (vshape, vsize, vdtype, vbytes) |
|
451 | print aformat % (vshape, vsize, vdtype, vbytes) | |
450 | else: |
|
452 | else: | |
451 | print aformat % (vshape, vsize, vdtype, vbytes), |
|
453 | print aformat % (vshape, vsize, vdtype, vbytes), | |
452 | if vbytes < Mb: |
|
454 | if vbytes < Mb: | |
453 | print '(%s kb)' % (vbytes/kb,) |
|
455 | print '(%s kb)' % (vbytes/kb,) | |
454 | else: |
|
456 | else: | |
455 | print '(%s Mb)' % (vbytes/Mb,) |
|
457 | print '(%s Mb)' % (vbytes/Mb,) | |
456 | else: |
|
458 | else: | |
457 | try: |
|
459 | try: | |
458 | vstr = str(var) |
|
460 | vstr = str(var) | |
459 | except UnicodeEncodeError: |
|
461 | except UnicodeEncodeError: | |
460 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
462 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |
461 | 'backslashreplace') |
|
463 | 'backslashreplace') | |
462 | except: |
|
464 | except: | |
463 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
465 | vstr = "<object with id %d (str() failed)>" % id(var) | |
464 | vstr = vstr.replace('\n', '\\n') |
|
466 | vstr = vstr.replace('\n', '\\n') | |
465 | if len(vstr) < 50: |
|
467 | if len(vstr) < 50: | |
466 | print vstr |
|
468 | print vstr | |
467 | else: |
|
469 | else: | |
468 | print vstr[:25] + "<...>" + vstr[-25:] |
|
470 | print vstr[:25] + "<...>" + vstr[-25:] | |
469 |
|
471 | |||
470 | @line_magic |
|
472 | @line_magic | |
471 | def reset(self, parameter_s=''): |
|
473 | def reset(self, parameter_s=''): | |
472 | """Resets the namespace by removing all names defined by the user, if |
|
474 | """Resets the namespace by removing all names defined by the user, if | |
473 | called without arguments, or by removing some types of objects, such |
|
475 | called without arguments, or by removing some types of objects, such | |
474 | as everything currently in IPython's In[] and Out[] containers (see |
|
476 | as everything currently in IPython's In[] and Out[] containers (see | |
475 | the parameters for details). |
|
477 | the parameters for details). | |
476 |
|
478 | |||
477 | Parameters |
|
479 | Parameters | |
478 | ---------- |
|
480 | ---------- | |
479 | -f : force reset without asking for confirmation. |
|
481 | -f : force reset without asking for confirmation. | |
480 |
|
482 | |||
481 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
483 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
482 | References to objects may be kept. By default (without this option), |
|
484 | References to objects may be kept. By default (without this option), | |
483 | we do a 'hard' reset, giving you a new session and removing all |
|
485 | we do a 'hard' reset, giving you a new session and removing all | |
484 | references to objects from the current session. |
|
486 | references to objects from the current session. | |
485 |
|
487 | |||
486 | in : reset input history |
|
488 | in : reset input history | |
487 |
|
489 | |||
488 | out : reset output history |
|
490 | out : reset output history | |
489 |
|
491 | |||
490 | dhist : reset directory history |
|
492 | dhist : reset directory history | |
491 |
|
493 | |||
492 | array : reset only variables that are NumPy arrays |
|
494 | array : reset only variables that are NumPy arrays | |
493 |
|
495 | |||
494 | See Also |
|
496 | See Also | |
495 | -------- |
|
497 | -------- | |
496 | magic_reset_selective : invoked as ``%reset_selective`` |
|
498 | magic_reset_selective : invoked as ``%reset_selective`` | |
497 |
|
499 | |||
498 | Examples |
|
500 | Examples | |
499 | -------- |
|
501 | -------- | |
500 | :: |
|
502 | :: | |
501 |
|
503 | |||
502 | In [6]: a = 1 |
|
504 | In [6]: a = 1 | |
503 |
|
505 | |||
504 | In [7]: a |
|
506 | In [7]: a | |
505 | Out[7]: 1 |
|
507 | Out[7]: 1 | |
506 |
|
508 | |||
507 | In [8]: 'a' in _ip.user_ns |
|
509 | In [8]: 'a' in _ip.user_ns | |
508 | Out[8]: True |
|
510 | Out[8]: True | |
509 |
|
511 | |||
510 | In [9]: %reset -f |
|
512 | In [9]: %reset -f | |
511 |
|
513 | |||
512 | In [1]: 'a' in _ip.user_ns |
|
514 | In [1]: 'a' in _ip.user_ns | |
513 | Out[1]: False |
|
515 | Out[1]: False | |
514 |
|
516 | |||
515 | In [2]: %reset -f in |
|
517 | In [2]: %reset -f in | |
516 | Flushing input history |
|
518 | Flushing input history | |
517 |
|
519 | |||
518 | In [3]: %reset -f dhist in |
|
520 | In [3]: %reset -f dhist in | |
519 | Flushing directory history |
|
521 | Flushing directory history | |
520 | Flushing input history |
|
522 | Flushing input history | |
521 |
|
523 | |||
522 | Notes |
|
524 | Notes | |
523 | ----- |
|
525 | ----- | |
524 | Calling this magic from clients that do not implement standard input, |
|
526 | Calling this magic from clients that do not implement standard input, | |
525 | such as the ipython notebook interface, will reset the namespace |
|
527 | such as the ipython notebook interface, will reset the namespace | |
526 | without confirmation. |
|
528 | without confirmation. | |
527 | """ |
|
529 | """ | |
528 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
530 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |
529 | if 'f' in opts: |
|
531 | if 'f' in opts: | |
530 | ans = True |
|
532 | ans = True | |
531 | else: |
|
533 | else: | |
532 | try: |
|
534 | try: | |
533 | ans = self.shell.ask_yes_no( |
|
535 | ans = self.shell.ask_yes_no( | |
534 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", |
|
536 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", | |
535 | default='n') |
|
537 | default='n') | |
536 | except StdinNotImplementedError: |
|
538 | except StdinNotImplementedError: | |
537 | ans = True |
|
539 | ans = True | |
538 | if not ans: |
|
540 | if not ans: | |
539 | print 'Nothing done.' |
|
541 | print 'Nothing done.' | |
540 | return |
|
542 | return | |
541 |
|
543 | |||
542 | if 's' in opts: # Soft reset |
|
544 | if 's' in opts: # Soft reset | |
543 | user_ns = self.shell.user_ns |
|
545 | user_ns = self.shell.user_ns | |
544 | for i in self.who_ls(): |
|
546 | for i in self.who_ls(): | |
545 | del(user_ns[i]) |
|
547 | del(user_ns[i]) | |
546 | elif len(args) == 0: # Hard reset |
|
548 | elif len(args) == 0: # Hard reset | |
547 | self.shell.reset(new_session = False) |
|
549 | self.shell.reset(new_session = False) | |
548 |
|
550 | |||
549 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
551 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |
550 | ip = self.shell |
|
552 | ip = self.shell | |
551 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
553 | user_ns = self.shell.user_ns # local lookup, heavily used | |
552 |
|
554 | |||
553 | for target in args: |
|
555 | for target in args: | |
554 | target = target.lower() # make matches case insensitive |
|
556 | target = target.lower() # make matches case insensitive | |
555 | if target == 'out': |
|
557 | if target == 'out': | |
556 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
558 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
557 | self.shell.displayhook.flush() |
|
559 | self.shell.displayhook.flush() | |
558 |
|
560 | |||
559 | elif target == 'in': |
|
561 | elif target == 'in': | |
560 | print "Flushing input history" |
|
562 | print "Flushing input history" | |
561 | pc = self.shell.displayhook.prompt_count + 1 |
|
563 | pc = self.shell.displayhook.prompt_count + 1 | |
562 | for n in range(1, pc): |
|
564 | for n in range(1, pc): | |
563 | key = '_i'+repr(n) |
|
565 | key = '_i'+repr(n) | |
564 | user_ns.pop(key,None) |
|
566 | user_ns.pop(key,None) | |
565 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
567 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
566 | hm = ip.history_manager |
|
568 | hm = ip.history_manager | |
567 | # don't delete these, as %save and %macro depending on the |
|
569 | # don't delete these, as %save and %macro depending on the | |
568 | # length of these lists to be preserved |
|
570 | # length of these lists to be preserved | |
569 | hm.input_hist_parsed[:] = [''] * pc |
|
571 | hm.input_hist_parsed[:] = [''] * pc | |
570 | hm.input_hist_raw[:] = [''] * pc |
|
572 | hm.input_hist_raw[:] = [''] * pc | |
571 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
573 | # hm has internal machinery for _i,_ii,_iii, clear it out | |
572 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
574 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |
573 |
|
575 | |||
574 | elif target == 'array': |
|
576 | elif target == 'array': | |
575 | # Support cleaning up numpy arrays |
|
577 | # Support cleaning up numpy arrays | |
576 | try: |
|
578 | try: | |
577 | from numpy import ndarray |
|
579 | from numpy import ndarray | |
578 | # This must be done with items and not iteritems because |
|
580 | # This must be done with items and not iteritems because | |
579 | # we're going to modify the dict in-place. |
|
581 | # we're going to modify the dict in-place. | |
580 | for x,val in user_ns.items(): |
|
582 | for x,val in user_ns.items(): | |
581 | if isinstance(val,ndarray): |
|
583 | if isinstance(val,ndarray): | |
582 | del user_ns[x] |
|
584 | del user_ns[x] | |
583 | except ImportError: |
|
585 | except ImportError: | |
584 | print "reset array only works if Numpy is available." |
|
586 | print "reset array only works if Numpy is available." | |
585 |
|
587 | |||
586 | elif target == 'dhist': |
|
588 | elif target == 'dhist': | |
587 | print "Flushing directory history" |
|
589 | print "Flushing directory history" | |
588 | del user_ns['_dh'][:] |
|
590 | del user_ns['_dh'][:] | |
589 |
|
591 | |||
590 | else: |
|
592 | else: | |
591 | print "Don't know how to reset ", |
|
593 | print "Don't know how to reset ", | |
592 | print target + ", please run `%reset?` for details" |
|
594 | print target + ", please run `%reset?` for details" | |
593 |
|
595 | |||
594 | gc.collect() |
|
596 | gc.collect() | |
595 |
|
597 | |||
596 | @line_magic |
|
598 | @line_magic | |
597 | def reset_selective(self, parameter_s=''): |
|
599 | def reset_selective(self, parameter_s=''): | |
598 | """Resets the namespace by removing names defined by the user. |
|
600 | """Resets the namespace by removing names defined by the user. | |
599 |
|
601 | |||
600 | Input/Output history are left around in case you need them. |
|
602 | Input/Output history are left around in case you need them. | |
601 |
|
603 | |||
602 | %reset_selective [-f] regex |
|
604 | %reset_selective [-f] regex | |
603 |
|
605 | |||
604 | No action is taken if regex is not included |
|
606 | No action is taken if regex is not included | |
605 |
|
607 | |||
606 | Options |
|
608 | Options | |
607 | -f : force reset without asking for confirmation. |
|
609 | -f : force reset without asking for confirmation. | |
608 |
|
610 | |||
609 | See Also |
|
611 | See Also | |
610 | -------- |
|
612 | -------- | |
611 | magic_reset : invoked as ``%reset`` |
|
613 | magic_reset : invoked as ``%reset`` | |
612 |
|
614 | |||
613 | Examples |
|
615 | Examples | |
614 | -------- |
|
616 | -------- | |
615 |
|
617 | |||
616 | We first fully reset the namespace so your output looks identical to |
|
618 | We first fully reset the namespace so your output looks identical to | |
617 | this example for pedagogical reasons; in practice you do not need a |
|
619 | this example for pedagogical reasons; in practice you do not need a | |
618 | full reset:: |
|
620 | full reset:: | |
619 |
|
621 | |||
620 | In [1]: %reset -f |
|
622 | In [1]: %reset -f | |
621 |
|
623 | |||
622 | Now, with a clean namespace we can make a few variables and use |
|
624 | Now, with a clean namespace we can make a few variables and use | |
623 | ``%reset_selective`` to only delete names that match our regexp:: |
|
625 | ``%reset_selective`` to only delete names that match our regexp:: | |
624 |
|
626 | |||
625 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
627 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
626 |
|
628 | |||
627 | In [3]: who_ls |
|
629 | In [3]: who_ls | |
628 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
630 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
629 |
|
631 | |||
630 | In [4]: %reset_selective -f b[2-3]m |
|
632 | In [4]: %reset_selective -f b[2-3]m | |
631 |
|
633 | |||
632 | In [5]: who_ls |
|
634 | In [5]: who_ls | |
633 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
635 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
634 |
|
636 | |||
635 | In [6]: %reset_selective -f d |
|
637 | In [6]: %reset_selective -f d | |
636 |
|
638 | |||
637 | In [7]: who_ls |
|
639 | In [7]: who_ls | |
638 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
640 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
639 |
|
641 | |||
640 | In [8]: %reset_selective -f c |
|
642 | In [8]: %reset_selective -f c | |
641 |
|
643 | |||
642 | In [9]: who_ls |
|
644 | In [9]: who_ls | |
643 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
645 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
644 |
|
646 | |||
645 | In [10]: %reset_selective -f b |
|
647 | In [10]: %reset_selective -f b | |
646 |
|
648 | |||
647 | In [11]: who_ls |
|
649 | In [11]: who_ls | |
648 | Out[11]: ['a'] |
|
650 | Out[11]: ['a'] | |
649 |
|
651 | |||
650 | Notes |
|
652 | Notes | |
651 | ----- |
|
653 | ----- | |
652 | Calling this magic from clients that do not implement standard input, |
|
654 | Calling this magic from clients that do not implement standard input, | |
653 | such as the ipython notebook interface, will reset the namespace |
|
655 | such as the ipython notebook interface, will reset the namespace | |
654 | without confirmation. |
|
656 | without confirmation. | |
655 | """ |
|
657 | """ | |
656 |
|
658 | |||
657 | opts, regex = self.parse_options(parameter_s,'f') |
|
659 | opts, regex = self.parse_options(parameter_s,'f') | |
658 |
|
660 | |||
659 | if 'f' in opts: |
|
661 | if 'f' in opts: | |
660 | ans = True |
|
662 | ans = True | |
661 | else: |
|
663 | else: | |
662 | try: |
|
664 | try: | |
663 | ans = self.shell.ask_yes_no( |
|
665 | ans = self.shell.ask_yes_no( | |
664 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
666 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
665 | default='n') |
|
667 | default='n') | |
666 | except StdinNotImplementedError: |
|
668 | except StdinNotImplementedError: | |
667 | ans = True |
|
669 | ans = True | |
668 | if not ans: |
|
670 | if not ans: | |
669 | print 'Nothing done.' |
|
671 | print 'Nothing done.' | |
670 | return |
|
672 | return | |
671 | user_ns = self.shell.user_ns |
|
673 | user_ns = self.shell.user_ns | |
672 | if not regex: |
|
674 | if not regex: | |
673 | print 'No regex pattern specified. Nothing done.' |
|
675 | print 'No regex pattern specified. Nothing done.' | |
674 | return |
|
676 | return | |
675 | else: |
|
677 | else: | |
676 | try: |
|
678 | try: | |
677 | m = re.compile(regex) |
|
679 | m = re.compile(regex) | |
678 | except TypeError: |
|
680 | except TypeError: | |
679 | raise TypeError('regex must be a string or compiled pattern') |
|
681 | raise TypeError('regex must be a string or compiled pattern') | |
680 | for i in self.who_ls(): |
|
682 | for i in self.who_ls(): | |
681 | if m.search(i): |
|
683 | if m.search(i): | |
682 | del(user_ns[i]) |
|
684 | del(user_ns[i]) | |
683 |
|
685 | |||
684 | @line_magic |
|
686 | @line_magic | |
685 | def xdel(self, parameter_s=''): |
|
687 | def xdel(self, parameter_s=''): | |
686 | """Delete a variable, trying to clear it from anywhere that |
|
688 | """Delete a variable, trying to clear it from anywhere that | |
687 | IPython's machinery has references to it. By default, this uses |
|
689 | IPython's machinery has references to it. By default, this uses | |
688 | the identity of the named object in the user namespace to remove |
|
690 | the identity of the named object in the user namespace to remove | |
689 | references held under other names. The object is also removed |
|
691 | references held under other names. The object is also removed | |
690 | from the output history. |
|
692 | from the output history. | |
691 |
|
693 | |||
692 | Options |
|
694 | Options | |
693 | -n : Delete the specified name from all namespaces, without |
|
695 | -n : Delete the specified name from all namespaces, without | |
694 | checking their identity. |
|
696 | checking their identity. | |
695 | """ |
|
697 | """ | |
696 | opts, varname = self.parse_options(parameter_s,'n') |
|
698 | opts, varname = self.parse_options(parameter_s,'n') | |
697 | try: |
|
699 | try: | |
698 | self.shell.del_var(varname, ('n' in opts)) |
|
700 | self.shell.del_var(varname, ('n' in opts)) | |
699 | except (NameError, ValueError) as e: |
|
701 | except (NameError, ValueError) as e: | |
700 | print type(e).__name__ +": "+ str(e) |
|
702 | print type(e).__name__ +": "+ str(e) |
@@ -1,721 +1,724 b'' | |||||
1 | """Implementation of magic functions for interaction with the OS. |
|
1 | """Implementation of magic functions for interaction with the OS. | |
2 |
|
2 | |||
3 | Note: this module is named 'osm' instead of 'os' to avoid a collision with the |
|
3 | Note: this module is named 'osm' instead of 'os' to avoid a collision with the | |
4 | builtin. |
|
4 | builtin. | |
5 | """ |
|
5 | """ | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (c) 2012 The IPython Development Team. |
|
7 | # Copyright (c) 2012 The IPython Development Team. | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the Modified BSD License. |
|
9 | # Distributed under the terms of the Modified BSD License. | |
10 | # |
|
10 | # | |
11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
11 | # The full license is in the file COPYING.txt, distributed with this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import io |
|
19 | import io | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 | import sys |
|
22 | import sys | |
23 | from pprint import pformat |
|
23 | from pprint import pformat | |
24 |
|
24 | |||
25 | # Our own packages |
|
25 | # Our own packages | |
26 | from IPython.core import magic_arguments |
|
26 | from IPython.core import magic_arguments | |
27 | from IPython.core import oinspect |
|
27 | from IPython.core import oinspect | |
28 | from IPython.core import page |
|
28 | from IPython.core import page | |
29 | from IPython.core.error import UsageError, StdinNotImplementedError |
|
29 | from IPython.core.error import UsageError, StdinNotImplementedError | |
30 | from IPython.core.magic import ( |
|
30 | from IPython.core.magic import ( | |
31 | Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic |
|
31 | Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic | |
32 | ) |
|
32 | ) | |
33 | from IPython.testing.skipdoctest import skip_doctest |
|
33 | from IPython.testing.skipdoctest import skip_doctest | |
34 | from IPython.utils.io import file_read, nlprint |
|
34 | from IPython.utils.io import file_read, nlprint | |
35 | from IPython.utils.path import get_py_filename, unquote_filename |
|
35 | from IPython.utils.path import get_py_filename, unquote_filename | |
36 | from IPython.utils.process import abbrev_cwd |
|
36 | from IPython.utils.process import abbrev_cwd | |
37 | from IPython.utils.terminal import set_term_title |
|
37 | from IPython.utils.terminal import set_term_title | |
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Magic implementation classes |
|
39 | # Magic implementation classes | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | @magics_class |
|
41 | @magics_class | |
42 | class OSMagics(Magics): |
|
42 | class OSMagics(Magics): | |
43 | """Magics to interact with the underlying OS (shell-type functionality). |
|
43 | """Magics to interact with the underlying OS (shell-type functionality). | |
44 | """ |
|
44 | """ | |
45 |
|
45 | |||
46 | @skip_doctest |
|
46 | @skip_doctest | |
47 | @line_magic |
|
47 | @line_magic | |
48 | def alias(self, parameter_s=''): |
|
48 | def alias(self, parameter_s=''): | |
49 | """Define an alias for a system command. |
|
49 | """Define an alias for a system command. | |
50 |
|
50 | |||
51 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
51 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
52 |
|
52 | |||
53 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
53 | Then, typing 'alias_name params' will execute the system command 'cmd | |
54 | params' (from your underlying operating system). |
|
54 | params' (from your underlying operating system). | |
55 |
|
55 | |||
56 | Aliases have lower precedence than magic functions and Python normal |
|
56 | Aliases have lower precedence than magic functions and Python normal | |
57 | variables, so if 'foo' is both a Python variable and an alias, the |
|
57 | variables, so if 'foo' is both a Python variable and an alias, the | |
58 | alias can not be executed until 'del foo' removes the Python variable. |
|
58 | alias can not be executed until 'del foo' removes the Python variable. | |
59 |
|
59 | |||
60 | You can use the %l specifier in an alias definition to represent the |
|
60 | You can use the %l specifier in an alias definition to represent the | |
61 | whole line when the alias is called. For example:: |
|
61 | whole line when the alias is called. For example:: | |
62 |
|
62 | |||
63 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
63 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
64 | In [3]: bracket hello world |
|
64 | In [3]: bracket hello world | |
65 | Input in brackets: <hello world> |
|
65 | Input in brackets: <hello world> | |
66 |
|
66 | |||
67 | You can also define aliases with parameters using %s specifiers (one |
|
67 | You can also define aliases with parameters using %s specifiers (one | |
68 | per parameter):: |
|
68 | per parameter):: | |
69 |
|
69 | |||
70 | In [1]: alias parts echo first %s second %s |
|
70 | In [1]: alias parts echo first %s second %s | |
71 | In [2]: %parts A B |
|
71 | In [2]: %parts A B | |
72 | first A second B |
|
72 | first A second B | |
73 | In [3]: %parts A |
|
73 | In [3]: %parts A | |
74 | Incorrect number of arguments: 2 expected. |
|
74 | Incorrect number of arguments: 2 expected. | |
75 | parts is an alias to: 'echo first %s second %s' |
|
75 | parts is an alias to: 'echo first %s second %s' | |
76 |
|
76 | |||
77 | Note that %l and %s are mutually exclusive. You can only use one or |
|
77 | Note that %l and %s are mutually exclusive. You can only use one or | |
78 | the other in your aliases. |
|
78 | the other in your aliases. | |
79 |
|
79 | |||
80 | Aliases expand Python variables just like system calls using ! or !! |
|
80 | Aliases expand Python variables just like system calls using ! or !! | |
81 | do: all expressions prefixed with '$' get expanded. For details of |
|
81 | do: all expressions prefixed with '$' get expanded. For details of | |
82 | the semantic rules, see PEP-215: |
|
82 | the semantic rules, see PEP-215: | |
83 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
83 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
84 | IPython for variable expansion. If you want to access a true shell |
|
84 | IPython for variable expansion. If you want to access a true shell | |
85 | variable, an extra $ is necessary to prevent its expansion by |
|
85 | variable, an extra $ is necessary to prevent its expansion by | |
86 | IPython:: |
|
86 | IPython:: | |
87 |
|
87 | |||
88 | In [6]: alias show echo |
|
88 | In [6]: alias show echo | |
89 | In [7]: PATH='A Python string' |
|
89 | In [7]: PATH='A Python string' | |
90 | In [8]: show $PATH |
|
90 | In [8]: show $PATH | |
91 | A Python string |
|
91 | A Python string | |
92 | In [9]: show $$PATH |
|
92 | In [9]: show $$PATH | |
93 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
93 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
94 |
|
94 | |||
95 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
95 | You can use the alias facility to acess all of $PATH. See the %rehash | |
96 | and %rehashx functions, which automatically create aliases for the |
|
96 | and %rehashx functions, which automatically create aliases for the | |
97 | contents of your $PATH. |
|
97 | contents of your $PATH. | |
98 |
|
98 | |||
99 | If called with no parameters, %alias prints the current alias table.""" |
|
99 | If called with no parameters, %alias prints the current alias table.""" | |
100 |
|
100 | |||
101 | par = parameter_s.strip() |
|
101 | par = parameter_s.strip() | |
102 | if not par: |
|
102 | if not par: | |
103 | aliases = sorted(self.shell.alias_manager.aliases) |
|
103 | aliases = sorted(self.shell.alias_manager.aliases) | |
104 | # stored = self.shell.db.get('stored_aliases', {} ) |
|
104 | # stored = self.shell.db.get('stored_aliases', {} ) | |
105 | # for k, v in stored: |
|
105 | # for k, v in stored: | |
106 | # atab.append(k, v[0]) |
|
106 | # atab.append(k, v[0]) | |
107 |
|
107 | |||
108 | print "Total number of aliases:", len(aliases) |
|
108 | print "Total number of aliases:", len(aliases) | |
109 | sys.stdout.flush() |
|
109 | sys.stdout.flush() | |
110 | return aliases |
|
110 | return aliases | |
111 |
|
111 | |||
112 | # Now try to define a new one |
|
112 | # Now try to define a new one | |
113 | try: |
|
113 | try: | |
114 | alias,cmd = par.split(None, 1) |
|
114 | alias,cmd = par.split(None, 1) | |
115 | except: |
|
115 | except: | |
116 | print oinspect.getdoc(self.alias) |
|
116 | print oinspect.getdoc(self.alias) | |
117 | else: |
|
117 | else: | |
118 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
118 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
119 | # end magic_alias |
|
119 | # end magic_alias | |
120 |
|
120 | |||
121 | @line_magic |
|
121 | @line_magic | |
122 | def unalias(self, parameter_s=''): |
|
122 | def unalias(self, parameter_s=''): | |
123 | """Remove an alias""" |
|
123 | """Remove an alias""" | |
124 |
|
124 | |||
125 | aname = parameter_s.strip() |
|
125 | aname = parameter_s.strip() | |
126 | self.shell.alias_manager.undefine_alias(aname) |
|
126 | self.shell.alias_manager.undefine_alias(aname) | |
127 | stored = self.shell.db.get('stored_aliases', {} ) |
|
127 | stored = self.shell.db.get('stored_aliases', {} ) | |
128 | if aname in stored: |
|
128 | if aname in stored: | |
129 | print "Removing %stored alias",aname |
|
129 | print "Removing %stored alias",aname | |
130 | del stored[aname] |
|
130 | del stored[aname] | |
131 | self.shell.db['stored_aliases'] = stored |
|
131 | self.shell.db['stored_aliases'] = stored | |
132 |
|
132 | |||
133 | @line_magic |
|
133 | @line_magic | |
134 | def rehashx(self, parameter_s=''): |
|
134 | def rehashx(self, parameter_s=''): | |
135 | """Update the alias table with all executable files in $PATH. |
|
135 | """Update the alias table with all executable files in $PATH. | |
136 |
|
136 | |||
137 | This version explicitly checks that every entry in $PATH is a file |
|
137 | This version explicitly checks that every entry in $PATH is a file | |
138 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
138 | with execute access (os.X_OK), so it is much slower than %rehash. | |
139 |
|
139 | |||
140 | Under Windows, it checks executability as a match against a |
|
140 | Under Windows, it checks executability as a match against a | |
141 | '|'-separated string of extensions, stored in the IPython config |
|
141 | '|'-separated string of extensions, stored in the IPython config | |
142 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
142 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
143 |
|
143 | |||
144 | This function also resets the root module cache of module completer, |
|
144 | This function also resets the root module cache of module completer, | |
145 | used on slow filesystems. |
|
145 | used on slow filesystems. | |
146 | """ |
|
146 | """ | |
147 | from IPython.core.alias import InvalidAliasError |
|
147 | from IPython.core.alias import InvalidAliasError | |
148 |
|
148 | |||
149 | # for the benefit of module completer in ipy_completers.py |
|
149 | # for the benefit of module completer in ipy_completers.py | |
150 | del self.shell.db['rootmodules'] |
|
150 | del self.shell.db['rootmodules'] | |
151 |
|
151 | |||
152 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
152 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
153 | os.environ.get('PATH','').split(os.pathsep)] |
|
153 | os.environ.get('PATH','').split(os.pathsep)] | |
154 | path = filter(os.path.isdir,path) |
|
154 | path = filter(os.path.isdir,path) | |
155 |
|
155 | |||
156 | syscmdlist = [] |
|
156 | syscmdlist = [] | |
157 | # Now define isexec in a cross platform manner. |
|
157 | # Now define isexec in a cross platform manner. | |
158 | if os.name == 'posix': |
|
158 | if os.name == 'posix': | |
159 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
159 | isexec = lambda fname:os.path.isfile(fname) and \ | |
160 | os.access(fname,os.X_OK) |
|
160 | os.access(fname,os.X_OK) | |
161 | else: |
|
161 | else: | |
162 | try: |
|
162 | try: | |
163 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
163 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
164 | except KeyError: |
|
164 | except KeyError: | |
165 | winext = 'exe|com|bat|py' |
|
165 | winext = 'exe|com|bat|py' | |
166 | if 'py' not in winext: |
|
166 | if 'py' not in winext: | |
167 | winext += '|py' |
|
167 | winext += '|py' | |
168 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
168 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
169 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
169 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
170 | savedir = os.getcwdu() |
|
170 | savedir = os.getcwdu() | |
171 |
|
171 | |||
172 | # Now walk the paths looking for executables to alias. |
|
172 | # Now walk the paths looking for executables to alias. | |
173 | try: |
|
173 | try: | |
174 | # write the whole loop for posix/Windows so we don't have an if in |
|
174 | # write the whole loop for posix/Windows so we don't have an if in | |
175 | # the innermost part |
|
175 | # the innermost part | |
176 | if os.name == 'posix': |
|
176 | if os.name == 'posix': | |
177 | for pdir in path: |
|
177 | for pdir in path: | |
178 | os.chdir(pdir) |
|
178 | os.chdir(pdir) | |
179 | for ff in os.listdir(pdir): |
|
179 | for ff in os.listdir(pdir): | |
180 | if isexec(ff): |
|
180 | if isexec(ff): | |
181 | try: |
|
181 | try: | |
182 | # Removes dots from the name since ipython |
|
182 | # Removes dots from the name since ipython | |
183 | # will assume names with dots to be python. |
|
183 | # will assume names with dots to be python. | |
184 | self.shell.alias_manager.define_alias( |
|
184 | self.shell.alias_manager.define_alias( | |
185 | ff.replace('.',''), ff) |
|
185 | ff.replace('.',''), ff) | |
186 | except InvalidAliasError: |
|
186 | except InvalidAliasError: | |
187 | pass |
|
187 | pass | |
188 | else: |
|
188 | else: | |
189 | syscmdlist.append(ff) |
|
189 | syscmdlist.append(ff) | |
190 | else: |
|
190 | else: | |
191 | no_alias = self.shell.alias_manager.no_alias |
|
191 | no_alias = self.shell.alias_manager.no_alias | |
192 | for pdir in path: |
|
192 | for pdir in path: | |
193 | os.chdir(pdir) |
|
193 | os.chdir(pdir) | |
194 | for ff in os.listdir(pdir): |
|
194 | for ff in os.listdir(pdir): | |
195 | base, ext = os.path.splitext(ff) |
|
195 | base, ext = os.path.splitext(ff) | |
196 | if isexec(ff) and base.lower() not in no_alias: |
|
196 | if isexec(ff) and base.lower() not in no_alias: | |
197 | if ext.lower() == '.exe': |
|
197 | if ext.lower() == '.exe': | |
198 | ff = base |
|
198 | ff = base | |
199 | try: |
|
199 | try: | |
200 | # Removes dots from the name since ipython |
|
200 | # Removes dots from the name since ipython | |
201 | # will assume names with dots to be python. |
|
201 | # will assume names with dots to be python. | |
202 | self.shell.alias_manager.define_alias( |
|
202 | self.shell.alias_manager.define_alias( | |
203 | base.lower().replace('.',''), ff) |
|
203 | base.lower().replace('.',''), ff) | |
204 | except InvalidAliasError: |
|
204 | except InvalidAliasError: | |
205 | pass |
|
205 | pass | |
206 | syscmdlist.append(ff) |
|
206 | syscmdlist.append(ff) | |
207 | self.shell.db['syscmdlist'] = syscmdlist |
|
207 | self.shell.db['syscmdlist'] = syscmdlist | |
208 | finally: |
|
208 | finally: | |
209 | os.chdir(savedir) |
|
209 | os.chdir(savedir) | |
210 |
|
210 | |||
211 | @skip_doctest |
|
211 | @skip_doctest | |
212 | @line_magic |
|
212 | @line_magic | |
213 | def pwd(self, parameter_s=''): |
|
213 | def pwd(self, parameter_s=''): | |
214 | """Return the current working directory path. |
|
214 | """Return the current working directory path. | |
215 |
|
215 | |||
216 | Examples |
|
216 | Examples | |
217 | -------- |
|
217 | -------- | |
218 | :: |
|
218 | :: | |
219 |
|
219 | |||
220 | In [9]: pwd |
|
220 | In [9]: pwd | |
221 | Out[9]: '/home/tsuser/sprint/ipython' |
|
221 | Out[9]: '/home/tsuser/sprint/ipython' | |
222 | """ |
|
222 | """ | |
223 | return os.getcwdu() |
|
223 | return os.getcwdu() | |
224 |
|
224 | |||
225 | @skip_doctest |
|
225 | @skip_doctest | |
226 | @line_magic |
|
226 | @line_magic | |
227 | def cd(self, parameter_s=''): |
|
227 | def cd(self, parameter_s=''): | |
228 | """Change the current working directory. |
|
228 | """Change the current working directory. | |
229 |
|
229 | |||
230 | This command automatically maintains an internal list of directories |
|
230 | This command automatically maintains an internal list of directories | |
231 | you visit during your IPython session, in the variable _dh. The |
|
231 | you visit during your IPython session, in the variable _dh. The | |
232 | command %dhist shows this history nicely formatted. You can also |
|
232 | command %dhist shows this history nicely formatted. You can also | |
233 | do 'cd -<tab>' to see directory history conveniently. |
|
233 | do 'cd -<tab>' to see directory history conveniently. | |
234 |
|
234 | |||
235 | Usage: |
|
235 | Usage: | |
236 |
|
236 | |||
237 | cd 'dir': changes to directory 'dir'. |
|
237 | cd 'dir': changes to directory 'dir'. | |
238 |
|
238 | |||
239 | cd -: changes to the last visited directory. |
|
239 | cd -: changes to the last visited directory. | |
240 |
|
240 | |||
241 | cd -<n>: changes to the n-th directory in the directory history. |
|
241 | cd -<n>: changes to the n-th directory in the directory history. | |
242 |
|
242 | |||
243 | cd --foo: change to directory that matches 'foo' in history |
|
243 | cd --foo: change to directory that matches 'foo' in history | |
244 |
|
244 | |||
245 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
245 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
246 | (note: cd <bookmark_name> is enough if there is no |
|
246 | (note: cd <bookmark_name> is enough if there is no | |
247 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
247 | directory <bookmark_name>, but a bookmark with the name exists.) | |
248 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
248 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
249 |
|
249 | |||
250 | Options: |
|
250 | Options: | |
251 |
|
251 | |||
252 | -q: quiet. Do not print the working directory after the cd command is |
|
252 | -q: quiet. Do not print the working directory after the cd command is | |
253 | executed. By default IPython's cd command does print this directory, |
|
253 | executed. By default IPython's cd command does print this directory, | |
254 | since the default prompts do not display path information. |
|
254 | since the default prompts do not display path information. | |
255 |
|
255 | |||
256 | Note that !cd doesn't work for this purpose because the shell where |
|
256 | Note that !cd doesn't work for this purpose because the shell where | |
257 | !command runs is immediately discarded after executing 'command'. |
|
257 | !command runs is immediately discarded after executing 'command'. | |
258 |
|
258 | |||
259 | Examples |
|
259 | Examples | |
260 | -------- |
|
260 | -------- | |
261 | :: |
|
261 | :: | |
262 |
|
262 | |||
263 | In [10]: cd parent/child |
|
263 | In [10]: cd parent/child | |
264 | /home/tsuser/parent/child |
|
264 | /home/tsuser/parent/child | |
265 | """ |
|
265 | """ | |
266 |
|
266 | |||
267 | oldcwd = os.getcwdu() |
|
267 | oldcwd = os.getcwdu() | |
268 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
268 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
269 | # jump in directory history by number |
|
269 | # jump in directory history by number | |
270 | if numcd: |
|
270 | if numcd: | |
271 | nn = int(numcd.group(2)) |
|
271 | nn = int(numcd.group(2)) | |
272 | try: |
|
272 | try: | |
273 | ps = self.shell.user_ns['_dh'][nn] |
|
273 | ps = self.shell.user_ns['_dh'][nn] | |
274 | except IndexError: |
|
274 | except IndexError: | |
275 | print 'The requested directory does not exist in history.' |
|
275 | print 'The requested directory does not exist in history.' | |
276 | return |
|
276 | return | |
277 | else: |
|
277 | else: | |
278 | opts = {} |
|
278 | opts = {} | |
279 | elif parameter_s.startswith('--'): |
|
279 | elif parameter_s.startswith('--'): | |
280 | ps = None |
|
280 | ps = None | |
281 | fallback = None |
|
281 | fallback = None | |
282 | pat = parameter_s[2:] |
|
282 | pat = parameter_s[2:] | |
283 | dh = self.shell.user_ns['_dh'] |
|
283 | dh = self.shell.user_ns['_dh'] | |
284 | # first search only by basename (last component) |
|
284 | # first search only by basename (last component) | |
285 | for ent in reversed(dh): |
|
285 | for ent in reversed(dh): | |
286 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
286 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
287 | ps = ent |
|
287 | ps = ent | |
288 | break |
|
288 | break | |
289 |
|
289 | |||
290 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
290 | if fallback is None and pat in ent and os.path.isdir(ent): | |
291 | fallback = ent |
|
291 | fallback = ent | |
292 |
|
292 | |||
293 | # if we have no last part match, pick the first full path match |
|
293 | # if we have no last part match, pick the first full path match | |
294 | if ps is None: |
|
294 | if ps is None: | |
295 | ps = fallback |
|
295 | ps = fallback | |
296 |
|
296 | |||
297 | if ps is None: |
|
297 | if ps is None: | |
298 | print "No matching entry in directory history" |
|
298 | print "No matching entry in directory history" | |
299 | return |
|
299 | return | |
300 | else: |
|
300 | else: | |
301 | opts = {} |
|
301 | opts = {} | |
302 |
|
302 | |||
303 |
|
303 | |||
304 | else: |
|
304 | else: | |
305 | #turn all non-space-escaping backslashes to slashes, |
|
305 | #turn all non-space-escaping backslashes to slashes, | |
306 | # for c:\windows\directory\names\ |
|
306 | # for c:\windows\directory\names\ | |
307 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
307 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
308 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
308 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
309 | # jump to previous |
|
309 | # jump to previous | |
310 | if ps == '-': |
|
310 | if ps == '-': | |
311 | try: |
|
311 | try: | |
312 | ps = self.shell.user_ns['_dh'][-2] |
|
312 | ps = self.shell.user_ns['_dh'][-2] | |
313 | except IndexError: |
|
313 | except IndexError: | |
314 | raise UsageError('%cd -: No previous directory to change to.') |
|
314 | raise UsageError('%cd -: No previous directory to change to.') | |
315 | # jump to bookmark if needed |
|
315 | # jump to bookmark if needed | |
316 | else: |
|
316 | else: | |
317 | if not os.path.isdir(ps) or 'b' in opts: |
|
317 | if not os.path.isdir(ps) or 'b' in opts: | |
318 | bkms = self.shell.db.get('bookmarks', {}) |
|
318 | bkms = self.shell.db.get('bookmarks', {}) | |
319 |
|
319 | |||
320 | if ps in bkms: |
|
320 | if ps in bkms: | |
321 | target = bkms[ps] |
|
321 | target = bkms[ps] | |
322 | print '(bookmark:%s) -> %s' % (ps, target) |
|
322 | print '(bookmark:%s) -> %s' % (ps, target) | |
323 | ps = target |
|
323 | ps = target | |
324 | else: |
|
324 | else: | |
325 | if 'b' in opts: |
|
325 | if 'b' in opts: | |
326 | raise UsageError("Bookmark '%s' not found. " |
|
326 | raise UsageError("Bookmark '%s' not found. " | |
327 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
327 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
328 |
|
328 | |||
329 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
329 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
330 | ps = unquote_filename(ps) |
|
330 | ps = unquote_filename(ps) | |
331 | # at this point ps should point to the target dir |
|
331 | # at this point ps should point to the target dir | |
332 | if ps: |
|
332 | if ps: | |
333 | try: |
|
333 | try: | |
334 | os.chdir(os.path.expanduser(ps)) |
|
334 | os.chdir(os.path.expanduser(ps)) | |
335 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
335 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
336 | set_term_title('IPython: ' + abbrev_cwd()) |
|
336 | set_term_title('IPython: ' + abbrev_cwd()) | |
337 | except OSError: |
|
337 | except OSError: | |
338 | print sys.exc_info()[1] |
|
338 | print sys.exc_info()[1] | |
339 | else: |
|
339 | else: | |
340 | cwd = os.getcwdu() |
|
340 | cwd = os.getcwdu() | |
341 | dhist = self.shell.user_ns['_dh'] |
|
341 | dhist = self.shell.user_ns['_dh'] | |
342 | if oldcwd != cwd: |
|
342 | if oldcwd != cwd: | |
343 | dhist.append(cwd) |
|
343 | dhist.append(cwd) | |
344 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
344 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
345 |
|
345 | |||
346 | else: |
|
346 | else: | |
347 | os.chdir(self.shell.home_dir) |
|
347 | os.chdir(self.shell.home_dir) | |
348 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
348 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
349 | set_term_title('IPython: ' + '~') |
|
349 | set_term_title('IPython: ' + '~') | |
350 | cwd = os.getcwdu() |
|
350 | cwd = os.getcwdu() | |
351 | dhist = self.shell.user_ns['_dh'] |
|
351 | dhist = self.shell.user_ns['_dh'] | |
352 |
|
352 | |||
353 | if oldcwd != cwd: |
|
353 | if oldcwd != cwd: | |
354 | dhist.append(cwd) |
|
354 | dhist.append(cwd) | |
355 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
355 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
356 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
356 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
357 | print self.shell.user_ns['_dh'][-1] |
|
357 | print self.shell.user_ns['_dh'][-1] | |
358 |
|
358 | |||
359 |
|
359 | |||
360 | @line_magic |
|
360 | @line_magic | |
361 | def env(self, parameter_s=''): |
|
361 | def env(self, parameter_s=''): | |
362 | """List environment variables.""" |
|
362 | """List environment variables.""" | |
363 |
|
363 | |||
364 | return dict(os.environ) |
|
364 | return dict(os.environ) | |
365 |
|
365 | |||
366 | @line_magic |
|
366 | @line_magic | |
367 | def pushd(self, parameter_s=''): |
|
367 | def pushd(self, parameter_s=''): | |
368 | """Place the current dir on stack and change directory. |
|
368 | """Place the current dir on stack and change directory. | |
369 |
|
369 | |||
370 | Usage:\\ |
|
370 | Usage:\\ | |
371 | %pushd ['dirname'] |
|
371 | %pushd ['dirname'] | |
372 | """ |
|
372 | """ | |
373 |
|
373 | |||
374 | dir_s = self.shell.dir_stack |
|
374 | dir_s = self.shell.dir_stack | |
375 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
375 | tgt = os.path.expanduser(unquote_filename(parameter_s)) | |
376 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') |
|
376 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') | |
377 | if tgt: |
|
377 | if tgt: | |
378 | self.cd(parameter_s) |
|
378 | self.cd(parameter_s) | |
379 | dir_s.insert(0,cwd) |
|
379 | dir_s.insert(0,cwd) | |
380 | return self.shell.magic('dirs') |
|
380 | return self.shell.magic('dirs') | |
381 |
|
381 | |||
382 | @line_magic |
|
382 | @line_magic | |
383 | def popd(self, parameter_s=''): |
|
383 | def popd(self, parameter_s=''): | |
384 | """Change to directory popped off the top of the stack. |
|
384 | """Change to directory popped off the top of the stack. | |
385 | """ |
|
385 | """ | |
386 | if not self.shell.dir_stack: |
|
386 | if not self.shell.dir_stack: | |
387 | raise UsageError("%popd on empty stack") |
|
387 | raise UsageError("%popd on empty stack") | |
388 | top = self.shell.dir_stack.pop(0) |
|
388 | top = self.shell.dir_stack.pop(0) | |
389 | self.cd(top) |
|
389 | self.cd(top) | |
390 | print "popd ->",top |
|
390 | print "popd ->",top | |
391 |
|
391 | |||
392 | @line_magic |
|
392 | @line_magic | |
393 | def dirs(self, parameter_s=''): |
|
393 | def dirs(self, parameter_s=''): | |
394 | """Return the current directory stack.""" |
|
394 | """Return the current directory stack.""" | |
395 |
|
395 | |||
396 | return self.shell.dir_stack |
|
396 | return self.shell.dir_stack | |
397 |
|
397 | |||
398 | @line_magic |
|
398 | @line_magic | |
399 | def dhist(self, parameter_s=''): |
|
399 | def dhist(self, parameter_s=''): | |
400 | """Print your history of visited directories. |
|
400 | """Print your history of visited directories. | |
401 |
|
401 | |||
402 | %dhist -> print full history\\ |
|
402 | %dhist -> print full history\\ | |
403 | %dhist n -> print last n entries only\\ |
|
403 | %dhist n -> print last n entries only\\ | |
404 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
404 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
405 |
|
405 | |||
406 | This history is automatically maintained by the %cd command, and |
|
406 | This history is automatically maintained by the %cd command, and | |
407 | always available as the global list variable _dh. You can use %cd -<n> |
|
407 | always available as the global list variable _dh. You can use %cd -<n> | |
408 | to go to directory number <n>. |
|
408 | to go to directory number <n>. | |
409 |
|
409 | |||
410 | Note that most of time, you should view directory history by entering |
|
410 | Note that most of time, you should view directory history by entering | |
411 | cd -<TAB>. |
|
411 | cd -<TAB>. | |
412 |
|
412 | |||
413 | """ |
|
413 | """ | |
414 |
|
414 | |||
415 | dh = self.shell.user_ns['_dh'] |
|
415 | dh = self.shell.user_ns['_dh'] | |
416 | if parameter_s: |
|
416 | if parameter_s: | |
417 | try: |
|
417 | try: | |
418 | args = map(int,parameter_s.split()) |
|
418 | args = map(int,parameter_s.split()) | |
419 | except: |
|
419 | except: | |
420 | self.arg_err(self.dhist) |
|
420 | self.arg_err(self.dhist) | |
421 | return |
|
421 | return | |
422 | if len(args) == 1: |
|
422 | if len(args) == 1: | |
423 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
423 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
424 | elif len(args) == 2: |
|
424 | elif len(args) == 2: | |
425 | ini,fin = args |
|
425 | ini,fin = args | |
426 | else: |
|
426 | else: | |
427 | self.arg_err(self.dhist) |
|
427 | self.arg_err(self.dhist) | |
428 | return |
|
428 | return | |
429 | else: |
|
429 | else: | |
430 | ini,fin = 0,len(dh) |
|
430 | ini,fin = 0,len(dh) | |
431 | nlprint(dh, |
|
431 | nlprint(dh, | |
432 | header = 'Directory history (kept in _dh)', |
|
432 | header = 'Directory history (kept in _dh)', | |
433 | start=ini,stop=fin) |
|
433 | start=ini,stop=fin) | |
434 |
|
434 | |||
435 | @skip_doctest |
|
435 | @skip_doctest | |
436 | @line_magic |
|
436 | @line_magic | |
437 | def sc(self, parameter_s=''): |
|
437 | def sc(self, parameter_s=''): | |
438 | """Shell capture - run shell command and capture output (DEPRECATED use !). |
|
438 | """Shell capture - run shell command and capture output (DEPRECATED use !). | |
439 |
|
439 | |||
440 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
440 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
441 |
|
441 | |||
442 | You should use the form 'var = !command' instead. Example: |
|
442 | You should use the form 'var = !command' instead. Example: | |
443 |
|
443 | |||
444 | "%sc -l myfiles = ls ~" should now be written as |
|
444 | "%sc -l myfiles = ls ~" should now be written as | |
445 |
|
445 | |||
446 | "myfiles = !ls ~" |
|
446 | "myfiles = !ls ~" | |
447 |
|
447 | |||
448 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
448 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
449 | below. |
|
449 | below. | |
450 |
|
450 | |||
451 | -- |
|
451 | -- | |
452 | %sc [options] varname=command |
|
452 | %sc [options] varname=command | |
453 |
|
453 | |||
454 | IPython will run the given command using commands.getoutput(), and |
|
454 | IPython will run the given command using commands.getoutput(), and | |
455 | will then update the user's interactive namespace with a variable |
|
455 | will then update the user's interactive namespace with a variable | |
456 | called varname, containing the value of the call. Your command can |
|
456 | called varname, containing the value of the call. Your command can | |
457 | contain shell wildcards, pipes, etc. |
|
457 | contain shell wildcards, pipes, etc. | |
458 |
|
458 | |||
459 | The '=' sign in the syntax is mandatory, and the variable name you |
|
459 | The '=' sign in the syntax is mandatory, and the variable name you | |
460 | supply must follow Python's standard conventions for valid names. |
|
460 | supply must follow Python's standard conventions for valid names. | |
461 |
|
461 | |||
462 | (A special format without variable name exists for internal use) |
|
462 | (A special format without variable name exists for internal use) | |
463 |
|
463 | |||
464 | Options: |
|
464 | Options: | |
465 |
|
465 | |||
466 | -l: list output. Split the output on newlines into a list before |
|
466 | -l: list output. Split the output on newlines into a list before | |
467 | assigning it to the given variable. By default the output is stored |
|
467 | assigning it to the given variable. By default the output is stored | |
468 | as a single string. |
|
468 | as a single string. | |
469 |
|
469 | |||
470 | -v: verbose. Print the contents of the variable. |
|
470 | -v: verbose. Print the contents of the variable. | |
471 |
|
471 | |||
472 | In most cases you should not need to split as a list, because the |
|
472 | In most cases you should not need to split as a list, because the | |
473 | returned value is a special type of string which can automatically |
|
473 | returned value is a special type of string which can automatically | |
474 | provide its contents either as a list (split on newlines) or as a |
|
474 | provide its contents either as a list (split on newlines) or as a | |
475 | space-separated string. These are convenient, respectively, either |
|
475 | space-separated string. These are convenient, respectively, either | |
476 | for sequential processing or to be passed to a shell command. |
|
476 | for sequential processing or to be passed to a shell command. | |
477 |
|
477 | |||
478 | For example:: |
|
478 | For example:: | |
479 |
|
479 | |||
480 | # Capture into variable a |
|
480 | # Capture into variable a | |
481 | In [1]: sc a=ls *py |
|
481 | In [1]: sc a=ls *py | |
482 |
|
482 | |||
483 | # a is a string with embedded newlines |
|
483 | # a is a string with embedded newlines | |
484 | In [2]: a |
|
484 | In [2]: a | |
485 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
485 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
486 |
|
486 | |||
487 | # which can be seen as a list: |
|
487 | # which can be seen as a list: | |
488 | In [3]: a.l |
|
488 | In [3]: a.l | |
489 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
489 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
490 |
|
490 | |||
491 | # or as a whitespace-separated string: |
|
491 | # or as a whitespace-separated string: | |
492 | In [4]: a.s |
|
492 | In [4]: a.s | |
493 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
493 | Out[4]: 'setup.py win32_manual_post_install.py' | |
494 |
|
494 | |||
495 | # a.s is useful to pass as a single command line: |
|
495 | # a.s is useful to pass as a single command line: | |
496 | In [5]: !wc -l $a.s |
|
496 | In [5]: !wc -l $a.s | |
497 | 146 setup.py |
|
497 | 146 setup.py | |
498 | 130 win32_manual_post_install.py |
|
498 | 130 win32_manual_post_install.py | |
499 | 276 total |
|
499 | 276 total | |
500 |
|
500 | |||
501 | # while the list form is useful to loop over: |
|
501 | # while the list form is useful to loop over: | |
502 | In [6]: for f in a.l: |
|
502 | In [6]: for f in a.l: | |
503 | ...: !wc -l $f |
|
503 | ...: !wc -l $f | |
504 | ...: |
|
504 | ...: | |
505 | 146 setup.py |
|
505 | 146 setup.py | |
506 | 130 win32_manual_post_install.py |
|
506 | 130 win32_manual_post_install.py | |
507 |
|
507 | |||
508 | Similarly, the lists returned by the -l option are also special, in |
|
508 | Similarly, the lists returned by the -l option are also special, in | |
509 | the sense that you can equally invoke the .s attribute on them to |
|
509 | the sense that you can equally invoke the .s attribute on them to | |
510 | automatically get a whitespace-separated string from their contents:: |
|
510 | automatically get a whitespace-separated string from their contents:: | |
511 |
|
511 | |||
512 | In [7]: sc -l b=ls *py |
|
512 | In [7]: sc -l b=ls *py | |
513 |
|
513 | |||
514 | In [8]: b |
|
514 | In [8]: b | |
515 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
515 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
516 |
|
516 | |||
517 | In [9]: b.s |
|
517 | In [9]: b.s | |
518 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
518 | Out[9]: 'setup.py win32_manual_post_install.py' | |
519 |
|
519 | |||
520 | In summary, both the lists and strings used for output capture have |
|
520 | In summary, both the lists and strings used for output capture have | |
521 | the following special attributes:: |
|
521 | the following special attributes:: | |
522 |
|
522 | |||
523 | .l (or .list) : value as list. |
|
523 | .l (or .list) : value as list. | |
524 | .n (or .nlstr): value as newline-separated string. |
|
524 | .n (or .nlstr): value as newline-separated string. | |
525 | .s (or .spstr): value as space-separated string. |
|
525 | .s (or .spstr): value as space-separated string. | |
526 | """ |
|
526 | """ | |
527 |
|
527 | |||
528 | opts,args = self.parse_options(parameter_s, 'lv') |
|
528 | opts,args = self.parse_options(parameter_s, 'lv') | |
529 | # Try to get a variable name and command to run |
|
529 | # Try to get a variable name and command to run | |
530 | try: |
|
530 | try: | |
531 | # the variable name must be obtained from the parse_options |
|
531 | # the variable name must be obtained from the parse_options | |
532 | # output, which uses shlex.split to strip options out. |
|
532 | # output, which uses shlex.split to strip options out. | |
533 | var,_ = args.split('=', 1) |
|
533 | var,_ = args.split('=', 1) | |
534 | var = var.strip() |
|
534 | var = var.strip() | |
535 | # But the command has to be extracted from the original input |
|
535 | # But the command has to be extracted from the original input | |
536 | # parameter_s, not on what parse_options returns, to avoid the |
|
536 | # parameter_s, not on what parse_options returns, to avoid the | |
537 | # quote stripping which shlex.split performs on it. |
|
537 | # quote stripping which shlex.split performs on it. | |
538 | _,cmd = parameter_s.split('=', 1) |
|
538 | _,cmd = parameter_s.split('=', 1) | |
539 | except ValueError: |
|
539 | except ValueError: | |
540 | var,cmd = '','' |
|
540 | var,cmd = '','' | |
541 | # If all looks ok, proceed |
|
541 | # If all looks ok, proceed | |
542 | split = 'l' in opts |
|
542 | split = 'l' in opts | |
543 | out = self.shell.getoutput(cmd, split=split) |
|
543 | out = self.shell.getoutput(cmd, split=split) | |
544 | if 'v' in opts: |
|
544 | if 'v' in opts: | |
545 | print '%s ==\n%s' % (var, pformat(out)) |
|
545 | print '%s ==\n%s' % (var, pformat(out)) | |
546 | if var: |
|
546 | if var: | |
547 | self.shell.user_ns.update({var:out}) |
|
547 | self.shell.user_ns.update({var:out}) | |
548 | else: |
|
548 | else: | |
549 | return out |
|
549 | return out | |
550 |
|
550 | |||
551 | @line_cell_magic |
|
551 | @line_cell_magic | |
552 | def sx(self, line='', cell=None): |
|
552 | def sx(self, line='', cell=None): | |
553 | """Shell execute - run shell command and capture output (!! is short-hand). |
|
553 | """Shell execute - run shell command and capture output (!! is short-hand). | |
554 |
|
554 | |||
555 | %sx command |
|
555 | %sx command | |
556 |
|
556 | |||
557 | IPython will run the given command using commands.getoutput(), and |
|
557 | IPython will run the given command using commands.getoutput(), and | |
558 | return the result formatted as a list (split on '\\n'). Since the |
|
558 | return the result formatted as a list (split on '\\n'). Since the | |
559 | output is _returned_, it will be stored in ipython's regular output |
|
559 | output is _returned_, it will be stored in ipython's regular output | |
560 | cache Out[N] and in the '_N' automatic variables. |
|
560 | cache Out[N] and in the '_N' automatic variables. | |
561 |
|
561 | |||
562 | Notes: |
|
562 | Notes: | |
563 |
|
563 | |||
564 | 1) If an input line begins with '!!', then %sx is automatically |
|
564 | 1) If an input line begins with '!!', then %sx is automatically | |
565 | invoked. That is, while:: |
|
565 | invoked. That is, while:: | |
566 |
|
566 | |||
567 | !ls |
|
567 | !ls | |
568 |
|
568 | |||
569 | causes ipython to simply issue system('ls'), typing:: |
|
569 | causes ipython to simply issue system('ls'), typing:: | |
570 |
|
570 | |||
571 | !!ls |
|
571 | !!ls | |
572 |
|
572 | |||
573 | is a shorthand equivalent to:: |
|
573 | is a shorthand equivalent to:: | |
574 |
|
574 | |||
575 | %sx ls |
|
575 | %sx ls | |
576 |
|
576 | |||
577 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
577 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
578 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
578 | like '%sc -l'. The reason for this is to make it as easy as possible | |
579 | to process line-oriented shell output via further python commands. |
|
579 | to process line-oriented shell output via further python commands. | |
580 | %sc is meant to provide much finer control, but requires more |
|
580 | %sc is meant to provide much finer control, but requires more | |
581 | typing. |
|
581 | typing. | |
582 |
|
582 | |||
583 | 3) Just like %sc -l, this is a list with special attributes: |
|
583 | 3) Just like %sc -l, this is a list with special attributes: | |
584 | :: |
|
584 | :: | |
585 |
|
585 | |||
586 | .l (or .list) : value as list. |
|
586 | .l (or .list) : value as list. | |
587 | .n (or .nlstr): value as newline-separated string. |
|
587 | .n (or .nlstr): value as newline-separated string. | |
588 | .s (or .spstr): value as whitespace-separated string. |
|
588 | .s (or .spstr): value as whitespace-separated string. | |
589 |
|
589 | |||
590 | This is very useful when trying to use such lists as arguments to |
|
590 | This is very useful when trying to use such lists as arguments to | |
591 | system commands.""" |
|
591 | system commands.""" | |
592 |
|
592 | |||
593 | if cell is None: |
|
593 | if cell is None: | |
594 | # line magic |
|
594 | # line magic | |
595 | return self.shell.getoutput(line) |
|
595 | return self.shell.getoutput(line) | |
596 | else: |
|
596 | else: | |
597 | opts,args = self.parse_options(line, '', 'out=') |
|
597 | opts,args = self.parse_options(line, '', 'out=') | |
598 | output = self.shell.getoutput(cell) |
|
598 | output = self.shell.getoutput(cell) | |
599 | out_name = opts.get('out', opts.get('o')) |
|
599 | out_name = opts.get('out', opts.get('o')) | |
600 | if out_name: |
|
600 | if out_name: | |
601 | self.shell.user_ns[out_name] = output |
|
601 | self.shell.user_ns[out_name] = output | |
602 | else: |
|
602 | else: | |
603 | return output |
|
603 | return output | |
604 |
|
604 | |||
605 | system = line_cell_magic('system')(sx) |
|
605 | system = line_cell_magic('system')(sx) | |
606 | bang = cell_magic('!')(sx) |
|
606 | bang = cell_magic('!')(sx) | |
607 |
|
607 | |||
608 | @line_magic |
|
608 | @line_magic | |
609 | def bookmark(self, parameter_s=''): |
|
609 | def bookmark(self, parameter_s=''): | |
610 | """Manage IPython's bookmark system. |
|
610 | """Manage IPython's bookmark system. | |
611 |
|
611 | |||
612 | %bookmark <name> - set bookmark to current dir |
|
612 | %bookmark <name> - set bookmark to current dir | |
613 | %bookmark <name> <dir> - set bookmark to <dir> |
|
613 | %bookmark <name> <dir> - set bookmark to <dir> | |
614 | %bookmark -l - list all bookmarks |
|
614 | %bookmark -l - list all bookmarks | |
615 | %bookmark -d <name> - remove bookmark |
|
615 | %bookmark -d <name> - remove bookmark | |
616 | %bookmark -r - remove all bookmarks |
|
616 | %bookmark -r - remove all bookmarks | |
617 |
|
617 | |||
618 | You can later on access a bookmarked folder with:: |
|
618 | You can later on access a bookmarked folder with:: | |
619 |
|
619 | |||
620 | %cd -b <name> |
|
620 | %cd -b <name> | |
621 |
|
621 | |||
622 | or simply '%cd <name>' if there is no directory called <name> AND |
|
622 | or simply '%cd <name>' if there is no directory called <name> AND | |
623 | there is such a bookmark defined. |
|
623 | there is such a bookmark defined. | |
624 |
|
624 | |||
625 | Your bookmarks persist through IPython sessions, but they are |
|
625 | Your bookmarks persist through IPython sessions, but they are | |
626 | associated with each profile.""" |
|
626 | associated with each profile.""" | |
627 |
|
627 | |||
628 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
628 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
629 | if len(args) > 2: |
|
629 | if len(args) > 2: | |
630 | raise UsageError("%bookmark: too many arguments") |
|
630 | raise UsageError("%bookmark: too many arguments") | |
631 |
|
631 | |||
632 | bkms = self.shell.db.get('bookmarks',{}) |
|
632 | bkms = self.shell.db.get('bookmarks',{}) | |
633 |
|
633 | |||
634 | if 'd' in opts: |
|
634 | if 'd' in opts: | |
635 | try: |
|
635 | try: | |
636 | todel = args[0] |
|
636 | todel = args[0] | |
637 | except IndexError: |
|
637 | except IndexError: | |
638 | raise UsageError( |
|
638 | raise UsageError( | |
639 | "%bookmark -d: must provide a bookmark to delete") |
|
639 | "%bookmark -d: must provide a bookmark to delete") | |
640 | else: |
|
640 | else: | |
641 | try: |
|
641 | try: | |
642 | del bkms[todel] |
|
642 | del bkms[todel] | |
643 | except KeyError: |
|
643 | except KeyError: | |
644 | raise UsageError( |
|
644 | raise UsageError( | |
645 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
645 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
646 |
|
646 | |||
647 | elif 'r' in opts: |
|
647 | elif 'r' in opts: | |
648 | bkms = {} |
|
648 | bkms = {} | |
649 | elif 'l' in opts: |
|
649 | elif 'l' in opts: | |
650 | bks = bkms.keys() |
|
650 | bks = bkms.keys() | |
651 | bks.sort() |
|
651 | bks.sort() | |
652 | if bks: |
|
652 | if bks: | |
653 | size = max(map(len, bks)) |
|
653 | size = max(map(len, bks)) | |
654 | else: |
|
654 | else: | |
655 | size = 0 |
|
655 | size = 0 | |
656 | fmt = '%-'+str(size)+'s -> %s' |
|
656 | fmt = '%-'+str(size)+'s -> %s' | |
657 | print 'Current bookmarks:' |
|
657 | print 'Current bookmarks:' | |
658 | for bk in bks: |
|
658 | for bk in bks: | |
659 | print fmt % (bk, bkms[bk]) |
|
659 | print fmt % (bk, bkms[bk]) | |
660 | else: |
|
660 | else: | |
661 | if not args: |
|
661 | if not args: | |
662 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
662 | raise UsageError("%bookmark: You must specify the bookmark name") | |
663 | elif len(args)==1: |
|
663 | elif len(args)==1: | |
664 | bkms[args[0]] = os.getcwdu() |
|
664 | bkms[args[0]] = os.getcwdu() | |
665 | elif len(args)==2: |
|
665 | elif len(args)==2: | |
666 | bkms[args[0]] = args[1] |
|
666 | bkms[args[0]] = args[1] | |
667 | self.shell.db['bookmarks'] = bkms |
|
667 | self.shell.db['bookmarks'] = bkms | |
668 |
|
668 | |||
669 | @line_magic |
|
669 | @line_magic | |
670 | def pycat(self, parameter_s=''): |
|
670 | def pycat(self, parameter_s=''): | |
671 | """Show a syntax-highlighted file through a pager. |
|
671 | """Show a syntax-highlighted file through a pager. | |
672 |
|
672 | |||
673 | This magic is similar to the cat utility, but it will assume the file |
|
673 | This magic is similar to the cat utility, but it will assume the file | |
674 | to be Python source and will show it with syntax highlighting. |
|
674 | to be Python source and will show it with syntax highlighting. | |
675 |
|
675 | |||
676 | This magic command can either take a local filename, an url, |
|
676 | This magic command can either take a local filename, an url, | |
677 | an history range (see %history) or a macro as argument :: |
|
677 | an history range (see %history) or a macro as argument :: | |
678 |
|
678 | |||
679 | %pycat myscript.py |
|
679 | %pycat myscript.py | |
680 | %pycat 7-27 |
|
680 | %pycat 7-27 | |
681 | %pycat myMacro |
|
681 | %pycat myMacro | |
682 | %pycat http://www.example.com/myscript.py |
|
682 | %pycat http://www.example.com/myscript.py | |
683 | """ |
|
683 | """ | |
|
684 | if not parameter_s: | |||
|
685 | raise UsageError('Missing filename, URL, input history range, ' | |||
|
686 | 'or macro.') | |||
684 |
|
687 | |||
685 | try : |
|
688 | try : | |
686 | cont = self.shell.find_user_code(parameter_s) |
|
689 | cont = self.shell.find_user_code(parameter_s) | |
687 | except (ValueError, IOError): |
|
690 | except (ValueError, IOError): | |
688 | print "Error: no such file, variable, URL, history range or macro" |
|
691 | print "Error: no such file, variable, URL, history range or macro" | |
689 | return |
|
692 | return | |
690 |
|
693 | |||
691 | page.page(self.shell.pycolorize(cont)) |
|
694 | page.page(self.shell.pycolorize(cont)) | |
692 |
|
695 | |||
693 | @magic_arguments.magic_arguments() |
|
696 | @magic_arguments.magic_arguments() | |
694 | @magic_arguments.argument( |
|
697 | @magic_arguments.argument( | |
695 | '-a', '--amend', action='store_true', default=False, |
|
698 | '-a', '--amend', action='store_true', default=False, | |
696 | help='Open file for amending if it exists' |
|
699 | help='Open file for amending if it exists' | |
697 | ) |
|
700 | ) | |
698 | @magic_arguments.argument( |
|
701 | @magic_arguments.argument( | |
699 | 'filename', type=unicode, |
|
702 | 'filename', type=unicode, | |
700 | help='file to write' |
|
703 | help='file to write' | |
701 | ) |
|
704 | ) | |
702 | @cell_magic |
|
705 | @cell_magic | |
703 | def file(self, line, cell): |
|
706 | def file(self, line, cell): | |
704 | """Write the contents of the cell to a file. |
|
707 | """Write the contents of the cell to a file. | |
705 |
|
708 | |||
706 | For frontends that do not support stdin (Notebook), -f is implied. |
|
709 | For frontends that do not support stdin (Notebook), -f is implied. | |
707 | """ |
|
710 | """ | |
708 | args = magic_arguments.parse_argstring(self.file, line) |
|
711 | args = magic_arguments.parse_argstring(self.file, line) | |
709 | filename = unquote_filename(args.filename) |
|
712 | filename = unquote_filename(args.filename) | |
710 |
|
713 | |||
711 | if os.path.exists(filename): |
|
714 | if os.path.exists(filename): | |
712 | if args.amend: |
|
715 | if args.amend: | |
713 | print "Amending to %s" % filename |
|
716 | print "Amending to %s" % filename | |
714 | else: |
|
717 | else: | |
715 | print "Overwriting %s" % filename |
|
718 | print "Overwriting %s" % filename | |
716 | else: |
|
719 | else: | |
717 | print "Writing %s" % filename |
|
720 | print "Writing %s" % filename | |
718 |
|
721 | |||
719 | mode = 'a' if args.amend else 'w' |
|
722 | mode = 'a' if args.amend else 'w' | |
720 | with io.open(filename, mode, encoding='utf-8') as f: |
|
723 | with io.open(filename, mode, encoding='utf-8') as f: | |
721 | f.write(cell) |
|
724 | f.write(cell) |
@@ -1,584 +1,588 b'' | |||||
1 | """A ZMQ-based subclass of InteractiveShell. |
|
1 | """A ZMQ-based subclass of InteractiveShell. | |
2 |
|
2 | |||
3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
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 |
|
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 |
|
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 |
|
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 |
|
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. |
|
8 | implementation that doesn't rely on so much monkeypatching. | |
9 |
|
9 | |||
10 | But this lets us maintain a fully working IPython as we develop the new |
|
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. |
|
11 | machinery. This should thus be thought of as scaffolding. | |
12 | """ |
|
12 | """ | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 | import time |
|
21 | import time | |
22 |
|
22 | |||
23 | # System library imports |
|
23 | # System library imports | |
24 | from zmq.eventloop import ioloop |
|
24 | from zmq.eventloop import ioloop | |
25 |
|
25 | |||
26 | # Our own |
|
26 | # Our own | |
27 | from IPython.core.interactiveshell import ( |
|
27 | from IPython.core.interactiveshell import ( | |
28 | InteractiveShell, InteractiveShellABC |
|
28 | InteractiveShell, InteractiveShellABC | |
29 | ) |
|
29 | ) | |
30 | from IPython.core import page |
|
30 | from IPython.core import page | |
31 | from IPython.core.autocall import ZMQExitAutocall |
|
31 | from IPython.core.autocall import ZMQExitAutocall | |
32 | from IPython.core.displaypub import DisplayPublisher |
|
32 | from IPython.core.displaypub import DisplayPublisher | |
|
33 | from IPython.core.error import UsageError | |||
33 | from IPython.core.magics import MacroToEdit, CodeMagics |
|
34 | from IPython.core.magics import MacroToEdit, CodeMagics | |
34 | from IPython.core.magic import magics_class, line_magic, Magics |
|
35 | from IPython.core.magic import magics_class, line_magic, Magics | |
35 | from IPython.core.payloadpage import install_payload_page |
|
36 | from IPython.core.payloadpage import install_payload_page | |
36 | from IPython.lib.kernel import ( |
|
37 | from IPython.lib.kernel import ( | |
37 | get_connection_file, get_connection_info, connect_qtconsole |
|
38 | get_connection_file, get_connection_info, connect_qtconsole | |
38 | ) |
|
39 | ) | |
39 | from IPython.testing.skipdoctest import skip_doctest |
|
40 | from IPython.testing.skipdoctest import skip_doctest | |
40 | from IPython.utils import io |
|
41 | from IPython.utils import io | |
41 | from IPython.utils.jsonutil import json_clean, encode_images |
|
42 | from IPython.utils.jsonutil import json_clean, encode_images | |
42 | from IPython.utils.process import arg_split |
|
43 | from IPython.utils.process import arg_split | |
43 | from IPython.utils import py3compat |
|
44 | from IPython.utils import py3compat | |
44 | from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes |
|
45 | from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes | |
45 | from IPython.utils.warn import warn, error |
|
46 | from IPython.utils.warn import warn, error | |
46 | from IPython.zmq.displayhook import ZMQShellDisplayHook |
|
47 | from IPython.zmq.displayhook import ZMQShellDisplayHook | |
47 | from IPython.zmq.datapub import ZMQDataPublisher |
|
48 | from IPython.zmq.datapub import ZMQDataPublisher | |
48 | from IPython.zmq.session import extract_header |
|
49 | from IPython.zmq.session import extract_header | |
49 | from session import Session |
|
50 | from session import Session | |
50 |
|
51 | |||
51 | #----------------------------------------------------------------------------- |
|
52 | #----------------------------------------------------------------------------- | |
52 | # Functions and classes |
|
53 | # Functions and classes | |
53 | #----------------------------------------------------------------------------- |
|
54 | #----------------------------------------------------------------------------- | |
54 |
|
55 | |||
55 | class ZMQDisplayPublisher(DisplayPublisher): |
|
56 | class ZMQDisplayPublisher(DisplayPublisher): | |
56 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" |
|
57 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" | |
57 |
|
58 | |||
58 | session = Instance(Session) |
|
59 | session = Instance(Session) | |
59 | pub_socket = Instance('zmq.Socket') |
|
60 | pub_socket = Instance('zmq.Socket') | |
60 | parent_header = Dict({}) |
|
61 | parent_header = Dict({}) | |
61 | topic = CBytes(b'displaypub') |
|
62 | topic = CBytes(b'displaypub') | |
62 |
|
63 | |||
63 | def set_parent(self, parent): |
|
64 | def set_parent(self, parent): | |
64 | """Set the parent for outbound messages.""" |
|
65 | """Set the parent for outbound messages.""" | |
65 | self.parent_header = extract_header(parent) |
|
66 | self.parent_header = extract_header(parent) | |
66 |
|
67 | |||
67 | def _flush_streams(self): |
|
68 | def _flush_streams(self): | |
68 | """flush IO Streams prior to display""" |
|
69 | """flush IO Streams prior to display""" | |
69 | sys.stdout.flush() |
|
70 | sys.stdout.flush() | |
70 | sys.stderr.flush() |
|
71 | sys.stderr.flush() | |
71 |
|
72 | |||
72 | def publish(self, source, data, metadata=None): |
|
73 | def publish(self, source, data, metadata=None): | |
73 | self._flush_streams() |
|
74 | self._flush_streams() | |
74 | if metadata is None: |
|
75 | if metadata is None: | |
75 | metadata = {} |
|
76 | metadata = {} | |
76 | self._validate_data(source, data, metadata) |
|
77 | self._validate_data(source, data, metadata) | |
77 | content = {} |
|
78 | content = {} | |
78 | content['source'] = source |
|
79 | content['source'] = source | |
79 | content['data'] = encode_images(data) |
|
80 | content['data'] = encode_images(data) | |
80 | content['metadata'] = metadata |
|
81 | content['metadata'] = metadata | |
81 | self.session.send( |
|
82 | self.session.send( | |
82 | self.pub_socket, u'display_data', json_clean(content), |
|
83 | self.pub_socket, u'display_data', json_clean(content), | |
83 | parent=self.parent_header, ident=self.topic, |
|
84 | parent=self.parent_header, ident=self.topic, | |
84 | ) |
|
85 | ) | |
85 |
|
86 | |||
86 | def clear_output(self, stdout=True, stderr=True, other=True): |
|
87 | def clear_output(self, stdout=True, stderr=True, other=True): | |
87 | content = dict(stdout=stdout, stderr=stderr, other=other) |
|
88 | content = dict(stdout=stdout, stderr=stderr, other=other) | |
88 |
|
89 | |||
89 | if stdout: |
|
90 | if stdout: | |
90 | print('\r', file=sys.stdout, end='') |
|
91 | print('\r', file=sys.stdout, end='') | |
91 | if stderr: |
|
92 | if stderr: | |
92 | print('\r', file=sys.stderr, end='') |
|
93 | print('\r', file=sys.stderr, end='') | |
93 |
|
94 | |||
94 | self._flush_streams() |
|
95 | self._flush_streams() | |
95 |
|
96 | |||
96 | self.session.send( |
|
97 | self.session.send( | |
97 | self.pub_socket, u'clear_output', content, |
|
98 | self.pub_socket, u'clear_output', content, | |
98 | parent=self.parent_header, ident=self.topic, |
|
99 | parent=self.parent_header, ident=self.topic, | |
99 | ) |
|
100 | ) | |
100 |
|
101 | |||
101 | @magics_class |
|
102 | @magics_class | |
102 | class KernelMagics(Magics): |
|
103 | class KernelMagics(Magics): | |
103 | #------------------------------------------------------------------------ |
|
104 | #------------------------------------------------------------------------ | |
104 | # Magic overrides |
|
105 | # Magic overrides | |
105 | #------------------------------------------------------------------------ |
|
106 | #------------------------------------------------------------------------ | |
106 | # Once the base class stops inheriting from magic, this code needs to be |
|
107 | # Once the base class stops inheriting from magic, this code needs to be | |
107 | # moved into a separate machinery as well. For now, at least isolate here |
|
108 | # moved into a separate machinery as well. For now, at least isolate here | |
108 | # the magics which this class needs to implement differently from the base |
|
109 | # the magics which this class needs to implement differently from the base | |
109 | # class, or that are unique to it. |
|
110 | # class, or that are unique to it. | |
110 |
|
111 | |||
111 | @line_magic |
|
112 | @line_magic | |
112 | def doctest_mode(self, parameter_s=''): |
|
113 | def doctest_mode(self, parameter_s=''): | |
113 | """Toggle doctest mode on and off. |
|
114 | """Toggle doctest mode on and off. | |
114 |
|
115 | |||
115 | This mode is intended to make IPython behave as much as possible like a |
|
116 | This mode is intended to make IPython behave as much as possible like a | |
116 | plain Python shell, from the perspective of how its prompts, exceptions |
|
117 | plain Python shell, from the perspective of how its prompts, exceptions | |
117 | and output look. This makes it easy to copy and paste parts of a |
|
118 | and output look. This makes it easy to copy and paste parts of a | |
118 | session into doctests. It does so by: |
|
119 | session into doctests. It does so by: | |
119 |
|
120 | |||
120 | - Changing the prompts to the classic ``>>>`` ones. |
|
121 | - Changing the prompts to the classic ``>>>`` ones. | |
121 | - Changing the exception reporting mode to 'Plain'. |
|
122 | - Changing the exception reporting mode to 'Plain'. | |
122 | - Disabling pretty-printing of output. |
|
123 | - Disabling pretty-printing of output. | |
123 |
|
124 | |||
124 | Note that IPython also supports the pasting of code snippets that have |
|
125 | Note that IPython also supports the pasting of code snippets that have | |
125 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
126 | leading '>>>' and '...' prompts in them. This means that you can paste | |
126 | doctests from files or docstrings (even if they have leading |
|
127 | doctests from files or docstrings (even if they have leading | |
127 | whitespace), and the code will execute correctly. You can then use |
|
128 | whitespace), and the code will execute correctly. You can then use | |
128 | '%history -t' to see the translated history; this will give you the |
|
129 | '%history -t' to see the translated history; this will give you the | |
129 | input after removal of all the leading prompts and whitespace, which |
|
130 | input after removal of all the leading prompts and whitespace, which | |
130 | can be pasted back into an editor. |
|
131 | can be pasted back into an editor. | |
131 |
|
132 | |||
132 | With these features, you can switch into this mode easily whenever you |
|
133 | With these features, you can switch into this mode easily whenever you | |
133 | need to do testing and changes to doctests, without having to leave |
|
134 | need to do testing and changes to doctests, without having to leave | |
134 | your existing IPython session. |
|
135 | your existing IPython session. | |
135 | """ |
|
136 | """ | |
136 |
|
137 | |||
137 | from IPython.utils.ipstruct import Struct |
|
138 | from IPython.utils.ipstruct import Struct | |
138 |
|
139 | |||
139 | # Shorthands |
|
140 | # Shorthands | |
140 | shell = self.shell |
|
141 | shell = self.shell | |
141 | disp_formatter = self.shell.display_formatter |
|
142 | disp_formatter = self.shell.display_formatter | |
142 | ptformatter = disp_formatter.formatters['text/plain'] |
|
143 | ptformatter = disp_formatter.formatters['text/plain'] | |
143 | # dstore is a data store kept in the instance metadata bag to track any |
|
144 | # dstore is a data store kept in the instance metadata bag to track any | |
144 | # changes we make, so we can undo them later. |
|
145 | # changes we make, so we can undo them later. | |
145 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
146 | dstore = shell.meta.setdefault('doctest_mode', Struct()) | |
146 | save_dstore = dstore.setdefault |
|
147 | save_dstore = dstore.setdefault | |
147 |
|
148 | |||
148 | # save a few values we'll need to recover later |
|
149 | # save a few values we'll need to recover later | |
149 | mode = save_dstore('mode', False) |
|
150 | mode = save_dstore('mode', False) | |
150 | save_dstore('rc_pprint', ptformatter.pprint) |
|
151 | save_dstore('rc_pprint', ptformatter.pprint) | |
151 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
152 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
152 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
153 | save_dstore('xmode', shell.InteractiveTB.mode) | |
153 |
|
154 | |||
154 | if mode == False: |
|
155 | if mode == False: | |
155 | # turn on |
|
156 | # turn on | |
156 | ptformatter.pprint = False |
|
157 | ptformatter.pprint = False | |
157 | disp_formatter.plain_text_only = True |
|
158 | disp_formatter.plain_text_only = True | |
158 | shell.magic('xmode Plain') |
|
159 | shell.magic('xmode Plain') | |
159 | else: |
|
160 | else: | |
160 | # turn off |
|
161 | # turn off | |
161 | ptformatter.pprint = dstore.rc_pprint |
|
162 | ptformatter.pprint = dstore.rc_pprint | |
162 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
163 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
163 | shell.magic("xmode " + dstore.xmode) |
|
164 | shell.magic("xmode " + dstore.xmode) | |
164 |
|
165 | |||
165 | # Store new mode and inform on console |
|
166 | # Store new mode and inform on console | |
166 | dstore.mode = bool(1-int(mode)) |
|
167 | dstore.mode = bool(1-int(mode)) | |
167 | mode_label = ['OFF','ON'][dstore.mode] |
|
168 | mode_label = ['OFF','ON'][dstore.mode] | |
168 | print('Doctest mode is:', mode_label) |
|
169 | print('Doctest mode is:', mode_label) | |
169 |
|
170 | |||
170 | # Send the payload back so that clients can modify their prompt display |
|
171 | # Send the payload back so that clients can modify their prompt display | |
171 | payload = dict( |
|
172 | payload = dict( | |
172 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.doctest_mode', |
|
173 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.doctest_mode', | |
173 | mode=dstore.mode) |
|
174 | mode=dstore.mode) | |
174 | shell.payload_manager.write_payload(payload) |
|
175 | shell.payload_manager.write_payload(payload) | |
175 |
|
176 | |||
176 |
|
177 | |||
177 | _find_edit_target = CodeMagics._find_edit_target |
|
178 | _find_edit_target = CodeMagics._find_edit_target | |
178 |
|
179 | |||
179 | @skip_doctest |
|
180 | @skip_doctest | |
180 | @line_magic |
|
181 | @line_magic | |
181 | def edit(self, parameter_s='', last_call=['','']): |
|
182 | def edit(self, parameter_s='', last_call=['','']): | |
182 | """Bring up an editor and execute the resulting code. |
|
183 | """Bring up an editor and execute the resulting code. | |
183 |
|
184 | |||
184 | Usage: |
|
185 | Usage: | |
185 | %edit [options] [args] |
|
186 | %edit [options] [args] | |
186 |
|
187 | |||
187 | %edit runs an external text editor. You will need to set the command for |
|
188 | %edit runs an external text editor. You will need to set the command for | |
188 | this editor via the ``TerminalInteractiveShell.editor`` option in your |
|
189 | this editor via the ``TerminalInteractiveShell.editor`` option in your | |
189 | configuration file before it will work. |
|
190 | configuration file before it will work. | |
190 |
|
191 | |||
191 | This command allows you to conveniently edit multi-line code right in |
|
192 | This command allows you to conveniently edit multi-line code right in | |
192 | your IPython session. |
|
193 | your IPython session. | |
193 |
|
194 | |||
194 | If called without arguments, %edit opens up an empty editor with a |
|
195 | If called without arguments, %edit opens up an empty editor with a | |
195 | temporary file and will execute the contents of this file when you |
|
196 | temporary file and will execute the contents of this file when you | |
196 | close it (don't forget to save it!). |
|
197 | close it (don't forget to save it!). | |
197 |
|
198 | |||
198 |
|
199 | |||
199 | Options: |
|
200 | Options: | |
200 |
|
201 | |||
201 | -n <number>: open the editor at a specified line number. By default, |
|
202 | -n <number>: open the editor at a specified line number. By default, | |
202 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
203 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
203 | you can configure this by providing your own modified hook if your |
|
204 | you can configure this by providing your own modified hook if your | |
204 | favorite editor supports line-number specifications with a different |
|
205 | favorite editor supports line-number specifications with a different | |
205 | syntax. |
|
206 | syntax. | |
206 |
|
207 | |||
207 | -p: this will call the editor with the same data as the previous time |
|
208 | -p: this will call the editor with the same data as the previous time | |
208 | it was used, regardless of how long ago (in your current session) it |
|
209 | it was used, regardless of how long ago (in your current session) it | |
209 | was. |
|
210 | was. | |
210 |
|
211 | |||
211 | -r: use 'raw' input. This option only applies to input taken from the |
|
212 | -r: use 'raw' input. This option only applies to input taken from the | |
212 | user's history. By default, the 'processed' history is used, so that |
|
213 | user's history. By default, the 'processed' history is used, so that | |
213 | magics are loaded in their transformed version to valid Python. If |
|
214 | magics are loaded in their transformed version to valid Python. If | |
214 | this option is given, the raw input as typed as the command line is |
|
215 | this option is given, the raw input as typed as the command line is | |
215 | used instead. When you exit the editor, it will be executed by |
|
216 | used instead. When you exit the editor, it will be executed by | |
216 | IPython's own processor. |
|
217 | IPython's own processor. | |
217 |
|
218 | |||
218 | -x: do not execute the edited code immediately upon exit. This is |
|
219 | -x: do not execute the edited code immediately upon exit. This is | |
219 | mainly useful if you are editing programs which need to be called with |
|
220 | mainly useful if you are editing programs which need to be called with | |
220 | command line arguments, which you can then do using %run. |
|
221 | command line arguments, which you can then do using %run. | |
221 |
|
222 | |||
222 |
|
223 | |||
223 | Arguments: |
|
224 | Arguments: | |
224 |
|
225 | |||
225 | If arguments are given, the following possibilites exist: |
|
226 | If arguments are given, the following possibilites exist: | |
226 |
|
227 | |||
227 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
228 | - The arguments are numbers or pairs of colon-separated numbers (like | |
228 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
229 | 1 4:8 9). These are interpreted as lines of previous input to be | |
229 | loaded into the editor. The syntax is the same of the %macro command. |
|
230 | loaded into the editor. The syntax is the same of the %macro command. | |
230 |
|
231 | |||
231 | - If the argument doesn't start with a number, it is evaluated as a |
|
232 | - If the argument doesn't start with a number, it is evaluated as a | |
232 | variable and its contents loaded into the editor. You can thus edit |
|
233 | variable and its contents loaded into the editor. You can thus edit | |
233 | any string which contains python code (including the result of |
|
234 | any string which contains python code (including the result of | |
234 | previous edits). |
|
235 | previous edits). | |
235 |
|
236 | |||
236 | - If the argument is the name of an object (other than a string), |
|
237 | - If the argument is the name of an object (other than a string), | |
237 | IPython will try to locate the file where it was defined and open the |
|
238 | IPython will try to locate the file where it was defined and open the | |
238 | editor at the point where it is defined. You can use `%edit function` |
|
239 | editor at the point where it is defined. You can use `%edit function` | |
239 | to load an editor exactly at the point where 'function' is defined, |
|
240 | to load an editor exactly at the point where 'function' is defined, | |
240 | edit it and have the file be executed automatically. |
|
241 | edit it and have the file be executed automatically. | |
241 |
|
242 | |||
242 | If the object is a macro (see %macro for details), this opens up your |
|
243 | If the object is a macro (see %macro for details), this opens up your | |
243 | specified editor with a temporary file containing the macro's data. |
|
244 | specified editor with a temporary file containing the macro's data. | |
244 | Upon exit, the macro is reloaded with the contents of the file. |
|
245 | Upon exit, the macro is reloaded with the contents of the file. | |
245 |
|
246 | |||
246 | Note: opening at an exact line is only supported under Unix, and some |
|
247 | Note: opening at an exact line is only supported under Unix, and some | |
247 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
248 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
248 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
249 | '+NUMBER' parameter necessary for this feature. Good editors like | |
249 | (X)Emacs, vi, jed, pico and joe all do. |
|
250 | (X)Emacs, vi, jed, pico and joe all do. | |
250 |
|
251 | |||
251 | - If the argument is not found as a variable, IPython will look for a |
|
252 | - If the argument is not found as a variable, IPython will look for a | |
252 | file with that name (adding .py if necessary) and load it into the |
|
253 | file with that name (adding .py if necessary) and load it into the | |
253 | editor. It will execute its contents with execfile() when you exit, |
|
254 | editor. It will execute its contents with execfile() when you exit, | |
254 | loading any code in the file into your interactive namespace. |
|
255 | loading any code in the file into your interactive namespace. | |
255 |
|
256 | |||
256 | After executing your code, %edit will return as output the code you |
|
257 | After executing your code, %edit will return as output the code you | |
257 | typed in the editor (except when it was an existing file). This way |
|
258 | typed in the editor (except when it was an existing file). This way | |
258 | you can reload the code in further invocations of %edit as a variable, |
|
259 | you can reload the code in further invocations of %edit as a variable, | |
259 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
260 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
260 | the output. |
|
261 | the output. | |
261 |
|
262 | |||
262 | Note that %edit is also available through the alias %ed. |
|
263 | Note that %edit is also available through the alias %ed. | |
263 |
|
264 | |||
264 | This is an example of creating a simple function inside the editor and |
|
265 | This is an example of creating a simple function inside the editor and | |
265 | then modifying it. First, start up the editor: |
|
266 | then modifying it. First, start up the editor: | |
266 |
|
267 | |||
267 | In [1]: ed |
|
268 | In [1]: ed | |
268 | Editing... done. Executing edited code... |
|
269 | Editing... done. Executing edited code... | |
269 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
270 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
270 |
|
271 | |||
271 | We can then call the function foo(): |
|
272 | We can then call the function foo(): | |
272 |
|
273 | |||
273 | In [2]: foo() |
|
274 | In [2]: foo() | |
274 | foo() was defined in an editing session |
|
275 | foo() was defined in an editing session | |
275 |
|
276 | |||
276 | Now we edit foo. IPython automatically loads the editor with the |
|
277 | Now we edit foo. IPython automatically loads the editor with the | |
277 | (temporary) file where foo() was previously defined: |
|
278 | (temporary) file where foo() was previously defined: | |
278 |
|
279 | |||
279 | In [3]: ed foo |
|
280 | In [3]: ed foo | |
280 | Editing... done. Executing edited code... |
|
281 | Editing... done. Executing edited code... | |
281 |
|
282 | |||
282 | And if we call foo() again we get the modified version: |
|
283 | And if we call foo() again we get the modified version: | |
283 |
|
284 | |||
284 | In [4]: foo() |
|
285 | In [4]: foo() | |
285 | foo() has now been changed! |
|
286 | foo() has now been changed! | |
286 |
|
287 | |||
287 | Here is an example of how to edit a code snippet successive |
|
288 | Here is an example of how to edit a code snippet successive | |
288 | times. First we call the editor: |
|
289 | times. First we call the editor: | |
289 |
|
290 | |||
290 | In [5]: ed |
|
291 | In [5]: ed | |
291 | Editing... done. Executing edited code... |
|
292 | Editing... done. Executing edited code... | |
292 | hello |
|
293 | hello | |
293 | Out[5]: "print 'hello'n" |
|
294 | Out[5]: "print 'hello'n" | |
294 |
|
295 | |||
295 | Now we call it again with the previous output (stored in _): |
|
296 | Now we call it again with the previous output (stored in _): | |
296 |
|
297 | |||
297 | In [6]: ed _ |
|
298 | In [6]: ed _ | |
298 | Editing... done. Executing edited code... |
|
299 | Editing... done. Executing edited code... | |
299 | hello world |
|
300 | hello world | |
300 | Out[6]: "print 'hello world'n" |
|
301 | Out[6]: "print 'hello world'n" | |
301 |
|
302 | |||
302 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
303 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
303 |
|
304 | |||
304 | In [7]: ed _8 |
|
305 | In [7]: ed _8 | |
305 | Editing... done. Executing edited code... |
|
306 | Editing... done. Executing edited code... | |
306 | hello again |
|
307 | hello again | |
307 | Out[7]: "print 'hello again'n" |
|
308 | Out[7]: "print 'hello again'n" | |
308 | """ |
|
309 | """ | |
309 |
|
310 | |||
310 | opts,args = self.parse_options(parameter_s,'prn:') |
|
311 | opts,args = self.parse_options(parameter_s,'prn:') | |
311 |
|
312 | |||
312 | try: |
|
313 | try: | |
313 | filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call) |
|
314 | filename, lineno, _ = CodeMagics._find_edit_target(self.shell, args, opts, last_call) | |
314 | except MacroToEdit as e: |
|
315 | except MacroToEdit as e: | |
315 | # TODO: Implement macro editing over 2 processes. |
|
316 | # TODO: Implement macro editing over 2 processes. | |
316 | print("Macro editing not yet implemented in 2-process model.") |
|
317 | print("Macro editing not yet implemented in 2-process model.") | |
317 | return |
|
318 | return | |
318 |
|
319 | |||
319 | # Make sure we send to the client an absolute path, in case the working |
|
320 | # Make sure we send to the client an absolute path, in case the working | |
320 | # directory of client and kernel don't match |
|
321 | # directory of client and kernel don't match | |
321 | filename = os.path.abspath(filename) |
|
322 | filename = os.path.abspath(filename) | |
322 |
|
323 | |||
323 | payload = { |
|
324 | payload = { | |
324 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
325 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
325 | 'filename' : filename, |
|
326 | 'filename' : filename, | |
326 | 'line_number' : lineno |
|
327 | 'line_number' : lineno | |
327 | } |
|
328 | } | |
328 | self.shell.payload_manager.write_payload(payload) |
|
329 | self.shell.payload_manager.write_payload(payload) | |
329 |
|
330 | |||
330 | # A few magics that are adapted to the specifics of using pexpect and a |
|
331 | # A few magics that are adapted to the specifics of using pexpect and a | |
331 | # remote terminal |
|
332 | # remote terminal | |
332 |
|
333 | |||
333 | @line_magic |
|
334 | @line_magic | |
334 | def clear(self, arg_s): |
|
335 | def clear(self, arg_s): | |
335 | """Clear the terminal.""" |
|
336 | """Clear the terminal.""" | |
336 | if os.name == 'posix': |
|
337 | if os.name == 'posix': | |
337 | self.shell.system("clear") |
|
338 | self.shell.system("clear") | |
338 | else: |
|
339 | else: | |
339 | self.shell.system("cls") |
|
340 | self.shell.system("cls") | |
340 |
|
341 | |||
341 | if os.name == 'nt': |
|
342 | if os.name == 'nt': | |
342 | # This is the usual name in windows |
|
343 | # This is the usual name in windows | |
343 | cls = line_magic('cls')(clear) |
|
344 | cls = line_magic('cls')(clear) | |
344 |
|
345 | |||
345 | # Terminal pagers won't work over pexpect, but we do have our own pager |
|
346 | # Terminal pagers won't work over pexpect, but we do have our own pager | |
346 |
|
347 | |||
347 | @line_magic |
|
348 | @line_magic | |
348 | def less(self, arg_s): |
|
349 | def less(self, arg_s): | |
349 | """Show a file through the pager. |
|
350 | """Show a file through the pager. | |
350 |
|
351 | |||
351 | Files ending in .py are syntax-highlighted.""" |
|
352 | Files ending in .py are syntax-highlighted.""" | |
|
353 | if not arg_s: | |||
|
354 | raise UsageError('Missing filename.') | |||
|
355 | ||||
352 | cont = open(arg_s).read() |
|
356 | cont = open(arg_s).read() | |
353 | if arg_s.endswith('.py'): |
|
357 | if arg_s.endswith('.py'): | |
354 | cont = self.shell.pycolorize(cont) |
|
358 | cont = self.shell.pycolorize(cont) | |
355 | page.page(cont) |
|
359 | page.page(cont) | |
356 |
|
360 | |||
357 | more = line_magic('more')(less) |
|
361 | more = line_magic('more')(less) | |
358 |
|
362 | |||
359 | # Man calls a pager, so we also need to redefine it |
|
363 | # Man calls a pager, so we also need to redefine it | |
360 | if os.name == 'posix': |
|
364 | if os.name == 'posix': | |
361 | @line_magic |
|
365 | @line_magic | |
362 | def man(self, arg_s): |
|
366 | def man(self, arg_s): | |
363 | """Find the man page for the given command and display in pager.""" |
|
367 | """Find the man page for the given command and display in pager.""" | |
364 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, |
|
368 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, | |
365 | split=False)) |
|
369 | split=False)) | |
366 |
|
370 | |||
367 | @line_magic |
|
371 | @line_magic | |
368 | def connect_info(self, arg_s): |
|
372 | def connect_info(self, arg_s): | |
369 | """Print information for connecting other clients to this kernel |
|
373 | """Print information for connecting other clients to this kernel | |
370 |
|
374 | |||
371 | It will print the contents of this session's connection file, as well as |
|
375 | It will print the contents of this session's connection file, as well as | |
372 | shortcuts for local clients. |
|
376 | shortcuts for local clients. | |
373 |
|
377 | |||
374 | In the simplest case, when called from the most recently launched kernel, |
|
378 | In the simplest case, when called from the most recently launched kernel, | |
375 | secondary clients can be connected, simply with: |
|
379 | secondary clients can be connected, simply with: | |
376 |
|
380 | |||
377 | $> ipython <app> --existing |
|
381 | $> ipython <app> --existing | |
378 |
|
382 | |||
379 | """ |
|
383 | """ | |
380 |
|
384 | |||
381 | from IPython.core.application import BaseIPythonApplication as BaseIPApp |
|
385 | from IPython.core.application import BaseIPythonApplication as BaseIPApp | |
382 |
|
386 | |||
383 | if BaseIPApp.initialized(): |
|
387 | if BaseIPApp.initialized(): | |
384 | app = BaseIPApp.instance() |
|
388 | app = BaseIPApp.instance() | |
385 | security_dir = app.profile_dir.security_dir |
|
389 | security_dir = app.profile_dir.security_dir | |
386 | profile = app.profile |
|
390 | profile = app.profile | |
387 | else: |
|
391 | else: | |
388 | profile = 'default' |
|
392 | profile = 'default' | |
389 | security_dir = '' |
|
393 | security_dir = '' | |
390 |
|
394 | |||
391 | try: |
|
395 | try: | |
392 | connection_file = get_connection_file() |
|
396 | connection_file = get_connection_file() | |
393 | info = get_connection_info(unpack=False) |
|
397 | info = get_connection_info(unpack=False) | |
394 | except Exception as e: |
|
398 | except Exception as e: | |
395 | error("Could not get connection info: %r" % e) |
|
399 | error("Could not get connection info: %r" % e) | |
396 | return |
|
400 | return | |
397 |
|
401 | |||
398 | # add profile flag for non-default profile |
|
402 | # add profile flag for non-default profile | |
399 | profile_flag = "--profile %s" % profile if profile != 'default' else "" |
|
403 | profile_flag = "--profile %s" % profile if profile != 'default' else "" | |
400 |
|
404 | |||
401 | # if it's in the security dir, truncate to basename |
|
405 | # if it's in the security dir, truncate to basename | |
402 | if security_dir == os.path.dirname(connection_file): |
|
406 | if security_dir == os.path.dirname(connection_file): | |
403 | connection_file = os.path.basename(connection_file) |
|
407 | connection_file = os.path.basename(connection_file) | |
404 |
|
408 | |||
405 |
|
409 | |||
406 | print (info + '\n') |
|
410 | print (info + '\n') | |
407 | print ("Paste the above JSON into a file, and connect with:\n" |
|
411 | print ("Paste the above JSON into a file, and connect with:\n" | |
408 | " $> ipython <app> --existing <file>\n" |
|
412 | " $> ipython <app> --existing <file>\n" | |
409 | "or, if you are local, you can connect with just:\n" |
|
413 | "or, if you are local, you can connect with just:\n" | |
410 | " $> ipython <app> --existing {0} {1}\n" |
|
414 | " $> ipython <app> --existing {0} {1}\n" | |
411 | "or even just:\n" |
|
415 | "or even just:\n" | |
412 | " $> ipython <app> --existing {1}\n" |
|
416 | " $> ipython <app> --existing {1}\n" | |
413 | "if this is the most recent IPython session you have started.".format( |
|
417 | "if this is the most recent IPython session you have started.".format( | |
414 | connection_file, profile_flag |
|
418 | connection_file, profile_flag | |
415 | ) |
|
419 | ) | |
416 | ) |
|
420 | ) | |
417 |
|
421 | |||
418 | @line_magic |
|
422 | @line_magic | |
419 | def qtconsole(self, arg_s): |
|
423 | def qtconsole(self, arg_s): | |
420 | """Open a qtconsole connected to this kernel. |
|
424 | """Open a qtconsole connected to this kernel. | |
421 |
|
425 | |||
422 | Useful for connecting a qtconsole to running notebooks, for better |
|
426 | Useful for connecting a qtconsole to running notebooks, for better | |
423 | debugging. |
|
427 | debugging. | |
424 | """ |
|
428 | """ | |
425 |
|
429 | |||
426 | # %qtconsole should imply bind_kernel for engines: |
|
430 | # %qtconsole should imply bind_kernel for engines: | |
427 | try: |
|
431 | try: | |
428 | from IPython.parallel import bind_kernel |
|
432 | from IPython.parallel import bind_kernel | |
429 | except ImportError: |
|
433 | except ImportError: | |
430 | # technically possible, because parallel has higher pyzmq min-version |
|
434 | # technically possible, because parallel has higher pyzmq min-version | |
431 | pass |
|
435 | pass | |
432 | else: |
|
436 | else: | |
433 | bind_kernel() |
|
437 | bind_kernel() | |
434 |
|
438 | |||
435 | try: |
|
439 | try: | |
436 | p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix')) |
|
440 | p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix')) | |
437 | except Exception as e: |
|
441 | except Exception as e: | |
438 | error("Could not start qtconsole: %r" % e) |
|
442 | error("Could not start qtconsole: %r" % e) | |
439 | return |
|
443 | return | |
440 |
|
444 | |||
441 | def safe_unicode(e): |
|
445 | def safe_unicode(e): | |
442 | """unicode(e) with various fallbacks. Used for exceptions, which may not be |
|
446 | """unicode(e) with various fallbacks. Used for exceptions, which may not be | |
443 | safe to call unicode() on. |
|
447 | safe to call unicode() on. | |
444 | """ |
|
448 | """ | |
445 | try: |
|
449 | try: | |
446 | return unicode(e) |
|
450 | return unicode(e) | |
447 | except UnicodeError: |
|
451 | except UnicodeError: | |
448 | pass |
|
452 | pass | |
449 |
|
453 | |||
450 | try: |
|
454 | try: | |
451 | return py3compat.str_to_unicode(str(e)) |
|
455 | return py3compat.str_to_unicode(str(e)) | |
452 | except UnicodeError: |
|
456 | except UnicodeError: | |
453 | pass |
|
457 | pass | |
454 |
|
458 | |||
455 | try: |
|
459 | try: | |
456 | return py3compat.str_to_unicode(repr(e)) |
|
460 | return py3compat.str_to_unicode(repr(e)) | |
457 | except UnicodeError: |
|
461 | except UnicodeError: | |
458 | pass |
|
462 | pass | |
459 |
|
463 | |||
460 | return u'Unrecoverably corrupt evalue' |
|
464 | return u'Unrecoverably corrupt evalue' | |
461 |
|
465 | |||
462 |
|
466 | |||
463 | class ZMQInteractiveShell(InteractiveShell): |
|
467 | class ZMQInteractiveShell(InteractiveShell): | |
464 | """A subclass of InteractiveShell for ZMQ.""" |
|
468 | """A subclass of InteractiveShell for ZMQ.""" | |
465 |
|
469 | |||
466 | displayhook_class = Type(ZMQShellDisplayHook) |
|
470 | displayhook_class = Type(ZMQShellDisplayHook) | |
467 | display_pub_class = Type(ZMQDisplayPublisher) |
|
471 | display_pub_class = Type(ZMQDisplayPublisher) | |
468 | data_pub_class = Type(ZMQDataPublisher) |
|
472 | data_pub_class = Type(ZMQDataPublisher) | |
469 |
|
473 | |||
470 | # Override the traitlet in the parent class, because there's no point using |
|
474 | # Override the traitlet in the parent class, because there's no point using | |
471 | # readline for the kernel. Can be removed when the readline code is moved |
|
475 | # readline for the kernel. Can be removed when the readline code is moved | |
472 | # to the terminal frontend. |
|
476 | # to the terminal frontend. | |
473 | colors_force = CBool(True) |
|
477 | colors_force = CBool(True) | |
474 | readline_use = CBool(False) |
|
478 | readline_use = CBool(False) | |
475 | # autoindent has no meaning in a zmqshell, and attempting to enable it |
|
479 | # autoindent has no meaning in a zmqshell, and attempting to enable it | |
476 | # will print a warning in the absence of readline. |
|
480 | # will print a warning in the absence of readline. | |
477 | autoindent = CBool(False) |
|
481 | autoindent = CBool(False) | |
478 |
|
482 | |||
479 | exiter = Instance(ZMQExitAutocall) |
|
483 | exiter = Instance(ZMQExitAutocall) | |
480 | def _exiter_default(self): |
|
484 | def _exiter_default(self): | |
481 | return ZMQExitAutocall(self) |
|
485 | return ZMQExitAutocall(self) | |
482 |
|
486 | |||
483 | def _exit_now_changed(self, name, old, new): |
|
487 | def _exit_now_changed(self, name, old, new): | |
484 | """stop eventloop when exit_now fires""" |
|
488 | """stop eventloop when exit_now fires""" | |
485 | if new: |
|
489 | if new: | |
486 | loop = ioloop.IOLoop.instance() |
|
490 | loop = ioloop.IOLoop.instance() | |
487 | loop.add_timeout(time.time()+0.1, loop.stop) |
|
491 | loop.add_timeout(time.time()+0.1, loop.stop) | |
488 |
|
492 | |||
489 | keepkernel_on_exit = None |
|
493 | keepkernel_on_exit = None | |
490 |
|
494 | |||
491 | # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no |
|
495 | # Over ZeroMQ, GUI control isn't done with PyOS_InputHook as there is no | |
492 | # interactive input being read; we provide event loop support in ipkernel |
|
496 | # interactive input being read; we provide event loop support in ipkernel | |
493 | from .eventloops import enable_gui |
|
497 | from .eventloops import enable_gui | |
494 | enable_gui = staticmethod(enable_gui) |
|
498 | enable_gui = staticmethod(enable_gui) | |
495 |
|
499 | |||
496 | def init_environment(self): |
|
500 | def init_environment(self): | |
497 | """Configure the user's environment. |
|
501 | """Configure the user's environment. | |
498 |
|
502 | |||
499 | """ |
|
503 | """ | |
500 | env = os.environ |
|
504 | env = os.environ | |
501 | # These two ensure 'ls' produces nice coloring on BSD-derived systems |
|
505 | # These two ensure 'ls' produces nice coloring on BSD-derived systems | |
502 | env['TERM'] = 'xterm-color' |
|
506 | env['TERM'] = 'xterm-color' | |
503 | env['CLICOLOR'] = '1' |
|
507 | env['CLICOLOR'] = '1' | |
504 | # Since normal pagers don't work at all (over pexpect we don't have |
|
508 | # Since normal pagers don't work at all (over pexpect we don't have | |
505 | # single-key control of the subprocess), try to disable paging in |
|
509 | # single-key control of the subprocess), try to disable paging in | |
506 | # subprocesses as much as possible. |
|
510 | # subprocesses as much as possible. | |
507 | env['PAGER'] = 'cat' |
|
511 | env['PAGER'] = 'cat' | |
508 | env['GIT_PAGER'] = 'cat' |
|
512 | env['GIT_PAGER'] = 'cat' | |
509 |
|
513 | |||
510 | # And install the payload version of page. |
|
514 | # And install the payload version of page. | |
511 | install_payload_page() |
|
515 | install_payload_page() | |
512 |
|
516 | |||
513 | def auto_rewrite_input(self, cmd): |
|
517 | def auto_rewrite_input(self, cmd): | |
514 | """Called to show the auto-rewritten input for autocall and friends. |
|
518 | """Called to show the auto-rewritten input for autocall and friends. | |
515 |
|
519 | |||
516 | FIXME: this payload is currently not correctly processed by the |
|
520 | FIXME: this payload is currently not correctly processed by the | |
517 | frontend. |
|
521 | frontend. | |
518 | """ |
|
522 | """ | |
519 | new = self.prompt_manager.render('rewrite') + cmd |
|
523 | new = self.prompt_manager.render('rewrite') + cmd | |
520 | payload = dict( |
|
524 | payload = dict( | |
521 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
525 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', | |
522 | transformed_input=new, |
|
526 | transformed_input=new, | |
523 | ) |
|
527 | ) | |
524 | self.payload_manager.write_payload(payload) |
|
528 | self.payload_manager.write_payload(payload) | |
525 |
|
529 | |||
526 | def ask_exit(self): |
|
530 | def ask_exit(self): | |
527 | """Engage the exit actions.""" |
|
531 | """Engage the exit actions.""" | |
528 | self.exit_now = True |
|
532 | self.exit_now = True | |
529 | payload = dict( |
|
533 | payload = dict( | |
530 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
534 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', | |
531 | exit=True, |
|
535 | exit=True, | |
532 | keepkernel=self.keepkernel_on_exit, |
|
536 | keepkernel=self.keepkernel_on_exit, | |
533 | ) |
|
537 | ) | |
534 | self.payload_manager.write_payload(payload) |
|
538 | self.payload_manager.write_payload(payload) | |
535 |
|
539 | |||
536 | def _showtraceback(self, etype, evalue, stb): |
|
540 | def _showtraceback(self, etype, evalue, stb): | |
537 |
|
541 | |||
538 | exc_content = { |
|
542 | exc_content = { | |
539 | u'traceback' : stb, |
|
543 | u'traceback' : stb, | |
540 | u'ename' : unicode(etype.__name__), |
|
544 | u'ename' : unicode(etype.__name__), | |
541 | u'evalue' : safe_unicode(evalue) |
|
545 | u'evalue' : safe_unicode(evalue) | |
542 | } |
|
546 | } | |
543 |
|
547 | |||
544 | dh = self.displayhook |
|
548 | dh = self.displayhook | |
545 | # Send exception info over pub socket for other clients than the caller |
|
549 | # Send exception info over pub socket for other clients than the caller | |
546 | # to pick up |
|
550 | # to pick up | |
547 | topic = None |
|
551 | topic = None | |
548 | if dh.topic: |
|
552 | if dh.topic: | |
549 | topic = dh.topic.replace(b'pyout', b'pyerr') |
|
553 | topic = dh.topic.replace(b'pyout', b'pyerr') | |
550 |
|
554 | |||
551 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', json_clean(exc_content), dh.parent_header, ident=topic) |
|
555 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', json_clean(exc_content), dh.parent_header, ident=topic) | |
552 |
|
556 | |||
553 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
557 | # FIXME - Hack: store exception info in shell object. Right now, the | |
554 | # caller is reading this info after the fact, we need to fix this logic |
|
558 | # caller is reading this info after the fact, we need to fix this logic | |
555 | # to remove this hack. Even uglier, we need to store the error status |
|
559 | # to remove this hack. Even uglier, we need to store the error status | |
556 | # here, because in the main loop, the logic that sets it is being |
|
560 | # here, because in the main loop, the logic that sets it is being | |
557 | # skipped because runlines swallows the exceptions. |
|
561 | # skipped because runlines swallows the exceptions. | |
558 | exc_content[u'status'] = u'error' |
|
562 | exc_content[u'status'] = u'error' | |
559 | self._reply_content = exc_content |
|
563 | self._reply_content = exc_content | |
560 | # /FIXME |
|
564 | # /FIXME | |
561 |
|
565 | |||
562 | return exc_content |
|
566 | return exc_content | |
563 |
|
567 | |||
564 | def set_next_input(self, text): |
|
568 | def set_next_input(self, text): | |
565 | """Send the specified text to the frontend to be presented at the next |
|
569 | """Send the specified text to the frontend to be presented at the next | |
566 | input cell.""" |
|
570 | input cell.""" | |
567 | payload = dict( |
|
571 | payload = dict( | |
568 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', |
|
572 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', | |
569 | text=text |
|
573 | text=text | |
570 | ) |
|
574 | ) | |
571 | self.payload_manager.write_payload(payload) |
|
575 | self.payload_manager.write_payload(payload) | |
572 |
|
576 | |||
573 | #------------------------------------------------------------------------- |
|
577 | #------------------------------------------------------------------------- | |
574 | # Things related to magics |
|
578 | # Things related to magics | |
575 | #------------------------------------------------------------------------- |
|
579 | #------------------------------------------------------------------------- | |
576 |
|
580 | |||
577 | def init_magics(self): |
|
581 | def init_magics(self): | |
578 | super(ZMQInteractiveShell, self).init_magics() |
|
582 | super(ZMQInteractiveShell, self).init_magics() | |
579 | self.register_magics(KernelMagics) |
|
583 | self.register_magics(KernelMagics) | |
580 | self.magics_manager.register_alias('ed', 'edit') |
|
584 | self.magics_manager.register_alias('ed', 'edit') | |
581 |
|
585 | |||
582 |
|
586 | |||
583 |
|
587 | |||
584 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
588 | InteractiveShellABC.register(ZMQInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now