Save a set of lines or a macro to a given filename. Usage:\\ %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... Options: -r: use 'raw' input. By default, the 'processed' history is used, so that magics are loaded in their transformed version to va
(self, parameter_s='')
| 180 | |
| 181 | @line_magic |
| 182 | def save(self, parameter_s=''): |
| 183 | """Save a set of lines or a macro to a given filename. |
| 184 | |
| 185 | Usage:\\ |
| 186 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
| 187 | |
| 188 | Options: |
| 189 | |
| 190 | -r: use 'raw' input. By default, the 'processed' history is used, |
| 191 | so that magics are loaded in their transformed version to valid |
| 192 | Python. If this option is given, the raw input as typed as the |
| 193 | command line is used instead. |
| 194 | |
| 195 | -f: force overwrite. If file exists, %save will prompt for overwrite |
| 196 | unless -f is given. |
| 197 | |
| 198 | -a: append to the file instead of overwriting it. |
| 199 | |
| 200 | This function uses the same syntax as %history for input ranges, |
| 201 | then saves the lines to the filename you specify. |
| 202 | |
| 203 | It adds a '.py' extension to the file if you don't do so yourself, and |
| 204 | it asks for confirmation before overwriting existing files. |
| 205 | |
| 206 | If `-r` option is used, the default extension is `.ipy`. |
| 207 | """ |
| 208 | |
| 209 | opts,args = self.parse_options(parameter_s,'fra',mode='list') |
| 210 | if not args: |
| 211 | raise UsageError('Missing filename.') |
| 212 | raw = 'r' in opts |
| 213 | force = 'f' in opts |
| 214 | append = 'a' in opts |
| 215 | mode = 'a' if append else 'w' |
| 216 | ext = '.ipy' if raw else '.py' |
| 217 | fname, codefrom = args[0], " ".join(args[1:]) |
| 218 | if not fname.endswith(('.py','.ipy')): |
| 219 | fname += ext |
| 220 | file_exists = os.path.isfile(fname) |
| 221 | if file_exists and not force and not append: |
| 222 | try: |
| 223 | overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') |
| 224 | except StdinNotImplementedError: |
| 225 | print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)) |
| 226 | return |
| 227 | if not overwrite : |
| 228 | print('Operation cancelled.') |
| 229 | return |
| 230 | try: |
| 231 | cmds = self.shell.find_user_code(codefrom,raw) |
| 232 | except (TypeError, ValueError) as e: |
| 233 | print(e.args[0]) |
| 234 | return |
| 235 | with io.open(fname, mode, encoding="utf-8") as f: |
| 236 | if not file_exists or not append: |
| 237 | f.write("# coding: utf-8\n") |
| 238 | f.write(cmds) |
| 239 | # make sure we end on a newline |