2011年2月12日 星期六

Cake: a python shell with a simple plugin system

Cake是一個python的shell操作介面,並實作了一個簡單的插件系統。

這裡下載

開啟

雙擊"CakeBoot.bat"即可開啟Cake。

操作說明

1. Shell
中間的Shell是主要的命令輸入介面。Shell的使用方式幾乎與python自帶的IDLE介面相同。
可使用的命令放置於cmdb模組的名稱空間中,因此在Shell中輸入
>>> dir(cmdb)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'callback_to_menubar', 'choice_one_dlg', 'error_dlg', 'file_open_dlg', 'file_save_dlg', 'hello_world', 'modlues_load', 'object_load', 'object_save', 'run_cmd']

即可獲得目前可使用的命令名稱,如欲查看命令的說明訊息,例如cmdb.error_dlg這個命令的說明,輸入
>>> help(cmdb.error_dlg)
Help on function error_dlg in module share.ui.SimpleDlg:

error_dlg(msg)
Popup an error message.

>>> error_dlg("ERROR!")

執行cmdb.error_dlg,輸入
>>> cmdb.error_dlg("NO")
即可看到一個彈出的錯誤訊息視窗。


2. Plugin

Cake在啟動時會匯入放置於路徑"cake\plugin"下的所有附檔名為py檔案。因此可從此處將自訂的命令匯入cake中。直接以一個plugin為例:
cake\plugin\hello_plugin.py
from cmdb import callback_to_menubar

def hello_world():
    print "Hello World"
    
callback_to_menubar(hello_world, "Plugin,Hello,World0")

callback_to_menubar函數提供自訂menubar的menu item的功能。
兩個參數,前一個為此menu item的call back函數,即是按下此menu item後要執行的函數。這裡將在按下menu item後執行hello_world()。
後一個參數則是此menu item在menubar上的放置路徑,這裡的"Plugin,Hello,World0"表示此menu item位於"Plugin"->"Hello"->"World0"
點擊"World0"即可執行hello_world()。於Shell介面會出現
>>> cmdb.hello_world()
Hello World
>>>
callback_to_menubar 函數除了在menubar上放置menu item,並且將回呼函數放入cmdb的名稱空間中。點擊menu item後的動作,只是在Shell介面執行回呼函數。因此也可以直接於Shell介面輸入相同的命令。換句話說,"點擊menu item"僅是取代在Shell介面鍵入函數名稱的動作。

2011年1月19日 星期三

在wxPython中使用自定event

參考網頁。一個簡單的測試程式如下:
import wx
import wx.lib.newevent

# regist a custom event
SomeNewEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent()

class TestWin(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        # bind event and event handler
        self.Bind(EVT_SOME_NEW_EVENT, self.handler)
        
        # trigger an event
        #     create an event
        evt = SomeNewEvent(attr1="hello", attr2=654)
        #     post this event
        wx.PostEvent(self, evt)

    # event handler
    def handler(self, evt):
        print evt.attr1, evt.attr2
 
app = wx.PySimpleApp()
app.TopWindow = TestWin()
app.TopWindow.Show()
app.MainLoop()