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