##// END OF EJS Templates
fix typo in %load docstring...
MinRK -
Show More
@@ -1,559 +1,559 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 os
18 import os
19 import re
19 import re
20 import sys
20 import sys
21
21
22 # Our own packages
22 # Our own packages
23 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
23 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
24 from IPython.core.macro import Macro
24 from IPython.core.macro import Macro
25 from IPython.core.magic import Magics, magics_class, line_magic
25 from IPython.core.magic import Magics, magics_class, line_magic
26 from IPython.core.oinspect import find_file, find_source_lines
26 from IPython.core.oinspect import find_file, find_source_lines
27 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils import py3compat
28 from IPython.utils import py3compat
29 from IPython.utils.contexts import preserve_keys
29 from IPython.utils.contexts import preserve_keys
30 from IPython.utils.path import get_py_filename, unquote_filename
30 from IPython.utils.path import get_py_filename, unquote_filename
31 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Magic implementation classes
34 # Magic implementation classes
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 # Used for exception handling in magic_edit
37 # Used for exception handling in magic_edit
38 class MacroToEdit(ValueError): pass
38 class MacroToEdit(ValueError): pass
39
39
40 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
40 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
41
41
42 class InteractivelyDefined(Exception):
42 class InteractivelyDefined(Exception):
43 """Exception for interactively defined variable in magic_edit"""
43 """Exception for interactively defined variable in magic_edit"""
44 def __init__(self, index):
44 def __init__(self, index):
45 self.index = index
45 self.index = index
46
46
47
47
48 @magics_class
48 @magics_class
49 class CodeMagics(Magics):
49 class CodeMagics(Magics):
50 """Magics related to code management (loading, saving, editing, ...)."""
50 """Magics related to code management (loading, saving, editing, ...)."""
51
51
52 @line_magic
52 @line_magic
53 def save(self, parameter_s=''):
53 def save(self, parameter_s=''):
54 """Save a set of lines or a macro to a given filename.
54 """Save a set of lines or a macro to a given filename.
55
55
56 Usage:\\
56 Usage:\\
57 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
57 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
58
58
59 Options:
59 Options:
60
60
61 -r: use 'raw' input. By default, the 'processed' history is used,
61 -r: use 'raw' input. By default, the 'processed' history is used,
62 so that magics are loaded in their transformed version to valid
62 so that magics are loaded in their transformed version to valid
63 Python. If this option is given, the raw input as typed as the
63 Python. If this option is given, the raw input as typed as the
64 command line is used instead.
64 command line is used instead.
65
65
66 -f: force overwrite. If file exists, %save will prompt for overwrite
66 -f: force overwrite. If file exists, %save will prompt for overwrite
67 unless -f is given.
67 unless -f is given.
68
68
69 -a: append to the file instead of overwriting it.
69 -a: append to the file instead of overwriting it.
70
70
71 This function uses the same syntax as %history for input ranges,
71 This function uses the same syntax as %history for input ranges,
72 then saves the lines to the filename you specify.
72 then saves the lines to the filename you specify.
73
73
74 It adds a '.py' extension to the file if you don't do so yourself, and
74 It adds a '.py' extension to the file if you don't do so yourself, and
75 it asks for confirmation before overwriting existing files.
75 it asks for confirmation before overwriting existing files.
76
76
77 If `-r` option is used, the default extension is `.ipy`.
77 If `-r` option is used, the default extension is `.ipy`.
78 """
78 """
79
79
80 opts,args = self.parse_options(parameter_s,'fra',mode='list')
80 opts,args = self.parse_options(parameter_s,'fra',mode='list')
81 if not args:
81 if not args:
82 raise UsageError('Missing filename.')
82 raise UsageError('Missing filename.')
83 raw = 'r' in opts
83 raw = 'r' in opts
84 force = 'f' in opts
84 force = 'f' in opts
85 append = 'a' in opts
85 append = 'a' in opts
86 mode = 'a' if append else 'w'
86 mode = 'a' if append else 'w'
87 ext = u'.ipy' if raw else u'.py'
87 ext = u'.ipy' if raw else u'.py'
88 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
88 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
89 if not fname.endswith((u'.py',u'.ipy')):
89 if not fname.endswith((u'.py',u'.ipy')):
90 fname += ext
90 fname += ext
91 file_exists = os.path.isfile(fname)
91 file_exists = os.path.isfile(fname)
92 if file_exists and not force and not append:
92 if file_exists and not force and not append:
93 try:
93 try:
94 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
94 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
95 except StdinNotImplementedError:
95 except StdinNotImplementedError:
96 print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)
96 print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)
97 return
97 return
98 if not overwrite :
98 if not overwrite :
99 print 'Operation cancelled.'
99 print 'Operation cancelled.'
100 return
100 return
101 try:
101 try:
102 cmds = self.shell.find_user_code(codefrom,raw)
102 cmds = self.shell.find_user_code(codefrom,raw)
103 except (TypeError, ValueError) as e:
103 except (TypeError, ValueError) as e:
104 print e.args[0]
104 print e.args[0]
105 return
105 return
106 out = py3compat.cast_unicode(cmds)
106 out = py3compat.cast_unicode(cmds)
107 with io.open(fname, mode, encoding="utf-8") as f:
107 with io.open(fname, mode, encoding="utf-8") as f:
108 if not file_exists or not append:
108 if not file_exists or not append:
109 f.write(u"# coding: utf-8\n")
109 f.write(u"# coding: utf-8\n")
110 f.write(out)
110 f.write(out)
111 # make sure we end on a newline
111 # make sure we end on a newline
112 if not out.endswith(u'\n'):
112 if not out.endswith(u'\n'):
113 f.write(u'\n')
113 f.write(u'\n')
114 print 'The following commands were written to file `%s`:' % fname
114 print 'The following commands were written to file `%s`:' % fname
115 print cmds
115 print cmds
116
116
117 @line_magic
117 @line_magic
118 def pastebin(self, parameter_s=''):
118 def pastebin(self, parameter_s=''):
119 """Upload code to Github's Gist paste bin, returning the URL.
119 """Upload code to Github's Gist paste bin, returning the URL.
120
120
121 Usage:\\
121 Usage:\\
122 %pastebin [-d "Custom description"] 1-7
122 %pastebin [-d "Custom description"] 1-7
123
123
124 The argument can be an input history range, a filename, or the name of a
124 The argument can be an input history range, a filename, or the name of a
125 string or macro.
125 string or macro.
126
126
127 Options:
127 Options:
128
128
129 -d: Pass a custom description for the gist. The default will say
129 -d: Pass a custom description for the gist. The default will say
130 "Pasted from IPython".
130 "Pasted from IPython".
131 """
131 """
132 opts, args = self.parse_options(parameter_s, 'd:')
132 opts, args = self.parse_options(parameter_s, 'd:')
133
133
134 try:
134 try:
135 code = self.shell.find_user_code(args)
135 code = self.shell.find_user_code(args)
136 except (ValueError, TypeError) as e:
136 except (ValueError, TypeError) as e:
137 print e.args[0]
137 print e.args[0]
138 return
138 return
139
139
140 from urllib2 import urlopen # Deferred import
140 from urllib2 import urlopen # Deferred import
141 import json
141 import json
142 post_data = json.dumps({
142 post_data = json.dumps({
143 "description": opts.get('d', "Pasted from IPython"),
143 "description": opts.get('d', "Pasted from IPython"),
144 "public": True,
144 "public": True,
145 "files": {
145 "files": {
146 "file1.py": {
146 "file1.py": {
147 "content": code
147 "content": code
148 }
148 }
149 }
149 }
150 }).encode('utf-8')
150 }).encode('utf-8')
151
151
152 response = urlopen("https://api.github.com/gists", post_data)
152 response = urlopen("https://api.github.com/gists", post_data)
153 response_data = json.loads(response.read().decode('utf-8'))
153 response_data = json.loads(response.read().decode('utf-8'))
154 return response_data['html_url']
154 return response_data['html_url']
155
155
156 @line_magic
156 @line_magic
157 def loadpy(self, arg_s):
157 def loadpy(self, arg_s):
158 """Alias of `%load`
158 """Alias of `%load`
159
159
160 `%loadpy` has gained some flexibility and droped the requirement of a `.py`
160 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
161 extension. So it has been renamed simply into %load. You can look at
161 extension. So it has been renamed simply into %load. You can look at
162 `%load`'s docstring for more info.
162 `%load`'s docstring for more info.
163 """
163 """
164 self.load(arg_s)
164 self.load(arg_s)
165
165
166 @line_magic
166 @line_magic
167 def load(self, arg_s):
167 def load(self, arg_s):
168 """Load code into the current frontend.
168 """Load code into the current frontend.
169
169
170 Usage:\\
170 Usage:\\
171 %load [options] source
171 %load [options] source
172
172
173 where source can be a filename, URL, input history range or macro
173 where source can be a filename, URL, input history range or macro
174
174
175 Options:
175 Options:
176 --------
176 --------
177 -y : Don't ask confirmation for loading source above 200 000 characters.
177 -y : Don't ask confirmation for loading source above 200 000 characters.
178
178
179 This magic command can either take a local filename, a URL, an history
179 This magic command can either take a local filename, a URL, an history
180 range (see %history) or a macro as argument, it will prompt for
180 range (see %history) or a macro as argument, it will prompt for
181 confirmation before loading source with more than 200 000 characters, unless
181 confirmation before loading source with more than 200 000 characters, unless
182 -y flag is passed or if the frontend does not support raw_input::
182 -y flag is passed or if the frontend does not support raw_input::
183
183
184 %load myscript.py
184 %load myscript.py
185 %load 7-27
185 %load 7-27
186 %load myMacro
186 %load myMacro
187 %load http://www.example.com/myscript.py
187 %load http://www.example.com/myscript.py
188 """
188 """
189 opts,args = self.parse_options(arg_s,'y')
189 opts,args = self.parse_options(arg_s,'y')
190 if not args:
190 if not args:
191 raise UsageError('Missing filename, URL, input history range, '
191 raise UsageError('Missing filename, URL, input history range, '
192 'or macro.')
192 'or macro.')
193
193
194 contents = self.shell.find_user_code(args)
194 contents = self.shell.find_user_code(args)
195 l = len(contents)
195 l = len(contents)
196
196
197 # 200 000 is ~ 2500 full 80 caracter lines
197 # 200 000 is ~ 2500 full 80 caracter lines
198 # so in average, more than 5000 lines
198 # so in average, more than 5000 lines
199 if l > 200000 and 'y' not in opts:
199 if l > 200000 and 'y' not in opts:
200 try:
200 try:
201 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
201 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
202 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
202 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
203 except StdinNotImplementedError:
203 except StdinNotImplementedError:
204 #asume yes if raw input not implemented
204 #asume yes if raw input not implemented
205 ans = True
205 ans = True
206
206
207 if ans is False :
207 if ans is False :
208 print 'Operation cancelled.'
208 print 'Operation cancelled.'
209 return
209 return
210
210
211 self.shell.set_next_input(contents)
211 self.shell.set_next_input(contents)
212
212
213 @staticmethod
213 @staticmethod
214 def _find_edit_target(shell, args, opts, last_call):
214 def _find_edit_target(shell, args, opts, last_call):
215 """Utility method used by magic_edit to find what to edit."""
215 """Utility method used by magic_edit to find what to edit."""
216
216
217 def make_filename(arg):
217 def make_filename(arg):
218 "Make a filename from the given args"
218 "Make a filename from the given args"
219 arg = unquote_filename(arg)
219 arg = unquote_filename(arg)
220 try:
220 try:
221 filename = get_py_filename(arg)
221 filename = get_py_filename(arg)
222 except IOError:
222 except IOError:
223 # If it ends with .py but doesn't already exist, assume we want
223 # If it ends with .py but doesn't already exist, assume we want
224 # a new file.
224 # a new file.
225 if arg.endswith('.py'):
225 if arg.endswith('.py'):
226 filename = arg
226 filename = arg
227 else:
227 else:
228 filename = None
228 filename = None
229 return filename
229 return filename
230
230
231 # Set a few locals from the options for convenience:
231 # Set a few locals from the options for convenience:
232 opts_prev = 'p' in opts
232 opts_prev = 'p' in opts
233 opts_raw = 'r' in opts
233 opts_raw = 'r' in opts
234
234
235 # custom exceptions
235 # custom exceptions
236 class DataIsObject(Exception): pass
236 class DataIsObject(Exception): pass
237
237
238 # Default line number value
238 # Default line number value
239 lineno = opts.get('n',None)
239 lineno = opts.get('n',None)
240
240
241 if opts_prev:
241 if opts_prev:
242 args = '_%s' % last_call[0]
242 args = '_%s' % last_call[0]
243 if args not in shell.user_ns:
243 if args not in shell.user_ns:
244 args = last_call[1]
244 args = last_call[1]
245
245
246 # by default this is done with temp files, except when the given
246 # by default this is done with temp files, except when the given
247 # arg is a filename
247 # arg is a filename
248 use_temp = True
248 use_temp = True
249
249
250 data = ''
250 data = ''
251
251
252 # First, see if the arguments should be a filename.
252 # First, see if the arguments should be a filename.
253 filename = make_filename(args)
253 filename = make_filename(args)
254 if filename:
254 if filename:
255 use_temp = False
255 use_temp = False
256 elif args:
256 elif args:
257 # Mode where user specifies ranges of lines, like in %macro.
257 # Mode where user specifies ranges of lines, like in %macro.
258 data = shell.extract_input_lines(args, opts_raw)
258 data = shell.extract_input_lines(args, opts_raw)
259 if not data:
259 if not data:
260 try:
260 try:
261 # Load the parameter given as a variable. If not a string,
261 # Load the parameter given as a variable. If not a string,
262 # process it as an object instead (below)
262 # process it as an object instead (below)
263
263
264 #print '*** args',args,'type',type(args) # dbg
264 #print '*** args',args,'type',type(args) # dbg
265 data = eval(args, shell.user_ns)
265 data = eval(args, shell.user_ns)
266 if not isinstance(data, basestring):
266 if not isinstance(data, basestring):
267 raise DataIsObject
267 raise DataIsObject
268
268
269 except (NameError,SyntaxError):
269 except (NameError,SyntaxError):
270 # given argument is not a variable, try as a filename
270 # given argument is not a variable, try as a filename
271 filename = make_filename(args)
271 filename = make_filename(args)
272 if filename is None:
272 if filename is None:
273 warn("Argument given (%s) can't be found as a variable "
273 warn("Argument given (%s) can't be found as a variable "
274 "or as a filename." % args)
274 "or as a filename." % args)
275 return (None, None, None)
275 return (None, None, None)
276 use_temp = False
276 use_temp = False
277
277
278 except DataIsObject:
278 except DataIsObject:
279 # macros have a special edit function
279 # macros have a special edit function
280 if isinstance(data, Macro):
280 if isinstance(data, Macro):
281 raise MacroToEdit(data)
281 raise MacroToEdit(data)
282
282
283 # For objects, try to edit the file where they are defined
283 # For objects, try to edit the file where they are defined
284 filename = find_file(data)
284 filename = find_file(data)
285 if filename:
285 if filename:
286 if 'fakemodule' in filename.lower() and \
286 if 'fakemodule' in filename.lower() and \
287 inspect.isclass(data):
287 inspect.isclass(data):
288 # class created by %edit? Try to find source
288 # class created by %edit? Try to find source
289 # by looking for method definitions instead, the
289 # by looking for method definitions instead, the
290 # __module__ in those classes is FakeModule.
290 # __module__ in those classes is FakeModule.
291 attrs = [getattr(data, aname) for aname in dir(data)]
291 attrs = [getattr(data, aname) for aname in dir(data)]
292 for attr in attrs:
292 for attr in attrs:
293 if not inspect.ismethod(attr):
293 if not inspect.ismethod(attr):
294 continue
294 continue
295 filename = find_file(attr)
295 filename = find_file(attr)
296 if filename and \
296 if filename and \
297 'fakemodule' not in filename.lower():
297 'fakemodule' not in filename.lower():
298 # change the attribute to be the edit
298 # change the attribute to be the edit
299 # target instead
299 # target instead
300 data = attr
300 data = attr
301 break
301 break
302
302
303 m = ipython_input_pat.match(os.path.basename(filename))
303 m = ipython_input_pat.match(os.path.basename(filename))
304 if m:
304 if m:
305 raise InteractivelyDefined(int(m.groups()[0]))
305 raise InteractivelyDefined(int(m.groups()[0]))
306
306
307 datafile = 1
307 datafile = 1
308 if filename is None:
308 if filename is None:
309 filename = make_filename(args)
309 filename = make_filename(args)
310 datafile = 1
310 datafile = 1
311 if filename is not None:
311 if filename is not None:
312 # only warn about this if we get a real name
312 # only warn about this if we get a real name
313 warn('Could not find file where `%s` is defined.\n'
313 warn('Could not find file where `%s` is defined.\n'
314 'Opening a file named `%s`' % (args, filename))
314 'Opening a file named `%s`' % (args, filename))
315 # Now, make sure we can actually read the source (if it was
315 # Now, make sure we can actually read the source (if it was
316 # in a temp file it's gone by now).
316 # in a temp file it's gone by now).
317 if datafile:
317 if datafile:
318 if lineno is None:
318 if lineno is None:
319 lineno = find_source_lines(data)
319 lineno = find_source_lines(data)
320 if lineno is None:
320 if lineno is None:
321 filename = make_filename(args)
321 filename = make_filename(args)
322 if filename is None:
322 if filename is None:
323 warn('The file where `%s` was defined '
323 warn('The file where `%s` was defined '
324 'cannot be read or found.' % data)
324 'cannot be read or found.' % data)
325 return (None, None, None)
325 return (None, None, None)
326 use_temp = False
326 use_temp = False
327
327
328 if use_temp:
328 if use_temp:
329 filename = shell.mktempfile(data)
329 filename = shell.mktempfile(data)
330 print 'IPython will make a temporary file named:',filename
330 print 'IPython will make a temporary file named:',filename
331
331
332 # use last_call to remember the state of the previous call, but don't
332 # use last_call to remember the state of the previous call, but don't
333 # let it be clobbered by successive '-p' calls.
333 # let it be clobbered by successive '-p' calls.
334 try:
334 try:
335 last_call[0] = shell.displayhook.prompt_count
335 last_call[0] = shell.displayhook.prompt_count
336 if not opts_prev:
336 if not opts_prev:
337 last_call[1] = args
337 last_call[1] = args
338 except:
338 except:
339 pass
339 pass
340
340
341
341
342 return filename, lineno, use_temp
342 return filename, lineno, use_temp
343
343
344 def _edit_macro(self,mname,macro):
344 def _edit_macro(self,mname,macro):
345 """open an editor with the macro data in a file"""
345 """open an editor with the macro data in a file"""
346 filename = self.shell.mktempfile(macro.value)
346 filename = self.shell.mktempfile(macro.value)
347 self.shell.hooks.editor(filename)
347 self.shell.hooks.editor(filename)
348
348
349 # and make a new macro object, to replace the old one
349 # and make a new macro object, to replace the old one
350 mfile = open(filename)
350 mfile = open(filename)
351 mvalue = mfile.read()
351 mvalue = mfile.read()
352 mfile.close()
352 mfile.close()
353 self.shell.user_ns[mname] = Macro(mvalue)
353 self.shell.user_ns[mname] = Macro(mvalue)
354
354
355 @skip_doctest
355 @skip_doctest
356 @line_magic
356 @line_magic
357 def edit(self, parameter_s='',last_call=['','']):
357 def edit(self, parameter_s='',last_call=['','']):
358 """Bring up an editor and execute the resulting code.
358 """Bring up an editor and execute the resulting code.
359
359
360 Usage:
360 Usage:
361 %edit [options] [args]
361 %edit [options] [args]
362
362
363 %edit runs IPython's editor hook. The default version of this hook is
363 %edit runs IPython's editor hook. The default version of this hook is
364 set to call the editor specified by your $EDITOR environment variable.
364 set to call the editor specified by your $EDITOR environment variable.
365 If this isn't found, it will default to vi under Linux/Unix and to
365 If this isn't found, it will default to vi under Linux/Unix and to
366 notepad under Windows. See the end of this docstring for how to change
366 notepad under Windows. See the end of this docstring for how to change
367 the editor hook.
367 the editor hook.
368
368
369 You can also set the value of this editor via the
369 You can also set the value of this editor via the
370 ``TerminalInteractiveShell.editor`` option in your configuration file.
370 ``TerminalInteractiveShell.editor`` option in your configuration file.
371 This is useful if you wish to use a different editor from your typical
371 This is useful if you wish to use a different editor from your typical
372 default with IPython (and for Windows users who typically don't set
372 default with IPython (and for Windows users who typically don't set
373 environment variables).
373 environment variables).
374
374
375 This command allows you to conveniently edit multi-line code right in
375 This command allows you to conveniently edit multi-line code right in
376 your IPython session.
376 your IPython session.
377
377
378 If called without arguments, %edit opens up an empty editor with a
378 If called without arguments, %edit opens up an empty editor with a
379 temporary file and will execute the contents of this file when you
379 temporary file and will execute the contents of this file when you
380 close it (don't forget to save it!).
380 close it (don't forget to save it!).
381
381
382
382
383 Options:
383 Options:
384
384
385 -n <number>: open the editor at a specified line number. By default,
385 -n <number>: open the editor at a specified line number. By default,
386 the IPython editor hook uses the unix syntax 'editor +N filename', but
386 the IPython editor hook uses the unix syntax 'editor +N filename', but
387 you can configure this by providing your own modified hook if your
387 you can configure this by providing your own modified hook if your
388 favorite editor supports line-number specifications with a different
388 favorite editor supports line-number specifications with a different
389 syntax.
389 syntax.
390
390
391 -p: this will call the editor with the same data as the previous time
391 -p: this will call the editor with the same data as the previous time
392 it was used, regardless of how long ago (in your current session) it
392 it was used, regardless of how long ago (in your current session) it
393 was.
393 was.
394
394
395 -r: use 'raw' input. This option only applies to input taken from the
395 -r: use 'raw' input. This option only applies to input taken from the
396 user's history. By default, the 'processed' history is used, so that
396 user's history. By default, the 'processed' history is used, so that
397 magics are loaded in their transformed version to valid Python. If
397 magics are loaded in their transformed version to valid Python. If
398 this option is given, the raw input as typed as the command line is
398 this option is given, the raw input as typed as the command line is
399 used instead. When you exit the editor, it will be executed by
399 used instead. When you exit the editor, it will be executed by
400 IPython's own processor.
400 IPython's own processor.
401
401
402 -x: do not execute the edited code immediately upon exit. This is
402 -x: do not execute the edited code immediately upon exit. This is
403 mainly useful if you are editing programs which need to be called with
403 mainly useful if you are editing programs which need to be called with
404 command line arguments, which you can then do using %run.
404 command line arguments, which you can then do using %run.
405
405
406
406
407 Arguments:
407 Arguments:
408
408
409 If arguments are given, the following possibilities exist:
409 If arguments are given, the following possibilities exist:
410
410
411 - If the argument is a filename, IPython will load that into the
411 - If the argument is a filename, IPython will load that into the
412 editor. It will execute its contents with execfile() when you exit,
412 editor. It will execute its contents with execfile() when you exit,
413 loading any code in the file into your interactive namespace.
413 loading any code in the file into your interactive namespace.
414
414
415 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
415 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
416 The syntax is the same as in the %history magic.
416 The syntax is the same as in the %history magic.
417
417
418 - If the argument is a string variable, its contents are loaded
418 - If the argument is a string variable, its contents are loaded
419 into the editor. You can thus edit any string which contains
419 into the editor. You can thus edit any string which contains
420 python code (including the result of previous edits).
420 python code (including the result of previous edits).
421
421
422 - If the argument is the name of an object (other than a string),
422 - If the argument is the name of an object (other than a string),
423 IPython will try to locate the file where it was defined and open the
423 IPython will try to locate the file where it was defined and open the
424 editor at the point where it is defined. You can use `%edit function`
424 editor at the point where it is defined. You can use `%edit function`
425 to load an editor exactly at the point where 'function' is defined,
425 to load an editor exactly at the point where 'function' is defined,
426 edit it and have the file be executed automatically.
426 edit it and have the file be executed automatically.
427
427
428 - If the object is a macro (see %macro for details), this opens up your
428 - If the object is a macro (see %macro for details), this opens up your
429 specified editor with a temporary file containing the macro's data.
429 specified editor with a temporary file containing the macro's data.
430 Upon exit, the macro is reloaded with the contents of the file.
430 Upon exit, the macro is reloaded with the contents of the file.
431
431
432 Note: opening at an exact line is only supported under Unix, and some
432 Note: opening at an exact line is only supported under Unix, and some
433 editors (like kedit and gedit up to Gnome 2.8) do not understand the
433 editors (like kedit and gedit up to Gnome 2.8) do not understand the
434 '+NUMBER' parameter necessary for this feature. Good editors like
434 '+NUMBER' parameter necessary for this feature. Good editors like
435 (X)Emacs, vi, jed, pico and joe all do.
435 (X)Emacs, vi, jed, pico and joe all do.
436
436
437 After executing your code, %edit will return as output the code you
437 After executing your code, %edit will return as output the code you
438 typed in the editor (except when it was an existing file). This way
438 typed in the editor (except when it was an existing file). This way
439 you can reload the code in further invocations of %edit as a variable,
439 you can reload the code in further invocations of %edit as a variable,
440 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
440 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
441 the output.
441 the output.
442
442
443 Note that %edit is also available through the alias %ed.
443 Note that %edit is also available through the alias %ed.
444
444
445 This is an example of creating a simple function inside the editor and
445 This is an example of creating a simple function inside the editor and
446 then modifying it. First, start up the editor::
446 then modifying it. First, start up the editor::
447
447
448 In [1]: edit
448 In [1]: edit
449 Editing... done. Executing edited code...
449 Editing... done. Executing edited code...
450 Out[1]: 'def foo():\\n print "foo() was defined in an editing
450 Out[1]: 'def foo():\\n print "foo() was defined in an editing
451 session"\\n'
451 session"\\n'
452
452
453 We can then call the function foo()::
453 We can then call the function foo()::
454
454
455 In [2]: foo()
455 In [2]: foo()
456 foo() was defined in an editing session
456 foo() was defined in an editing session
457
457
458 Now we edit foo. IPython automatically loads the editor with the
458 Now we edit foo. IPython automatically loads the editor with the
459 (temporary) file where foo() was previously defined::
459 (temporary) file where foo() was previously defined::
460
460
461 In [3]: edit foo
461 In [3]: edit foo
462 Editing... done. Executing edited code...
462 Editing... done. Executing edited code...
463
463
464 And if we call foo() again we get the modified version::
464 And if we call foo() again we get the modified version::
465
465
466 In [4]: foo()
466 In [4]: foo()
467 foo() has now been changed!
467 foo() has now been changed!
468
468
469 Here is an example of how to edit a code snippet successive
469 Here is an example of how to edit a code snippet successive
470 times. First we call the editor::
470 times. First we call the editor::
471
471
472 In [5]: edit
472 In [5]: edit
473 Editing... done. Executing edited code...
473 Editing... done. Executing edited code...
474 hello
474 hello
475 Out[5]: "print 'hello'\\n"
475 Out[5]: "print 'hello'\\n"
476
476
477 Now we call it again with the previous output (stored in _)::
477 Now we call it again with the previous output (stored in _)::
478
478
479 In [6]: edit _
479 In [6]: edit _
480 Editing... done. Executing edited code...
480 Editing... done. Executing edited code...
481 hello world
481 hello world
482 Out[6]: "print 'hello world'\\n"
482 Out[6]: "print 'hello world'\\n"
483
483
484 Now we call it with the output #8 (stored in _8, also as Out[8])::
484 Now we call it with the output #8 (stored in _8, also as Out[8])::
485
485
486 In [7]: edit _8
486 In [7]: edit _8
487 Editing... done. Executing edited code...
487 Editing... done. Executing edited code...
488 hello again
488 hello again
489 Out[7]: "print 'hello again'\\n"
489 Out[7]: "print 'hello again'\\n"
490
490
491
491
492 Changing the default editor hook:
492 Changing the default editor hook:
493
493
494 If you wish to write your own editor hook, you can put it in a
494 If you wish to write your own editor hook, you can put it in a
495 configuration file which you load at startup time. The default hook
495 configuration file which you load at startup time. The default hook
496 is defined in the IPython.core.hooks module, and you can use that as a
496 is defined in the IPython.core.hooks module, and you can use that as a
497 starting example for further modifications. That file also has
497 starting example for further modifications. That file also has
498 general instructions on how to set a new hook for use once you've
498 general instructions on how to set a new hook for use once you've
499 defined it."""
499 defined it."""
500 opts,args = self.parse_options(parameter_s,'prxn:')
500 opts,args = self.parse_options(parameter_s,'prxn:')
501
501
502 try:
502 try:
503 filename, lineno, is_temp = self._find_edit_target(self.shell,
503 filename, lineno, is_temp = self._find_edit_target(self.shell,
504 args, opts, last_call)
504 args, opts, last_call)
505 except MacroToEdit as e:
505 except MacroToEdit as e:
506 self._edit_macro(args, e.args[0])
506 self._edit_macro(args, e.args[0])
507 return
507 return
508 except InteractivelyDefined as e:
508 except InteractivelyDefined as e:
509 print "Editing In[%i]" % e.index
509 print "Editing In[%i]" % e.index
510 args = str(e.index)
510 args = str(e.index)
511 filename, lineno, is_temp = self._find_edit_target(self.shell,
511 filename, lineno, is_temp = self._find_edit_target(self.shell,
512 args, opts, last_call)
512 args, opts, last_call)
513 if filename is None:
513 if filename is None:
514 # nothing was found, warnings have already been issued,
514 # nothing was found, warnings have already been issued,
515 # just give up.
515 # just give up.
516 return
516 return
517
517
518 # do actual editing here
518 # do actual editing here
519 print 'Editing...',
519 print 'Editing...',
520 sys.stdout.flush()
520 sys.stdout.flush()
521 try:
521 try:
522 # Quote filenames that may have spaces in them
522 # Quote filenames that may have spaces in them
523 if ' ' in filename:
523 if ' ' in filename:
524 filename = "'%s'" % filename
524 filename = "'%s'" % filename
525 self.shell.hooks.editor(filename,lineno)
525 self.shell.hooks.editor(filename,lineno)
526 except TryNext:
526 except TryNext:
527 warn('Could not open editor')
527 warn('Could not open editor')
528 return
528 return
529
529
530 # XXX TODO: should this be generalized for all string vars?
530 # XXX TODO: should this be generalized for all string vars?
531 # For now, this is special-cased to blocks created by cpaste
531 # For now, this is special-cased to blocks created by cpaste
532 if args.strip() == 'pasted_block':
532 if args.strip() == 'pasted_block':
533 with open(filename, 'r') as f:
533 with open(filename, 'r') as f:
534 self.shell.user_ns['pasted_block'] = f.read()
534 self.shell.user_ns['pasted_block'] = f.read()
535
535
536 if 'x' in opts: # -x prevents actual execution
536 if 'x' in opts: # -x prevents actual execution
537 print
537 print
538 else:
538 else:
539 print 'done. Executing edited code...'
539 print 'done. Executing edited code...'
540 with preserve_keys(self.shell.user_ns, '__file__'):
540 with preserve_keys(self.shell.user_ns, '__file__'):
541 if not is_temp:
541 if not is_temp:
542 self.shell.user_ns['__file__'] = filename
542 self.shell.user_ns['__file__'] = filename
543 if 'r' in opts: # Untranslated IPython code
543 if 'r' in opts: # Untranslated IPython code
544 with open(filename, 'r') as f:
544 with open(filename, 'r') as f:
545 source = f.read()
545 source = f.read()
546 self.shell.run_cell(source, store_history=False)
546 self.shell.run_cell(source, store_history=False)
547 else:
547 else:
548 self.shell.safe_execfile(filename, self.shell.user_ns,
548 self.shell.safe_execfile(filename, self.shell.user_ns,
549 self.shell.user_ns)
549 self.shell.user_ns)
550
550
551 if is_temp:
551 if is_temp:
552 try:
552 try:
553 return open(filename).read()
553 return open(filename).read()
554 except IOError as msg:
554 except IOError as msg:
555 if msg.filename == filename:
555 if msg.filename == filename:
556 warn('File not found. Did you forget to save?')
556 warn('File not found. Did you forget to save?')
557 return
557 return
558 else:
558 else:
559 self.shell.showtraceback()
559 self.shell.showtraceback()
General Comments 0
You need to be logged in to leave comments. Login now