ext_rescapture.py
63 lines
| 1.5 KiB
| text/x-python
|
PythonLexer
vivainio
|
r151 | # -*- coding: utf-8 -*- | ||
""" IPython extension: new prefilters for output grabbing | ||||
Provides | ||||
var = %magic blah blah | ||||
var = !ls | ||||
""" | ||||
Brian Granger
|
r2027 | from IPython.core import ipapi | ||
Brian Granger
|
r2023 | from IPython.utils.genutils import * | ||
vivainio
|
r151 | |||
Brian Granger
|
r2027 | ip = ipapi.get() | ||
vivainio
|
r151 | |||
import re | ||||
def hnd_magic(line,mo): | ||||
""" Handle a = %mymagic blah blah """ | ||||
#cmd = genutils.make_quoted_expr(mo.group('syscmd')) | ||||
#mag = 'ipmagic | ||||
#return "%s = %s" | ||||
var = mo.group('varname') | ||||
cmd = mo.group('cmd') | ||||
expr = make_quoted_expr(cmd) | ||||
vivainio
|
r158 | return itpl('$var = _ip.magic($expr)') | ||
vivainio
|
r151 | |||
def hnd_syscmd(line,mo): | ||||
""" Handle a = !ls """ | ||||
#cmd = genutils.make_quoted_expr(mo.group('syscmd')) | ||||
#mag = 'ipmagic | ||||
#return "%s = %s" | ||||
var = mo.group('varname') | ||||
cmd = mo.group('cmd') | ||||
vivainio
|
r902 | expr = make_quoted_expr(itpl("sc -l =$cmd")) | ||
vivainio
|
r158 | return itpl('$var = _ip.magic($expr)') | ||
vivainio
|
r151 | |||
def install_re_handler(pat, hnd): | ||||
fperez
|
r284 | ip.meta.re_prefilters.append((re.compile(pat), hnd)) | ||
vivainio
|
r151 | |||
def init_handlers(): | ||||
fperez
|
r284 | ip.meta.re_prefilters = [] | ||
vivainio
|
r151 | |||
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): | ||||
fperez
|
r284 | for pat, handler in ip.meta.re_prefilters: | ||
vivainio
|
r151 | mo = pat.match(line) | ||
if mo: | ||||
return handler(line,mo) | ||||
Brian Granger
|
r2027 | raise ipapi.TryNext | ||
vivainio
|
r151 | |||
fperez
|
r284 | ip.set_hook('input_prefilter', regex_prefilter_f) | ||