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