ython的方便不用說,VB6做GUI的簡單程度更不用說。二者混合編程的需求一直非常旺盛,但我苦苦搜尋了很久,始終未找到合適的解決方案。
在很長一段時間內,我都是通過創建、讀取、刪除臨時文件來在VB程序和Python程序間傳遞信息,麻煩,且低級。(如下)
比如下面是一個典型的處理流程

 

1. VB創建需要處理的文本please.txt,並調用Python

 

2. Python讀取、處理文本,並將處理後的文本保存爲ok.txt

 

3. VB在執行上面語句後進入死循環,等待ok.txt生成,完成後讀取,繼續流程

 

諸位請看,是不是非常符合麻煩、低級的描述?但沒有更好的解決方案,只有如此。

----激動人心的分界線-----

後來發現了一本書(python programming on win32,有興趣的找來看),終於讓我發現瞭解決方法。COM組件!

COM is a technology from Microsoft that allows objects to communicate without the need for either object to know any details about the other, even the language it's implemented in.

看看本書某章節的總結:

We have seen examples of the various data types that can be passed back and forth between the two languages: numbers, strings, and arrays. The ability to pass multidimensional arrays allows you to move large amounts of data between the two languages without writing a lot of conversion code.

也不用說很多,不想看書的,看看下面這個我從書中摘抄的簡短例子,就能知道該方法的核心之處。
在python裏:

#需要先安裝pipywin32模塊
class PythonUtilities:

    _public_methods_=['SplitString']
    _reg_progid_='PythonDemos.Utilities'

    # 使用"print (pythoncom.CreateGuid())" 得到一個自己的clsid,不要用下面這個!!
    _reg_clsid_='{5FCAC95E-653A-484C-8568-A02D5E0256E8}'

    def SplitString(self, val, item=None):
        import string 
        if item !=None: 
            item=str(item)
        val=str(val)
        return val.split(item)

if __name__=='__main__':
    print ('Registering COM server...')
    import win32com.server.register
    win32com.server.register.UseCommandLine(PythonUtilities)

在VB裏:

Private Sub Form_Load()
    Set PythonUtils = CreateObject("PythonDemos.Utilities")
    response = PythonUtils.SplitString("Hello from VB")
    For Each Item In response
        MsgBox Item
    Next
End Sub

完成後在cmd中使用(py_name是上面python文件的名稱)

> python py_name.py --unregister

註銷COM,保證電腦純淨。
多餘的不用說了,一試便知,這點代碼足以解決諸多混合編程的難題。

該方法不僅適用於VB+Python,Office,Delphi,C++等等,均可使用。

 

 

怕不見備份用

arrow
arrow
    全站熱搜

    JL8051 發表在 痞客邦 留言(0) 人氣()