为什么我不能在Python的新线程中创建COM对象?

2024-09-28 23:39:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python的一个新线程中从dll创建一个COM对象,这样我就可以在该线程中运行消息泵:

from comtypes.client import CreateObject
import threading

class MessageThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True

    def run(self):
        print "Thread starting"
        connection = CreateObject("IDMessaging.IDMMFileConnection")
        print "connection created"

a = CreateObject("IDMessaging.IDMMFileConnection")
print "aConnection created"
t = MessageThread()
t.start()

这是我得到的错误跟踪:

^{pr2}$

有什么想法吗?在


Tags: importselfinitdefconnection线程threaddll
3条回答

您需要在一个线程上调用CoInitialize()(或CoInitializeEx()),然后才能在该线程上创建COM对象。在

from win32com.client.pythoncom import CoInitialize
CoInitialize()

据我所知(很久以前我用COM组件编写了很多程序),如果COM对象使用STA,则必须在每个线程上调用CoInitialize

http://msdn.microsoft.com/en-us/library/ms678543(VS.85).aspx

但我不知道如何在python中调用这个函数。在

这是MSDN文档

http://msdn.microsoft.com/en-us/library/ms678543(VS.85).aspx

为了更新当前使用PyCharm和Python 2.7的体验: 您需要导入:

from pythoncom import CoInitializeEx
from pythoncom import CoUninitialize

然后运行线程:

^{pr2}$

PyCharm与STA公寓混淆,需要启用真正的多线程。在

每个CoInitialize()都以CoUninitialize()结尾,这一点很重要,因此请确保您的代码也遵循此规则,以防出现错误。在

相关问题 更多 >