PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/core/magics/code.py

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