code.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. """Implementation of code management magic functions.
  2. """
  3. from __future__ import print_function
  4. from __future__ import absolute_import
  5. #-----------------------------------------------------------------------------
  6. # Copyright (c) 2012 The IPython Development Team.
  7. #
  8. # Distributed under the terms of the Modified BSD License.
  9. #
  10. # The full license is in the file COPYING.txt, distributed with this software.
  11. #-----------------------------------------------------------------------------
  12. #-----------------------------------------------------------------------------
  13. # Imports
  14. #-----------------------------------------------------------------------------
  15. # Stdlib
  16. import inspect
  17. import io
  18. import os
  19. import re
  20. import sys
  21. import ast
  22. from itertools import chain
  23. # Our own packages
  24. from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
  25. from IPython.core.macro import Macro
  26. from IPython.core.magic import Magics, magics_class, line_magic
  27. from IPython.core.oinspect import find_file, find_source_lines
  28. from IPython.testing.skipdoctest import skip_doctest
  29. from IPython.utils import py3compat
  30. from IPython.utils.py3compat import string_types
  31. from IPython.utils.contexts import preserve_keys
  32. from IPython.utils.path import get_py_filename
  33. from warnings import warn
  34. from logging import error
  35. from IPython.utils.text import get_text_list
  36. #-----------------------------------------------------------------------------
  37. # Magic implementation classes
  38. #-----------------------------------------------------------------------------
  39. # Used for exception handling in magic_edit
  40. class MacroToEdit(ValueError): pass
  41. ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
  42. # To match, e.g. 8-10 1:5 :10 3-
  43. range_re = re.compile(r"""
  44. (?P<start>\d+)?
  45. ((?P<sep>[\-:])
  46. (?P<end>\d+)?)?
  47. $""", re.VERBOSE)
  48. def extract_code_ranges(ranges_str):
  49. """Turn a string of range for %%load into 2-tuples of (start, stop)
  50. ready to use as a slice of the content splitted by lines.
  51. Examples
  52. --------
  53. list(extract_input_ranges("5-10 2"))
  54. [(4, 10), (1, 2)]
  55. """
  56. for range_str in ranges_str.split():
  57. rmatch = range_re.match(range_str)
  58. if not rmatch:
  59. continue
  60. sep = rmatch.group("sep")
  61. start = rmatch.group("start")
  62. end = rmatch.group("end")
  63. if sep == '-':
  64. start = int(start) - 1 if start else None
  65. end = int(end) if end else None
  66. elif sep == ':':
  67. start = int(start) - 1 if start else None
  68. end = int(end) - 1 if end else None
  69. else:
  70. end = int(start)
  71. start = int(start) - 1
  72. yield (start, end)
  73. @skip_doctest
  74. def extract_symbols(code, symbols):
  75. """
  76. Return a tuple (blocks, not_found)
  77. where ``blocks`` is a list of code fragments
  78. for each symbol parsed from code, and ``not_found`` are
  79. symbols not found in the code.
  80. For example::
  81. >>> code = '''a = 10
  82. def b(): return 42
  83. class A: pass'''
  84. >>> extract_symbols(code, 'A,b,z')
  85. (["class A: pass", "def b(): return 42"], ['z'])
  86. """
  87. symbols = symbols.split(',')
  88. # this will raise SyntaxError if code isn't valid Python
  89. py_code = ast.parse(code)
  90. marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
  91. code = code.split('\n')
  92. symbols_lines = {}
  93. # we already know the start_lineno of each symbol (marks).
  94. # To find each end_lineno, we traverse in reverse order until each
  95. # non-blank line
  96. end = len(code)
  97. for name, start in reversed(marks):
  98. while not code[end - 1].strip():
  99. end -= 1
  100. if name:
  101. symbols_lines[name] = (start - 1, end)
  102. end = start - 1
  103. # Now symbols_lines is a map
  104. # {'symbol_name': (start_lineno, end_lineno), ...}
  105. # fill a list with chunks of codes for each requested symbol
  106. blocks = []
  107. not_found = []
  108. for symbol in symbols:
  109. if symbol in symbols_lines:
  110. start, end = symbols_lines[symbol]
  111. blocks.append('\n'.join(code[start:end]) + '\n')
  112. else:
  113. not_found.append(symbol)
  114. return blocks, not_found
  115. def strip_initial_indent(lines):
  116. """For %load, strip indent from lines until finding an unindented line.
  117. https://github.com/ipython/ipython/issues/9775
  118. """
  119. indent_re = re.compile(r'\s+')
  120. it = iter(lines)
  121. first_line = next(it)
  122. indent_match = indent_re.match(first_line)
  123. if indent_match:
  124. # First line was indented
  125. indent = indent_match.group()
  126. yield first_line[len(indent):]
  127. for line in it:
  128. if line.startswith(indent):
  129. yield line[len(indent):]
  130. else:
  131. # Less indented than the first line - stop dedenting
  132. yield line
  133. break
  134. else:
  135. yield first_line
  136. # Pass the remaining lines through without dedenting
  137. for line in it:
  138. yield line
  139. class InteractivelyDefined(Exception):
  140. """Exception for interactively defined variable in magic_edit"""
  141. def __init__(self, index):
  142. self.index = index
  143. @magics_class
  144. class CodeMagics(Magics):
  145. """Magics related to code management (loading, saving, editing, ...)."""
  146. def __init__(self, *args, **kwargs):
  147. self._knowntemps = set()
  148. super(CodeMagics, self).__init__(*args, **kwargs)
  149. @line_magic
  150. def save(self, parameter_s=''):
  151. """Save a set of lines or a macro to a given filename.
  152. Usage:\\
  153. %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
  154. Options:
  155. -r: use 'raw' input. By default, the 'processed' history is used,
  156. so that magics are loaded in their transformed version to valid
  157. Python. If this option is given, the raw input as typed as the
  158. command line is used instead.
  159. -f: force overwrite. If file exists, %save will prompt for overwrite
  160. unless -f is given.
  161. -a: append to the file instead of overwriting it.
  162. This function uses the same syntax as %history for input ranges,
  163. then saves the lines to the filename you specify.
  164. It adds a '.py' extension to the file if you don't do so yourself, and
  165. it asks for confirmation before overwriting existing files.
  166. If `-r` option is used, the default extension is `.ipy`.
  167. """
  168. opts,args = self.parse_options(parameter_s,'fra',mode='list')
  169. if not args:
  170. raise UsageError('Missing filename.')
  171. raw = 'r' in opts
  172. force = 'f' in opts
  173. append = 'a' in opts
  174. mode = 'a' if append else 'w'
  175. ext = u'.ipy' if raw else u'.py'
  176. fname, codefrom = args[0], " ".join(args[1:])
  177. if not fname.endswith((u'.py',u'.ipy')):
  178. fname += ext
  179. file_exists = os.path.isfile(fname)
  180. if file_exists and not force and not append:
  181. try:
  182. overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
  183. except StdinNotImplementedError:
  184. print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
  185. return
  186. if not overwrite :
  187. print('Operation cancelled.')
  188. return
  189. try:
  190. cmds = self.shell.find_user_code(codefrom,raw)
  191. except (TypeError, ValueError) as e:
  192. print(e.args[0])
  193. return
  194. out = py3compat.cast_unicode(cmds)
  195. with io.open(fname, mode, encoding="utf-8") as f:
  196. if not file_exists or not append:
  197. f.write(u"# coding: utf-8\n")
  198. f.write(out)
  199. # make sure we end on a newline
  200. if not out.endswith(u'\n'):
  201. f.write(u'\n')
  202. print('The following commands were written to file `%s`:' % fname)
  203. print(cmds)
  204. @line_magic
  205. def pastebin(self, parameter_s=''):
  206. """Upload code to Github's Gist paste bin, returning the URL.
  207. Usage:\\
  208. %pastebin [-d "Custom description"] 1-7
  209. The argument can be an input history range, a filename, or the name of a
  210. string or macro.
  211. Options:
  212. -d: Pass a custom description for the gist. The default will say
  213. "Pasted from IPython".
  214. """
  215. opts, args = self.parse_options(parameter_s, 'd:')
  216. try:
  217. code = self.shell.find_user_code(args)
  218. except (ValueError, TypeError) as e:
  219. print(e.args[0])
  220. return
  221. # Deferred import
  222. try:
  223. from urllib.request import urlopen # Py 3
  224. except ImportError:
  225. from urllib2 import urlopen
  226. import json
  227. post_data = json.dumps({
  228. "description": opts.get('d', "Pasted from IPython"),
  229. "public": True,
  230. "files": {
  231. "file1.py": {
  232. "content": code
  233. }
  234. }
  235. }).encode('utf-8')
  236. response = urlopen("https://api.github.com/gists", post_data)
  237. response_data = json.loads(response.read().decode('utf-8'))
  238. return response_data['html_url']
  239. @line_magic
  240. def loadpy(self, arg_s):
  241. """Alias of `%load`
  242. `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
  243. extension. So it has been renamed simply into %load. You can look at
  244. `%load`'s docstring for more info.
  245. """
  246. self.load(arg_s)
  247. @line_magic
  248. def load(self, arg_s):
  249. """Load code into the current frontend.
  250. Usage:\\
  251. %load [options] source
  252. where source can be a filename, URL, input history range, macro, or
  253. element in the user namespace
  254. Options:
  255. -r <lines>: Specify lines or ranges of lines to load from the source.
  256. Ranges could be specified as x-y (x..y) or in python-style x:y
  257. (x..(y-1)). Both limits x and y can be left blank (meaning the
  258. beginning and end of the file, respectively).
  259. -s <symbols>: Specify function or classes to load from python source.
  260. -y : Don't ask confirmation for loading source above 200 000 characters.
  261. -n : Include the user's namespace when searching for source code.
  262. This magic command can either take a local filename, a URL, an history
  263. range (see %history) or a macro as argument, it will prompt for
  264. confirmation before loading source with more than 200 000 characters, unless
  265. -y flag is passed or if the frontend does not support raw_input::
  266. %load myscript.py
  267. %load 7-27
  268. %load myMacro
  269. %load http://www.example.com/myscript.py
  270. %load -r 5-10 myscript.py
  271. %load -r 10-20,30,40: foo.py
  272. %load -s MyClass,wonder_function myscript.py
  273. %load -n MyClass
  274. %load -n my_module.wonder_function
  275. """
  276. opts,args = self.parse_options(arg_s,'yns:r:')
  277. if not args:
  278. raise UsageError('Missing filename, URL, input history range, '
  279. 'macro, or element in the user namespace.')
  280. search_ns = 'n' in opts
  281. contents = self.shell.find_user_code(args, search_ns=search_ns)
  282. if 's' in opts:
  283. try:
  284. blocks, not_found = extract_symbols(contents, opts['s'])
  285. except SyntaxError:
  286. # non python code
  287. error("Unable to parse the input as valid Python code")
  288. return
  289. if len(not_found) == 1:
  290. warn('The symbol `%s` was not found' % not_found[0])
  291. elif len(not_found) > 1:
  292. warn('The symbols %s were not found' % get_text_list(not_found,
  293. wrap_item_with='`')
  294. )
  295. contents = '\n'.join(blocks)
  296. if 'r' in opts:
  297. ranges = opts['r'].replace(',', ' ')
  298. lines = contents.split('\n')
  299. slices = extract_code_ranges(ranges)
  300. contents = [lines[slice(*slc)] for slc in slices]
  301. contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
  302. l = len(contents)
  303. # 200 000 is ~ 2500 full 80 caracter lines
  304. # so in average, more than 5000 lines
  305. if l > 200000 and 'y' not in opts:
  306. try:
  307. ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
  308. " (%d characters). Continue (y/[N]) ?" % l), default='n' )
  309. except StdinNotImplementedError:
  310. #asume yes if raw input not implemented
  311. ans = True
  312. if ans is False :
  313. print('Operation cancelled.')
  314. return
  315. contents = "# %load {}\n".format(arg_s) + contents
  316. self.shell.set_next_input(contents, replace=True)
  317. @staticmethod
  318. def _find_edit_target(shell, args, opts, last_call):
  319. """Utility method used by magic_edit to find what to edit."""
  320. def make_filename(arg):
  321. "Make a filename from the given args"
  322. try:
  323. filename = get_py_filename(arg)
  324. except IOError:
  325. # If it ends with .py but doesn't already exist, assume we want
  326. # a new file.
  327. if arg.endswith('.py'):
  328. filename = arg
  329. else:
  330. filename = None
  331. return filename
  332. # Set a few locals from the options for convenience:
  333. opts_prev = 'p' in opts
  334. opts_raw = 'r' in opts
  335. # custom exceptions
  336. class DataIsObject(Exception): pass
  337. # Default line number value
  338. lineno = opts.get('n',None)
  339. if opts_prev:
  340. args = '_%s' % last_call[0]
  341. if args not in shell.user_ns:
  342. args = last_call[1]
  343. # by default this is done with temp files, except when the given
  344. # arg is a filename
  345. use_temp = True
  346. data = ''
  347. # First, see if the arguments should be a filename.
  348. filename = make_filename(args)
  349. if filename:
  350. use_temp = False
  351. elif args:
  352. # Mode where user specifies ranges of lines, like in %macro.
  353. data = shell.extract_input_lines(args, opts_raw)
  354. if not data:
  355. try:
  356. # Load the parameter given as a variable. If not a string,
  357. # process it as an object instead (below)
  358. #print '*** args',args,'type',type(args) # dbg
  359. data = eval(args, shell.user_ns)
  360. if not isinstance(data, string_types):
  361. raise DataIsObject
  362. except (NameError,SyntaxError):
  363. # given argument is not a variable, try as a filename
  364. filename = make_filename(args)
  365. if filename is None:
  366. warn("Argument given (%s) can't be found as a variable "
  367. "or as a filename." % args)
  368. return (None, None, None)
  369. use_temp = False
  370. except DataIsObject:
  371. # macros have a special edit function
  372. if isinstance(data, Macro):
  373. raise MacroToEdit(data)
  374. # For objects, try to edit the file where they are defined
  375. filename = find_file(data)
  376. if filename:
  377. if 'fakemodule' in filename.lower() and \
  378. inspect.isclass(data):
  379. # class created by %edit? Try to find source
  380. # by looking for method definitions instead, the
  381. # __module__ in those classes is FakeModule.
  382. attrs = [getattr(data, aname) for aname in dir(data)]
  383. for attr in attrs:
  384. if not inspect.ismethod(attr):
  385. continue
  386. filename = find_file(attr)
  387. if filename and \
  388. 'fakemodule' not in filename.lower():
  389. # change the attribute to be the edit
  390. # target instead
  391. data = attr
  392. break
  393. m = ipython_input_pat.match(os.path.basename(filename))
  394. if m:
  395. raise InteractivelyDefined(int(m.groups()[0]))
  396. datafile = 1
  397. if filename is None:
  398. filename = make_filename(args)
  399. datafile = 1
  400. if filename is not None:
  401. # only warn about this if we get a real name
  402. warn('Could not find file where `%s` is defined.\n'
  403. 'Opening a file named `%s`' % (args, filename))
  404. # Now, make sure we can actually read the source (if it was
  405. # in a temp file it's gone by now).
  406. if datafile:
  407. if lineno is None:
  408. lineno = find_source_lines(data)
  409. if lineno is None:
  410. filename = make_filename(args)
  411. if filename is None:
  412. warn('The file where `%s` was defined '
  413. 'cannot be read or found.' % data)
  414. return (None, None, None)
  415. use_temp = False
  416. if use_temp:
  417. filename = shell.mktempfile(data)
  418. print('IPython will make a temporary file named:',filename)
  419. # use last_call to remember the state of the previous call, but don't
  420. # let it be clobbered by successive '-p' calls.
  421. try:
  422. last_call[0] = shell.displayhook.prompt_count
  423. if not opts_prev:
  424. last_call[1] = args
  425. except:
  426. pass
  427. return filename, lineno, use_temp
  428. def _edit_macro(self,mname,macro):
  429. """open an editor with the macro data in a file"""
  430. filename = self.shell.mktempfile(macro.value)
  431. self.shell.hooks.editor(filename)
  432. # and make a new macro object, to replace the old one
  433. with open(filename) as mfile:
  434. mvalue = mfile.read()
  435. self.shell.user_ns[mname] = Macro(mvalue)
  436. @skip_doctest
  437. @line_magic
  438. def edit(self, parameter_s='',last_call=['','']):
  439. """Bring up an editor and execute the resulting code.
  440. Usage:
  441. %edit [options] [args]
  442. %edit runs IPython's editor hook. The default version of this hook is
  443. set to call the editor specified by your $EDITOR environment variable.
  444. If this isn't found, it will default to vi under Linux/Unix and to
  445. notepad under Windows. See the end of this docstring for how to change
  446. the editor hook.
  447. You can also set the value of this editor via the
  448. ``TerminalInteractiveShell.editor`` option in your configuration file.
  449. This is useful if you wish to use a different editor from your typical
  450. default with IPython (and for Windows users who typically don't set
  451. environment variables).
  452. This command allows you to conveniently edit multi-line code right in
  453. your IPython session.
  454. If called without arguments, %edit opens up an empty editor with a
  455. temporary file and will execute the contents of this file when you
  456. close it (don't forget to save it!).
  457. Options:
  458. -n <number>: open the editor at a specified line number. By default,
  459. the IPython editor hook uses the unix syntax 'editor +N filename', but
  460. you can configure this by providing your own modified hook if your
  461. favorite editor supports line-number specifications with a different
  462. syntax.
  463. -p: this will call the editor with the same data as the previous time
  464. it was used, regardless of how long ago (in your current session) it
  465. was.
  466. -r: use 'raw' input. This option only applies to input taken from the
  467. user's history. By default, the 'processed' history is used, so that
  468. magics are loaded in their transformed version to valid Python. If
  469. this option is given, the raw input as typed as the command line is
  470. used instead. When you exit the editor, it will be executed by
  471. IPython's own processor.
  472. -x: do not execute the edited code immediately upon exit. This is
  473. mainly useful if you are editing programs which need to be called with
  474. command line arguments, which you can then do using %run.
  475. Arguments:
  476. If arguments are given, the following possibilities exist:
  477. - If the argument is a filename, IPython will load that into the
  478. editor. It will execute its contents with execfile() when you exit,
  479. loading any code in the file into your interactive namespace.
  480. - The arguments are ranges of input history, e.g. "7 ~1/4-6".
  481. The syntax is the same as in the %history magic.
  482. - If the argument is a string variable, its contents are loaded
  483. into the editor. You can thus edit any string which contains
  484. python code (including the result of previous edits).
  485. - If the argument is the name of an object (other than a string),
  486. IPython will try to locate the file where it was defined and open the
  487. editor at the point where it is defined. You can use `%edit function`
  488. to load an editor exactly at the point where 'function' is defined,
  489. edit it and have the file be executed automatically.
  490. - If the object is a macro (see %macro for details), this opens up your
  491. specified editor with a temporary file containing the macro's data.
  492. Upon exit, the macro is reloaded with the contents of the file.
  493. Note: opening at an exact line is only supported under Unix, and some
  494. editors (like kedit and gedit up to Gnome 2.8) do not understand the
  495. '+NUMBER' parameter necessary for this feature. Good editors like
  496. (X)Emacs, vi, jed, pico and joe all do.
  497. After executing your code, %edit will return as output the code you
  498. typed in the editor (except when it was an existing file). This way
  499. you can reload the code in further invocations of %edit as a variable,
  500. via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
  501. the output.
  502. Note that %edit is also available through the alias %ed.
  503. This is an example of creating a simple function inside the editor and
  504. then modifying it. First, start up the editor::
  505. In [1]: edit
  506. Editing... done. Executing edited code...
  507. Out[1]: 'def foo():\\n print "foo() was defined in an editing
  508. session"\\n'
  509. We can then call the function foo()::
  510. In [2]: foo()
  511. foo() was defined in an editing session
  512. Now we edit foo. IPython automatically loads the editor with the
  513. (temporary) file where foo() was previously defined::
  514. In [3]: edit foo
  515. Editing... done. Executing edited code...
  516. And if we call foo() again we get the modified version::
  517. In [4]: foo()
  518. foo() has now been changed!
  519. Here is an example of how to edit a code snippet successive
  520. times. First we call the editor::
  521. In [5]: edit
  522. Editing... done. Executing edited code...
  523. hello
  524. Out[5]: "print 'hello'\\n"
  525. Now we call it again with the previous output (stored in _)::
  526. In [6]: edit _
  527. Editing... done. Executing edited code...
  528. hello world
  529. Out[6]: "print 'hello world'\\n"
  530. Now we call it with the output #8 (stored in _8, also as Out[8])::
  531. In [7]: edit _8
  532. Editing... done. Executing edited code...
  533. hello again
  534. Out[7]: "print 'hello again'\\n"
  535. Changing the default editor hook:
  536. If you wish to write your own editor hook, you can put it in a
  537. configuration file which you load at startup time. The default hook
  538. is defined in the IPython.core.hooks module, and you can use that as a
  539. starting example for further modifications. That file also has
  540. general instructions on how to set a new hook for use once you've
  541. defined it."""
  542. opts,args = self.parse_options(parameter_s,'prxn:')
  543. try:
  544. filename, lineno, is_temp = self._find_edit_target(self.shell,
  545. args, opts, last_call)
  546. except MacroToEdit as e:
  547. self._edit_macro(args, e.args[0])
  548. return
  549. except InteractivelyDefined as e:
  550. print("Editing In[%i]" % e.index)
  551. args = str(e.index)
  552. filename, lineno, is_temp = self._find_edit_target(self.shell,
  553. args, opts, last_call)
  554. if filename is None:
  555. # nothing was found, warnings have already been issued,
  556. # just give up.
  557. return
  558. if is_temp:
  559. self._knowntemps.add(filename)
  560. elif (filename in self._knowntemps):
  561. is_temp = True
  562. # do actual editing here
  563. print('Editing...', end=' ')
  564. sys.stdout.flush()
  565. try:
  566. # Quote filenames that may have spaces in them
  567. if ' ' in filename:
  568. filename = "'%s'" % filename
  569. self.shell.hooks.editor(filename,lineno)
  570. except TryNext:
  571. warn('Could not open editor')
  572. return
  573. # XXX TODO: should this be generalized for all string vars?
  574. # For now, this is special-cased to blocks created by cpaste
  575. if args.strip() == 'pasted_block':
  576. with open(filename, 'r') as f:
  577. self.shell.user_ns['pasted_block'] = f.read()
  578. if 'x' in opts: # -x prevents actual execution
  579. print()
  580. else:
  581. print('done. Executing edited code...')
  582. with preserve_keys(self.shell.user_ns, '__file__'):
  583. if not is_temp:
  584. self.shell.user_ns['__file__'] = filename
  585. if 'r' in opts: # Untranslated IPython code
  586. with open(filename, 'r') as f:
  587. source = f.read()
  588. self.shell.run_cell(source, store_history=False)
  589. else:
  590. self.shell.safe_execfile(filename, self.shell.user_ns,
  591. self.shell.user_ns)
  592. if is_temp:
  593. try:
  594. return open(filename).read()
  595. except IOError as msg:
  596. if msg.filename == filename:
  597. warn('File not found. Did you forget to save?')
  598. return
  599. else:
  600. self.shell.showtraceback()