Ulipad中Script的编写

Ulipad中有一个tool菜单,下面有一个script-script manager菜单选项,依据Ulipad的帮助文档,可以编写Python脚本,然后有由该菜单选项进行执行。

Ulipad帮助文档中,只提供了一个win的参数,并说明这个win参数是整个框架的win对象。具体是怎么进来的,Ulipad的文档并没有说明,今天在google group上咨询了limodou,说是用exec进行script的执行,然后在Ulipad目录中进行查找,找到了Script脚本执行的Python文件为mScript.py文件,里面有相关的代码,在执行的时候,Ulipad会传递下面的参数进去:

eid  当前事件id
index  菜单索引
filename 将要被执行的Python文件名,即script脚本
scripttext 脚本内容
code  将script脚本内容编译后生成的code对象,可以被exec执行
win  整个框架的win对象
event  事件类
wx.lib.dialogs 对话框类
trackback 模块
modules.common  模块

当然有些参数,并不是Ulipad有意传递进去的,因为exec的时候,Ulipad使用locals()函数获取了所有的局部变量。

因此,在进行脚本执行的时候,可以得到上面的这些参数。当然,最有用的肯定是win参数,其次,对于脚本本身的文件名(因为包含了路径),也是很重要的,每个执行脚本知道了自己的位置,就可以编写更灵活的代码,可以导入自己编写的代码,并重用这些代码。

在用Python编写代码的时候,我们通常需要编写自己的文件说明,这些说明通常有很大一部分是重复的,通过script来进行这方面的插入是很有必要的。

下面是script中关于这部分插入说明的代码:

代码
#! /usr/bin/env python
#coding
=utf-8

# author: ubunoon
# email: netubu#gmail.com
# blog: http:
//www.cnblogs.com/ubunoon
# date: 2010-5-15
# aim : insert comment
in ulipad

import datetime
import re

header
= re.compile(r'(#!.*\n#coding=.*)|(#!.*\n#-*-.*)|(#!.*)')
commenter
= re.compile(r'#author.*')
def iscomment(text):
return commenter.search( text ) is not None

def getHeader(text):
head
= ''
try:
match
= header.search( text )
match
= [ m for m in match.groups() if m is not None ]
head
= match[0]
except Exception:
pass
except AttributeError:
pass
return head

def run(win):
text
= win.document.GetText()
if iscomment(text):
return
comment
= '''
#author : ubunoon
#email: netubu#gmail.com
#blog : http:
//www.cnblogs.com/ubunoon
#date : %s
#aim :
''' %str(datetime.datetime.now() )

header
= getHeader(text)
if len(header) > 0:
text
= '%s\n%s\n%s' %(header, comment, text[len(header):] )
else:
text
='%s\n%s' %(comment, text )

win.document.SetText( text )
win.messagewindow.SetText( text ) # write information in message window


try:
run(win) # 在win不存在时,也可以被正确调用
except:
pass

由于filename的传递进来,可以对代码进行更多控制,比方说导入模块的控制,这些代码可能是自己编写的,并不在自己的packages库当中。

原文地址:https://www.cnblogs.com/ubunoon/p/1739557.html