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