File: ipy_render.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 (67 lines) | stat: -rw-r--r-- 1,680 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
60
61
62
63
64
65
66
67
""" IPython extension: Render templates from variables and paste to clipbard """

from IPython.core import ipapi

ip = ipapi.get()

from string import Template
import sys,os

# We no longer bundle Itpl. If you update this module, you should use advanced
# string formatting instead.
from IPython.external.Itpl import itplns

def toclip_w32(s):
    """ Places contents of s to clipboard

    Needs pyvin32 to work:
    http://sourceforge.net/projects/pywin32/
    """
    import win32clipboard as cl
    import win32con
    cl.OpenClipboard()
    cl.EmptyClipboard()
    cl.SetClipboardText( s.replace('\n','\r\n' ))
    cl.CloseClipboard()

try:
    import win32clipboard
    toclip = toclip_w32
except ImportError:
    def toclip(s): pass


def render(tmpl):
    """ Render a template (Itpl format) from ipython variables

    Example:

    $ import ipy_render
    $ my_name = 'Bob'  # %store this for convenience
    $ t_submission_form = "Submission report, author: $my_name"  # %store also
    $ render t_submission_form

    => returns "Submission report, author: Bob" and copies to clipboard on win32

    # if template exist as a file, read it. Note: ;f hei vaan => f("hei vaan")
    $ ;render c:/templates/greeting.txt

    Template examples (Ka-Ping Yee's Itpl library):

    Here is a $string.
    Here is a $module.member.
    Here is an $object.member.
    Here is a $functioncall(with, arguments).
    Here is an ${arbitrary + expression}.
    Here is an $array[3] member.
    Here is a $dictionary['member'].
    """

    if os.path.isfile(tmpl):
        tmpl = open(tmpl).read()

    res = itplns(tmpl, ip.user_ns)
    toclip(res)
    return res

ip.push('render')