File: ext_rescapture.py

package info (click to toggle)
ipython 0.13.1-2%2Bdeb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 15,752 kB
  • sloc: python: 69,537; makefile: 355; lisp: 272; sh: 80; objc: 37
file content (59 lines) | stat: -rw-r--r-- 1,382 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -*- coding: utf-8 -*-
""" IPython extension: new prefilters for output grabbing

Provides

var = %magic blah blah

var = !ls
"""

from IPython.core import ipapi
from IPython.core.error import TryNext
from IPython.utils.text import make_quoted_expr
from IPython.utils.genutils import *

ip = ipapi.get()

import re

def hnd_magic(line,mo):
    """ Handle a = %mymagic blah blah """
    var = mo.group('varname')
    cmd = mo.group('cmd')
    expr = make_quoted_expr(cmd)
    return itpl('$var = get_ipython().magic($expr)')

def hnd_syscmd(line,mo):
    """ Handle a = !ls """
    var = mo.group('varname')
    cmd = mo.group('cmd')
    expr = make_quoted_expr(itpl("sc -l =$cmd"))
    return itpl('$var = get_ipython().magic($expr)')

def install_re_handler(pat, hnd):
    ip.meta.re_prefilters.append((re.compile(pat), hnd))

def init_handlers():

    ip.meta.re_prefilters = []

    install_re_handler('(?P<varname>[\w\.]+)\s*=\s*%(?P<cmd>.*)',
                       hnd_magic
                       )

    install_re_handler('(?P<varname>[\w\.]+)\s*=\s*!(?P<cmd>.*)',
                       hnd_syscmd
                       )

init_handlers()

def regex_prefilter_f(self,line):
    for pat, handler in ip.meta.re_prefilters:
        mo = pat.match(line)
        if mo:
            return handler(line,mo)

    raise TryNext

ip.set_hook('input_prefilter', regex_prefilter_f)