##// END OF EJS Templates
Add option append (-a) to %save...
Dominik Dabrowski -
Show More
@@ -61,6 +61,9 b' class CodeMagics(Magics):'
61 -f: force overwrite. If file exists, %save will prompt for overwrite
61 -f: force overwrite. If file exists, %save will prompt for overwrite
62 unless -f is given.
62 unless -f is given.
63
63
64 -a: append to file. Open file in append mode and end every write
65 on a newline.
66
64 This function uses the same syntax as %history for input ranges,
67 This function uses the same syntax as %history for input ranges,
65 then saves the lines to the filename you specify.
68 then saves the lines to the filename you specify.
66
69
@@ -70,14 +73,16 b' class CodeMagics(Magics):'
70 If `-r` option is used, the default extension is `.ipy`.
73 If `-r` option is used, the default extension is `.ipy`.
71 """
74 """
72
75
73 opts,args = self.parse_options(parameter_s,'fr',mode='list')
76 opts,args = self.parse_options(parameter_s,'fra',mode='list')
74 raw = 'r' in opts
77 raw = 'r' in opts
75 force = 'f' in opts
78 force = 'f' in opts
79 append = 'a' in opts
80 mode = 'a' if append else 'w'
76 ext = u'.ipy' if raw else u'.py'
81 ext = u'.ipy' if raw else u'.py'
77 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
82 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
78 if not fname.endswith((u'.py',u'.ipy')):
83 if not fname.endswith((u'.py',u'.ipy')):
79 fname += ext
84 fname += ext
80 if os.path.isfile(fname) and not force:
85 if os.path.isfile(fname) and not force and not append:
81 try:
86 try:
82 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
87 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
83 except StdinNotImplementedError:
88 except StdinNotImplementedError:
@@ -91,9 +96,16 b' class CodeMagics(Magics):'
91 except (TypeError, ValueError) as e:
96 except (TypeError, ValueError) as e:
92 print e.args[0]
97 print e.args[0]
93 return
98 return
94 with io.open(fname,'w', encoding="utf-8") as f:
99 out = py3compat.cast_unicode(cmds)
95 f.write(u"# coding: utf-8\n")
100 with io.open(fname, mode, encoding="utf-8") as f:
96 f.write(py3compat.cast_unicode(cmds))
101 if append:
102 f.write(out)
103 # make sure we end on a newline
104 if not out.endswith(u'\n'):
105 f.write(u'\n')
106 else:
107 f.write(u"# coding: utf-8\n")
108 f.write(out)
97 print 'The following commands were written to file `%s`:' % fname
109 print 'The following commands were written to file `%s`:' % fname
98 print cmds
110 print cmds
99
111
General Comments 0
You need to be logged in to leave comments. Login now