![](/img/trans.png)
[英]win32com.client.Dispatch opening the undesired canoe version
[英]Different behaviour when opening Excel and Word in python using win32com.client.dispatch function
我是python开发的新手。
我正在尝试练习 win32com.client 模块,并且出现了一些非常混乱的错误。
首先,我试过了。
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Visible = True
显然,它运作良好。 所以我在下面尝试。
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
它像 Word 一样工作,但几秒钟后关闭。 我不知道为什么会这样。
看起来 Word 的行为并不像它应该的那样直接。 Word 应用程序必须由gc模块进行垃圾收集,但事实并非如此。 您可以使用解释器中的input
获得终止执行的表面视图:
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
app.Visible = True
input('deleting reference...')
# deleting reference forces gc to clear Excel
# though Word remains uncollected even thereafter
del app
input('Exit...')
Python 内存管理相当复杂,当 Python 嵌入到其他应用程序中时,它就会成为一个问题。 您可以在Python 如何管理内存一文中找到有关垃圾收集的一些有用信息? (可能已经过时,但可能对共同理解有用)或在 Python 的文档Memory Management 中。
好的方法是使用Quit
方法显式关闭它以从内存中正确释放应用程序:
app.Quit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.