##// END OF EJS Templates
add %%file magic
MinRK -
Show More
@@ -1,677 +1,713
1 1 """Implementation of magic functions for interaction with the OS.
2 2
3 3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 4 builtin.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (c) 2012 The IPython Development Team.
8 8 #
9 9 # Distributed under the terms of the Modified BSD License.
10 10 #
11 11 # The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 # Stdlib
19 19 import os
20 20 import re
21 21 import sys
22 22 from pprint import pformat
23 23
24 24 # Our own packages
25 from IPython.core import magic_arguments
25 26 from IPython.core import oinspect
26 27 from IPython.core import page
27 28 from IPython.core.error import UsageError
28 from IPython.core.magic import (Magics, compress_dhist, magics_class,
29 line_magic)
29 from IPython.core.magic import (
30 Magics, compress_dhist, magics_class, line_magic, cell_magic
31 )
30 32 from IPython.testing.skipdoctest import skip_doctest
31 33 from IPython.utils.io import file_read, nlprint
32 34 from IPython.utils.path import get_py_filename, unquote_filename
33 35 from IPython.utils.process import abbrev_cwd
34 36 from IPython.utils.terminal import set_term_title
35 37 #-----------------------------------------------------------------------------
36 38 # Magic implementation classes
37 39 #-----------------------------------------------------------------------------
38 40 @magics_class
39 41 class OSMagics(Magics):
40 42 """Magics to interact with the underlying OS (shell-type functionality).
41 43 """
42 44
43 45 @skip_doctest
44 46 @line_magic
45 47 def alias(self, parameter_s=''):
46 48 """Define an alias for a system command.
47 49
48 50 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
49 51
50 52 Then, typing 'alias_name params' will execute the system command 'cmd
51 53 params' (from your underlying operating system).
52 54
53 55 Aliases have lower precedence than magic functions and Python normal
54 56 variables, so if 'foo' is both a Python variable and an alias, the
55 57 alias can not be executed until 'del foo' removes the Python variable.
56 58
57 59 You can use the %l specifier in an alias definition to represent the
58 60 whole line when the alias is called. For example::
59 61
60 62 In [2]: alias bracket echo "Input in brackets: <%l>"
61 63 In [3]: bracket hello world
62 64 Input in brackets: <hello world>
63 65
64 66 You can also define aliases with parameters using %s specifiers (one
65 67 per parameter)::
66 68
67 69 In [1]: alias parts echo first %s second %s
68 70 In [2]: %parts A B
69 71 first A second B
70 72 In [3]: %parts A
71 73 Incorrect number of arguments: 2 expected.
72 74 parts is an alias to: 'echo first %s second %s'
73 75
74 76 Note that %l and %s are mutually exclusive. You can only use one or
75 77 the other in your aliases.
76 78
77 79 Aliases expand Python variables just like system calls using ! or !!
78 80 do: all expressions prefixed with '$' get expanded. For details of
79 81 the semantic rules, see PEP-215:
80 82 http://www.python.org/peps/pep-0215.html. This is the library used by
81 83 IPython for variable expansion. If you want to access a true shell
82 84 variable, an extra $ is necessary to prevent its expansion by
83 85 IPython::
84 86
85 87 In [6]: alias show echo
86 88 In [7]: PATH='A Python string'
87 89 In [8]: show $PATH
88 90 A Python string
89 91 In [9]: show $$PATH
90 92 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
91 93
92 94 You can use the alias facility to acess all of $PATH. See the %rehash
93 95 and %rehashx functions, which automatically create aliases for the
94 96 contents of your $PATH.
95 97
96 98 If called with no parameters, %alias prints the current alias table."""
97 99
98 100 par = parameter_s.strip()
99 101 if not par:
100 102 aliases = sorted(self.shell.alias_manager.aliases)
101 103 # stored = self.shell.db.get('stored_aliases', {} )
102 104 # for k, v in stored:
103 105 # atab.append(k, v[0])
104 106
105 107 print "Total number of aliases:", len(aliases)
106 108 sys.stdout.flush()
107 109 return aliases
108 110
109 111 # Now try to define a new one
110 112 try:
111 113 alias,cmd = par.split(None, 1)
112 114 except:
113 115 print oinspect.getdoc(self.alias)
114 116 else:
115 117 self.shell.alias_manager.soft_define_alias(alias, cmd)
116 118 # end magic_alias
117 119
118 120 @line_magic
119 121 def unalias(self, parameter_s=''):
120 122 """Remove an alias"""
121 123
122 124 aname = parameter_s.strip()
123 125 self.shell.alias_manager.undefine_alias(aname)
124 126 stored = self.shell.db.get('stored_aliases', {} )
125 127 if aname in stored:
126 128 print "Removing %stored alias",aname
127 129 del stored[aname]
128 130 self.shell.db['stored_aliases'] = stored
129 131
130 132 @line_magic
131 133 def rehashx(self, parameter_s=''):
132 134 """Update the alias table with all executable files in $PATH.
133 135
134 136 This version explicitly checks that every entry in $PATH is a file
135 137 with execute access (os.X_OK), so it is much slower than %rehash.
136 138
137 139 Under Windows, it checks executability as a match against a
138 140 '|'-separated string of extensions, stored in the IPython config
139 141 variable win_exec_ext. This defaults to 'exe|com|bat'.
140 142
141 143 This function also resets the root module cache of module completer,
142 144 used on slow filesystems.
143 145 """
144 146 from IPython.core.alias import InvalidAliasError
145 147
146 148 # for the benefit of module completer in ipy_completers.py
147 149 del self.shell.db['rootmodules']
148 150
149 151 path = [os.path.abspath(os.path.expanduser(p)) for p in
150 152 os.environ.get('PATH','').split(os.pathsep)]
151 153 path = filter(os.path.isdir,path)
152 154
153 155 syscmdlist = []
154 156 # Now define isexec in a cross platform manner.
155 157 if os.name == 'posix':
156 158 isexec = lambda fname:os.path.isfile(fname) and \
157 159 os.access(fname,os.X_OK)
158 160 else:
159 161 try:
160 162 winext = os.environ['pathext'].replace(';','|').replace('.','')
161 163 except KeyError:
162 164 winext = 'exe|com|bat|py'
163 165 if 'py' not in winext:
164 166 winext += '|py'
165 167 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
166 168 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
167 169 savedir = os.getcwdu()
168 170
169 171 # Now walk the paths looking for executables to alias.
170 172 try:
171 173 # write the whole loop for posix/Windows so we don't have an if in
172 174 # the innermost part
173 175 if os.name == 'posix':
174 176 for pdir in path:
175 177 os.chdir(pdir)
176 178 for ff in os.listdir(pdir):
177 179 if isexec(ff):
178 180 try:
179 181 # Removes dots from the name since ipython
180 182 # will assume names with dots to be python.
181 183 self.shell.alias_manager.define_alias(
182 184 ff.replace('.',''), ff)
183 185 except InvalidAliasError:
184 186 pass
185 187 else:
186 188 syscmdlist.append(ff)
187 189 else:
188 190 no_alias = self.shell.alias_manager.no_alias
189 191 for pdir in path:
190 192 os.chdir(pdir)
191 193 for ff in os.listdir(pdir):
192 194 base, ext = os.path.splitext(ff)
193 195 if isexec(ff) and base.lower() not in no_alias:
194 196 if ext.lower() == '.exe':
195 197 ff = base
196 198 try:
197 199 # Removes dots from the name since ipython
198 200 # will assume names with dots to be python.
199 201 self.shell.alias_manager.define_alias(
200 202 base.lower().replace('.',''), ff)
201 203 except InvalidAliasError:
202 204 pass
203 205 syscmdlist.append(ff)
204 206 self.shell.db['syscmdlist'] = syscmdlist
205 207 finally:
206 208 os.chdir(savedir)
207 209
208 210 @skip_doctest
209 211 @line_magic
210 212 def pwd(self, parameter_s=''):
211 213 """Return the current working directory path.
212 214
213 215 Examples
214 216 --------
215 217 ::
216 218
217 219 In [9]: pwd
218 220 Out[9]: '/home/tsuser/sprint/ipython'
219 221 """
220 222 return os.getcwdu()
221 223
222 224 @skip_doctest
223 225 @line_magic
224 226 def cd(self, parameter_s=''):
225 227 """Change the current working directory.
226 228
227 229 This command automatically maintains an internal list of directories
228 230 you visit during your IPython session, in the variable _dh. The
229 231 command %dhist shows this history nicely formatted. You can also
230 232 do 'cd -<tab>' to see directory history conveniently.
231 233
232 234 Usage:
233 235
234 236 cd 'dir': changes to directory 'dir'.
235 237
236 238 cd -: changes to the last visited directory.
237 239
238 240 cd -<n>: changes to the n-th directory in the directory history.
239 241
240 242 cd --foo: change to directory that matches 'foo' in history
241 243
242 244 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
243 245 (note: cd <bookmark_name> is enough if there is no
244 246 directory <bookmark_name>, but a bookmark with the name exists.)
245 247 'cd -b <tab>' allows you to tab-complete bookmark names.
246 248
247 249 Options:
248 250
249 251 -q: quiet. Do not print the working directory after the cd command is
250 252 executed. By default IPython's cd command does print this directory,
251 253 since the default prompts do not display path information.
252 254
253 255 Note that !cd doesn't work for this purpose because the shell where
254 256 !command runs is immediately discarded after executing 'command'.
255 257
256 258 Examples
257 259 --------
258 260 ::
259 261
260 262 In [10]: cd parent/child
261 263 /home/tsuser/parent/child
262 264 """
263 265
264 266 oldcwd = os.getcwdu()
265 267 numcd = re.match(r'(-)(\d+)$',parameter_s)
266 268 # jump in directory history by number
267 269 if numcd:
268 270 nn = int(numcd.group(2))
269 271 try:
270 272 ps = self.shell.user_ns['_dh'][nn]
271 273 except IndexError:
272 274 print 'The requested directory does not exist in history.'
273 275 return
274 276 else:
275 277 opts = {}
276 278 elif parameter_s.startswith('--'):
277 279 ps = None
278 280 fallback = None
279 281 pat = parameter_s[2:]
280 282 dh = self.shell.user_ns['_dh']
281 283 # first search only by basename (last component)
282 284 for ent in reversed(dh):
283 285 if pat in os.path.basename(ent) and os.path.isdir(ent):
284 286 ps = ent
285 287 break
286 288
287 289 if fallback is None and pat in ent and os.path.isdir(ent):
288 290 fallback = ent
289 291
290 292 # if we have no last part match, pick the first full path match
291 293 if ps is None:
292 294 ps = fallback
293 295
294 296 if ps is None:
295 297 print "No matching entry in directory history"
296 298 return
297 299 else:
298 300 opts = {}
299 301
300 302
301 303 else:
302 304 #turn all non-space-escaping backslashes to slashes,
303 305 # for c:\windows\directory\names\
304 306 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
305 307 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
306 308 # jump to previous
307 309 if ps == '-':
308 310 try:
309 311 ps = self.shell.user_ns['_dh'][-2]
310 312 except IndexError:
311 313 raise UsageError('%cd -: No previous directory to change to.')
312 314 # jump to bookmark if needed
313 315 else:
314 316 if not os.path.isdir(ps) or 'b' in opts:
315 317 bkms = self.shell.db.get('bookmarks', {})
316 318
317 319 if ps in bkms:
318 320 target = bkms[ps]
319 321 print '(bookmark:%s) -> %s' % (ps, target)
320 322 ps = target
321 323 else:
322 324 if 'b' in opts:
323 325 raise UsageError("Bookmark '%s' not found. "
324 326 "Use '%%bookmark -l' to see your bookmarks." % ps)
325 327
326 328 # strip extra quotes on Windows, because os.chdir doesn't like them
327 329 ps = unquote_filename(ps)
328 330 # at this point ps should point to the target dir
329 331 if ps:
330 332 try:
331 333 os.chdir(os.path.expanduser(ps))
332 334 if hasattr(self.shell, 'term_title') and self.shell.term_title:
333 335 set_term_title('IPython: ' + abbrev_cwd())
334 336 except OSError:
335 337 print sys.exc_info()[1]
336 338 else:
337 339 cwd = os.getcwdu()
338 340 dhist = self.shell.user_ns['_dh']
339 341 if oldcwd != cwd:
340 342 dhist.append(cwd)
341 343 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
342 344
343 345 else:
344 346 os.chdir(self.shell.home_dir)
345 347 if hasattr(self.shell, 'term_title') and self.shell.term_title:
346 348 set_term_title('IPython: ' + '~')
347 349 cwd = os.getcwdu()
348 350 dhist = self.shell.user_ns['_dh']
349 351
350 352 if oldcwd != cwd:
351 353 dhist.append(cwd)
352 354 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
353 355 if not 'q' in opts and self.shell.user_ns['_dh']:
354 356 print self.shell.user_ns['_dh'][-1]
355 357
356 358
357 359 @line_magic
358 360 def env(self, parameter_s=''):
359 361 """List environment variables."""
360 362
361 363 return dict(os.environ)
362 364
363 365 @line_magic
364 366 def pushd(self, parameter_s=''):
365 367 """Place the current dir on stack and change directory.
366 368
367 369 Usage:\\
368 370 %pushd ['dirname']
369 371 """
370 372
371 373 dir_s = self.shell.dir_stack
372 374 tgt = os.path.expanduser(unquote_filename(parameter_s))
373 375 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
374 376 if tgt:
375 377 self.cd(parameter_s)
376 378 dir_s.insert(0,cwd)
377 379 return self.shell.magic('dirs')
378 380
379 381 @line_magic
380 382 def popd(self, parameter_s=''):
381 383 """Change to directory popped off the top of the stack.
382 384 """
383 385 if not self.shell.dir_stack:
384 386 raise UsageError("%popd on empty stack")
385 387 top = self.shell.dir_stack.pop(0)
386 388 self.cd(top)
387 389 print "popd ->",top
388 390
389 391 @line_magic
390 392 def dirs(self, parameter_s=''):
391 393 """Return the current directory stack."""
392 394
393 395 return self.shell.dir_stack
394 396
395 397 @line_magic
396 398 def dhist(self, parameter_s=''):
397 399 """Print your history of visited directories.
398 400
399 401 %dhist -> print full history\\
400 402 %dhist n -> print last n entries only\\
401 403 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
402 404
403 405 This history is automatically maintained by the %cd command, and
404 406 always available as the global list variable _dh. You can use %cd -<n>
405 407 to go to directory number <n>.
406 408
407 409 Note that most of time, you should view directory history by entering
408 410 cd -<TAB>.
409 411
410 412 """
411 413
412 414 dh = self.shell.user_ns['_dh']
413 415 if parameter_s:
414 416 try:
415 417 args = map(int,parameter_s.split())
416 418 except:
417 419 self.arg_err(self.dhist)
418 420 return
419 421 if len(args) == 1:
420 422 ini,fin = max(len(dh)-(args[0]),0),len(dh)
421 423 elif len(args) == 2:
422 424 ini,fin = args
423 425 else:
424 426 self.arg_err(self.dhist)
425 427 return
426 428 else:
427 429 ini,fin = 0,len(dh)
428 430 nlprint(dh,
429 431 header = 'Directory history (kept in _dh)',
430 432 start=ini,stop=fin)
431 433
432 434 @skip_doctest
433 435 @line_magic
434 436 def sc(self, parameter_s=''):
435 437 """Shell capture - execute a shell command and capture its output.
436 438
437 439 DEPRECATED. Suboptimal, retained for backwards compatibility.
438 440
439 441 You should use the form 'var = !command' instead. Example:
440 442
441 443 "%sc -l myfiles = ls ~" should now be written as
442 444
443 445 "myfiles = !ls ~"
444 446
445 447 myfiles.s, myfiles.l and myfiles.n still apply as documented
446 448 below.
447 449
448 450 --
449 451 %sc [options] varname=command
450 452
451 453 IPython will run the given command using commands.getoutput(), and
452 454 will then update the user's interactive namespace with a variable
453 455 called varname, containing the value of the call. Your command can
454 456 contain shell wildcards, pipes, etc.
455 457
456 458 The '=' sign in the syntax is mandatory, and the variable name you
457 459 supply must follow Python's standard conventions for valid names.
458 460
459 461 (A special format without variable name exists for internal use)
460 462
461 463 Options:
462 464
463 465 -l: list output. Split the output on newlines into a list before
464 466 assigning it to the given variable. By default the output is stored
465 467 as a single string.
466 468
467 469 -v: verbose. Print the contents of the variable.
468 470
469 471 In most cases you should not need to split as a list, because the
470 472 returned value is a special type of string which can automatically
471 473 provide its contents either as a list (split on newlines) or as a
472 474 space-separated string. These are convenient, respectively, either
473 475 for sequential processing or to be passed to a shell command.
474 476
475 477 For example::
476 478
477 479 # Capture into variable a
478 480 In [1]: sc a=ls *py
479 481
480 482 # a is a string with embedded newlines
481 483 In [2]: a
482 484 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
483 485
484 486 # which can be seen as a list:
485 487 In [3]: a.l
486 488 Out[3]: ['setup.py', 'win32_manual_post_install.py']
487 489
488 490 # or as a whitespace-separated string:
489 491 In [4]: a.s
490 492 Out[4]: 'setup.py win32_manual_post_install.py'
491 493
492 494 # a.s is useful to pass as a single command line:
493 495 In [5]: !wc -l $a.s
494 496 146 setup.py
495 497 130 win32_manual_post_install.py
496 498 276 total
497 499
498 500 # while the list form is useful to loop over:
499 501 In [6]: for f in a.l:
500 502 ...: !wc -l $f
501 503 ...:
502 504 146 setup.py
503 505 130 win32_manual_post_install.py
504 506
505 507 Similarly, the lists returned by the -l option are also special, in
506 508 the sense that you can equally invoke the .s attribute on them to
507 509 automatically get a whitespace-separated string from their contents::
508 510
509 511 In [7]: sc -l b=ls *py
510 512
511 513 In [8]: b
512 514 Out[8]: ['setup.py', 'win32_manual_post_install.py']
513 515
514 516 In [9]: b.s
515 517 Out[9]: 'setup.py win32_manual_post_install.py'
516 518
517 519 In summary, both the lists and strings used for output capture have
518 520 the following special attributes::
519 521
520 522 .l (or .list) : value as list.
521 523 .n (or .nlstr): value as newline-separated string.
522 524 .s (or .spstr): value as space-separated string.
523 525 """
524 526
525 527 opts,args = self.parse_options(parameter_s, 'lv')
526 528 # Try to get a variable name and command to run
527 529 try:
528 530 # the variable name must be obtained from the parse_options
529 531 # output, which uses shlex.split to strip options out.
530 532 var,_ = args.split('=', 1)
531 533 var = var.strip()
532 534 # But the command has to be extracted from the original input
533 535 # parameter_s, not on what parse_options returns, to avoid the
534 536 # quote stripping which shlex.split performs on it.
535 537 _,cmd = parameter_s.split('=', 1)
536 538 except ValueError:
537 539 var,cmd = '',''
538 540 # If all looks ok, proceed
539 541 split = 'l' in opts
540 542 out = self.shell.getoutput(cmd, split=split)
541 543 if 'v' in opts:
542 544 print '%s ==\n%s' % (var, pformat(out))
543 545 if var:
544 546 self.shell.user_ns.update({var:out})
545 547 else:
546 548 return out
547 549
548 550 @line_magic
549 551 def sx(self, parameter_s=''):
550 552 """Shell execute - run a shell command and capture its output.
551 553
552 554 %sx command
553 555
554 556 IPython will run the given command using commands.getoutput(), and
555 557 return the result formatted as a list (split on '\\n'). Since the
556 558 output is _returned_, it will be stored in ipython's regular output
557 559 cache Out[N] and in the '_N' automatic variables.
558 560
559 561 Notes:
560 562
561 563 1) If an input line begins with '!!', then %sx is automatically
562 564 invoked. That is, while::
563 565
564 566 !ls
565 567
566 568 causes ipython to simply issue system('ls'), typing::
567 569
568 570 !!ls
569 571
570 572 is a shorthand equivalent to::
571 573
572 574 %sx ls
573 575
574 576 2) %sx differs from %sc in that %sx automatically splits into a list,
575 577 like '%sc -l'. The reason for this is to make it as easy as possible
576 578 to process line-oriented shell output via further python commands.
577 579 %sc is meant to provide much finer control, but requires more
578 580 typing.
579 581
580 582 3) Just like %sc -l, this is a list with special attributes:
581 583 ::
582 584
583 585 .l (or .list) : value as list.
584 586 .n (or .nlstr): value as newline-separated string.
585 587 .s (or .spstr): value as whitespace-separated string.
586 588
587 589 This is very useful when trying to use such lists as arguments to
588 590 system commands."""
589 591
590 592 if parameter_s:
591 593 return self.shell.getoutput(parameter_s)
592 594
593 595
594 596 @line_magic
595 597 def bookmark(self, parameter_s=''):
596 598 """Manage IPython's bookmark system.
597 599
598 600 %bookmark <name> - set bookmark to current dir
599 601 %bookmark <name> <dir> - set bookmark to <dir>
600 602 %bookmark -l - list all bookmarks
601 603 %bookmark -d <name> - remove bookmark
602 604 %bookmark -r - remove all bookmarks
603 605
604 606 You can later on access a bookmarked folder with::
605 607
606 608 %cd -b <name>
607 609
608 610 or simply '%cd <name>' if there is no directory called <name> AND
609 611 there is such a bookmark defined.
610 612
611 613 Your bookmarks persist through IPython sessions, but they are
612 614 associated with each profile."""
613 615
614 616 opts,args = self.parse_options(parameter_s,'drl',mode='list')
615 617 if len(args) > 2:
616 618 raise UsageError("%bookmark: too many arguments")
617 619
618 620 bkms = self.shell.db.get('bookmarks',{})
619 621
620 622 if 'd' in opts:
621 623 try:
622 624 todel = args[0]
623 625 except IndexError:
624 626 raise UsageError(
625 627 "%bookmark -d: must provide a bookmark to delete")
626 628 else:
627 629 try:
628 630 del bkms[todel]
629 631 except KeyError:
630 632 raise UsageError(
631 633 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
632 634
633 635 elif 'r' in opts:
634 636 bkms = {}
635 637 elif 'l' in opts:
636 638 bks = bkms.keys()
637 639 bks.sort()
638 640 if bks:
639 641 size = max(map(len, bks))
640 642 else:
641 643 size = 0
642 644 fmt = '%-'+str(size)+'s -> %s'
643 645 print 'Current bookmarks:'
644 646 for bk in bks:
645 647 print fmt % (bk, bkms[bk])
646 648 else:
647 649 if not args:
648 650 raise UsageError("%bookmark: You must specify the bookmark name")
649 651 elif len(args)==1:
650 652 bkms[args[0]] = os.getcwdu()
651 653 elif len(args)==2:
652 654 bkms[args[0]] = args[1]
653 655 self.shell.db['bookmarks'] = bkms
654 656
655 657 @line_magic
656 658 def pycat(self, parameter_s=''):
657 659 """Show a syntax-highlighted file through a pager.
658 660
659 661 This magic is similar to the cat utility, but it will assume the file
660 662 to be Python source and will show it with syntax highlighting.
661 663
662 664 This magic command can either take a local filename, an url,
663 665 an history range (see %history) or a macro as argument ::
664 666
665 667 %pycat myscript.py
666 668 %pycat 7-27
667 669 %pycat myMacro
668 670 %pycat http://www.example.com/myscript.py
669 671 """
670 672
671 673 try :
672 674 cont = self.shell.find_user_code(parameter_s)
673 675 except ValueError, IOError:
674 676 print "Error: no such file, variable, URL, history range or macro"
675 677 return
676 678
677 679 page.page(self.shell.pycolorize(cont))
680
681 @magic_arguments.magic_arguments()
682 @magic_arguments.argument(
683 '-f', '--force', action='store_true', default=False,
684 help='Whether to overwrite a file if it already exists'
685 )
686 @magic_arguments.argument(
687 'filename', type=unicode,
688 help='file to write'
689 )
690 @cell_magic
691 def file(self, line, cell):
692 """Write a cell to a file
693
694 %%file [-f] filename
695
696 Writes the contents of the cell to a file.
697
698 Will not overwrite existing files unless `-f` is specified.
699 """
700 args = magic_arguments.parse_argstring(self.file, line)
701 args.filename = unquote_filename(args.filename)
702
703 if os.path.exists(args.filename):
704 if args.force:
705 print("Overwriting %s" % args.filename)
706 else:
707 error("%s already exists! Force overwrite with %%%%file -f\n" % args.filename)
708 return
709 else:
710 print("Writing %s" % args.filename)
711
712 with io.open(args.filename, 'w', encoding='utf-8') as f:
713 f.write(cell)
General Comments 0
You need to be logged in to leave comments. Login now