ext_rescapture.py
58 lines
| 1.3 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
|
r2205 | from IPython.core.error import TryNext | ||
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 """ | ||||
var = mo.group('varname') | ||||
cmd = mo.group('cmd') | ||||
expr = make_quoted_expr(cmd) | ||||
Brian Granger
|
r2245 | return itpl('$var = get_ipython().magic($expr)') | ||
vivainio
|
r151 | |||
def hnd_syscmd(line,mo): | ||||
""" Handle a = !ls """ | ||||
var = mo.group('varname') | ||||
cmd = mo.group('cmd') | ||||
vivainio
|
r902 | expr = make_quoted_expr(itpl("sc -l =$cmd")) | ||
Brian Granger
|
r2245 | return itpl('$var = get_ipython().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() | ||||
Brian Granger
|
r2256 | 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
|
r2205 | raise TryNext | ||
vivainio
|
r151 | |||
fperez
|
r284 | ip.set_hook('input_prefilter', regex_prefilter_f) | ||