ipy_render.py
65 lines
| 1.5 KiB
| text/x-python
|
PythonLexer
vivainio
|
r680 | """ IPython extension: Render templates from variables and paste to clipbard """ | ||
Brian Granger
|
r2027 | from IPython.core import ipapi | ||
vivainio
|
r680 | |||
Brian Granger
|
r2027 | ip = ipapi.get() | ||
vivainio
|
r680 | |||
from string import Template | ||||
import sys,os | ||||
Brian Granger
|
r2031 | from IPython.external.Itpl import itplns | ||
vivainio
|
r680 | |||
def toclip_w32(s): | ||||
""" Places contents of s to clipboard | ||||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | 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: | ||||
Bernardo B. Marques
|
r4872 | import win32clipboard | ||
vivainio
|
r680 | toclip = toclip_w32 | ||
except ImportError: | ||||
def toclip(s): pass | ||||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | |||
def render(tmpl): | ||||
""" Render a template (Itpl format) from ipython variables | ||||
Example: | ||||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | $ import ipy_render | ||
$ my_name = 'Bob' # %store this for convenience | ||||
$ t_submission_form = "Submission report, author: $my_name" # %store also | ||||
$ render t_submission_form | ||||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | => 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") | ||||
Bernardo B. Marques
|
r4872 | $ ;render c:/templates/greeting.txt | ||
vivainio
|
r680 | Template examples (Ka-Ping Yee's Itpl library): | ||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | 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']. | ||||
""" | ||||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | if os.path.isfile(tmpl): | ||
tmpl = open(tmpl).read() | ||||
Bernardo B. Marques
|
r4872 | |||
vivainio
|
r680 | res = itplns(tmpl, ip.user_ns) | ||
toclip(res) | ||||
return res | ||||
Brian Granger
|
r2205 | ip.push('render') | ||