ipy_render.py
67 lines
| 1.7 KiB
| text/x-python
|
PythonLexer
vivainio
|
r607 | #!/usr/bin/env python | |
vivainio
|
r614 | """ IPython extension: Render templates from variables and paste to clipbard """ | |
vivainio
|
r607 | import IPython.ipapi | |
ip = IPython.ipapi.get() | |||
from string import Template | |||
vivainio
|
r617 | import sys,os | |
vivainio
|
r607 | ||
vivainio
|
r614 | from IPython.Itpl import itplns | |
vivainio
|
r607 | def toclip_w32(s): | |
vivainio
|
r614 | """ Places contents of s to clipboard | |
vivainio
|
r613 | ||
Needs pyvin32 to work: | |||
http://sourceforge.net/projects/pywin32/ | |||
""" | |||
vivainio
|
r607 | import win32clipboard as cl | |
import win32con | |||
cl.OpenClipboard() | |||
cl.EmptyClipboard() | |||
vivainio
|
r617 | cl.SetClipboardText( s.replace('\n','\r\n' )) | |
vivainio
|
r607 | cl.CloseClipboard() | |
vivainio
|
r613 | try: | |
import win32clipboard | |||
vivainio
|
r607 | toclip = toclip_w32 | |
vivainio
|
r613 | except ImportError: | |
vivainio
|
r607 | def toclip(s): pass | |
def render(tmpl): | |||
vivainio
|
r614 | """ Render a template (Itpl format) from ipython variables | |
vivainio
|
r607 | ||
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 | |||
vivainio
|
r614 | ||
vivainio
|
r617 | # if template exist as a file, read it. Note: ;f hei vaan => f("hei vaan") | |
$ ;render c:/templates/greeting.txt | |||
vivainio
|
r614 | Template examples (Ka-Ping Yee's Itpl library): | |
vivainio
|
r607 | ||
vivainio
|
r614 | 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']. | |||
vivainio
|
r607 | """ | |
vivainio
|
r617 | if os.path.isfile(tmpl): | |
tmpl = open(tmpl).read() | |||
vivainio
|
r614 | res = itplns(tmpl, ip.user_ns) | |
vivainio
|
r607 | toclip(res) | |
return res | |||
vivainio
|
r613 | ip.to_user_ns('render') | |
vivainio
|
r607 |