Show More
@@ -22,11 +22,13 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 ( |
|
|
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 |
@@ -675,3 +677,37 class OSMagics(Magics): | |||
|
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