0

我正在开发一个(相当大的)Python/Tkinter 应用程序(Windows 7 下的 Python 2.7),它(除其他外)通过 COM 接口调用 Matlab。Matlab/COM 部分的基本结构是这样的:

import Tkinter
import pythoncom
import win32com.client

class App( object ):

    def __init__( self, parent ):
        Tkinter.Button( root, text="Start Matlab", command=self.start_matlab ).grid()

    def start_matlab( self ):
        self.matlab = win32com.client.Dispatch( "Matlab.Application" )

root = Tkinter.Tk()
App( root )
root.mainloop()

我用这个简化的代码观察到的行为是:运行应用程序并单击按钮创建一个 Matlab-Instance(打开一个 Matlab-Command 窗口),当关闭 Tkinter 应用程序时,Matlab-window 和任务中的相应条目 -经理消失。重复该过程,Matlab 重新启动。但是,当我对“真实”应用程序执行“相同”操作时,Matlab 实例在关闭我的应用程序后仍然存在,此外,当我重新启动应用程序并运行“启动”Matlab 的部分时,它只是检索并使用该实例退出我的应用程序的第一个会话后,它仍保留在内存中。不幸的是,我无法隔离显示后一种行为的相当小的代码示例:(

有谁知道这是/可能是什么原因?

当创建它的父 Python 应用程序关闭时,如何控制 COM 对象是被杀死还是保留在内存中?

4

1 回答 1

0

以下是使用 Tkinter 的协议处理程序显式删除 COM 对象的方法:

import Tkinter
import pythoncom
import win32com.client

class App( object ):

    def __init__( self, parent ):
        self.parent = parent #reference to root
        Tkinter.Button( root, text="Start Matlab", command=self.start_matlab ).grid()
        self.parent.protocol('WM_DELETE_WINDOW', self.closeAll) #protocol method

    def start_matlab( self ):
        self.matlab = win32com.client.Dispatch( "Matlab.Application" )

    def closeAll(self):
        del self.matlab       #delete the COM object
        self.parent.destroy() #close the window

root = Tkinter.Tk()
App( root )
root.mainloop()

参考:从内存中删除 COM 对象

更多关于协议

于 2014-04-08T16:33:05.827 回答