尚未调用win32com.client.Dispatch + Cherrypy = CoInitialize [英] win32com.client.Dispatch + Cherrypy = CoInitialize has not been called

查看:54
本文介绍了尚未调用win32com.client.Dispatch + Cherrypy = CoInitialize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码运行良好,但是如果从CherryPy应用程序方法执行并出现错误消息 CoInitialize尚未调用

The following code works well, but it fails if executed from a CherryPy app method with the error message CoInitialize has not been called:

import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
xl.quit()

这篇文章提出一种对我有用的解决方案:

This post suggests a solution that works for me:

import pythoncom
pythoncom.CoInitialize()

我之所以要问一个已经有解决方案的问题,是因为(1)我想知道我在做什么(而不是仅仅因为我已经看到它可以工作一次而这样做)和(2)我不想冒险错过一些重要的事情(并阅读这篇文章使我认为我缺少一些东西.)

The reason I'm asking about a problem for which I already have a solution, is that (1) I would like to know what I'm doing (rather than doing it only because I've seen it working once) and (2) I don't want to risk to miss something important (and reading this post makes me think that I am missing something.)

我找不到有关 pythoncom.CoInitialize()的任何文档,并且pythoncom的源代码对以下三行无济于事(Eclipse + pydev也没有说该方法不存在):

I couldn't find any documentation for pythoncom.CoInitialize(), and the source of pythoncom is the following three lines that don't help me (nor Eclipse+pydev which says that the method does not exist):

# Magic utility that "redirects" to pythoncomxx.dll
import pywintypes
pywintypes.__import_pywin32_system_module__("pythoncom", globals())

推荐答案

我不记得过去几年没有使用COM的确切原因,但是我想您必须在使用它的每个线程中初始化COM(同样,我不确定每个COM隔离区).由于CherryPy是线程服务器,因此您的请求是由不同的线程处理的,而不是由您引导的线程.因此,我建议您在引导程序中尝试以下操作:

I can't remember exactly as I didn't work with COM last years but I guess that you have to initialize COM in every thread you work with it (again I'm not sure about every COM compartment). As CherryPy is threaded servers your requests are handled by different threads, not one you bootstrap with. So I suggest you to try the following in your bootstrap routine:

import pythoncom


def onThreadStart(threadIndex):
  pythoncom.CoInitialize()

cherrypy.engine.subscribe('start_thread', onThreadStart)

这篇关于尚未调用win32com.client.Dispatch + Cherrypy = CoInitialize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆