| Python的方便不用說,VB6做GUI的簡單程度更不用說。二者混合編程的需求一直非常旺盛,但我苦苦搜尋了很久,始終未找到合適的解決方案。在很長一段時間內(nèi),我都是通過創(chuàng)建、讀取、刪除臨時文件來在VB程序和Python程序間傳遞信息,麻煩,且低級。(如下)
 比如下面是一個典型的處理流程
 
 1. VB創(chuàng)建需要處理的文本please.txt,并調(diào)用Python
 2. Python讀取、處理文本,并將處理后的文本保存為ok.txt
 3. VB在執(zhí)行上面語句后進入死循環(huán),等待ok.txt生成,完成后讀取,繼續(xù)流程
 諸位請看,是不是非常符合麻煩、低級的描述?但沒有更好的解決方案,只有如此。 ----激動人心的分界線-----后來發(fā)現(xiàn)了一本書(python programming on win32,有興趣的找來看),終于讓我發(fā)現(xiàn)了解決方法。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.
 看看本書某章節(jié)的總結(jié): 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模塊
import pythoncom
class PythonUtilities:
    _public_methods_=['SplitString']
    _reg_progid_='PythonDemos.Utilities'
    _reg_clsid_=pythoncom.CreateGuid()
    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)
以管理員身份執(zhí)行上述代碼。在注冊成功后,COM組件會一直保留,不受開關(guān)機影響,因此可以在任意時候進行調(diào)用。最妙的是,你可以隨時更新代碼的函數(shù)部分,而無需重新注冊,因此通常情況下,你只需要在注冊時使用管理員權(quán)限。 在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
上面說COM組件會一直保留,如果需要注銷,可使用管理員權(quán)限執(zhí)行命令行語句(py_name是上面python文件的名稱)。 > python py_name.py --unregister
多余的不用說了,一試便知,這點代碼足以解決諸多混合編程的難題。 該方法不僅適用于VB+Python,Office,Delphi,C++等等,均可使用。注:針對評論說的python版本,上述案例使用的是64位python+vb6,沒有問題。實測VBA同樣可以。 再注:有同學反映說所給的案例無法執(zhí)行,我將該案例上傳,供各位參考。下載后執(zhí)行bat文件注冊COM,就可以打開VB工程使用了。
 鏈接: https://pan.baidu.com/s/1MUx_NkGMfMKYuGc-8W1tKQ
 |