我正在使用CherryPy开发一个需要通过COM访问一些应用程序的Web应用程序.
现在我用每个请求创建一个新的应用程序实例,这意味着每个请求等待3秒钟启动应用程序,0.01等待实际作业.
我想启动每个COM应用程序一次并使其保持活动状态并在以下请求中重复使用它几秒钟,因为大多数时候它被5-10个ajax请求的突发使用,然后几个小时都没有.
是否可以在CherryPy应用程序的所有线程之间共享COM abject?
以下是一些实验的摘要,这些实验显示了它现在如何处理每个请求以及它如何在线程之间不起作用.
以下代码成功启动和停止Excel:
>>> import pythoncom, win32com.client
>>> def start():
global xl
xl = win32com.client.Dispatch('Excel.Application')
>>> def stop():
global xl
xl.quit()
xl = None
>>> start()
>>> stop()
Run Code Online (Sandbox Code Playgroud)
但是下面的代码启动Excel并在3秒后关闭它.
>>> import pythoncom, win32com.client, threading, time
>>> def start():
global xl
pythoncom.CoInitialize()
xl = win32com.client.Dispatch('Excel.Application')
time.sleep(3)
>>> threading.Thread(target=start).start()
Run Code Online (Sandbox Code Playgroud)
我添加了调用,CoInitialize()否则xl对象将无法工作(请参阅此文章).
我添加了3秒的暂停,所以我可以在任务管理器上看到EXCEL.EXE进程启动并且活着3秒钟.
为什么它在启动它的线程结束后死亡?
我检查了文档CoInitialize(),但我无法理解是否有可能让它在多线程环境中工作.
当我尝试按原样运行此代码时,出现此错误“IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize 尚未被调用。', None, None )" ,但是如果我单独运行 stp_tracker ,它工作得很好,如果我单独运行 notify stp ,它工作得很好。我感谢任何人的意见。谢谢
import time
import win32com.client
# import sys
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
# import watchdog
class MyHandler(PatternMatchingEventHandler):
patterns = ["*.stp", "*.step", "*.txt"]
def process(self, event):
"""
event.event_type
'modified' | 'created' | 'moved' | 'deleted'
event.is_directory
True | False
event.src_path
path/to/observed/file
"""
# the file will be processed there
print(event.src_path, event.event_type)
def on_modified(self, event):
self.process(event)
notify_stps()
def on_created(self, event): …Run Code Online (Sandbox Code Playgroud) 我正在编写一个控制台应用程序,它将为我的主应用程序Client.exe创建一个防火墙例外,它通过FTP将一些文档上传到我们的服务器.我从Delphi 7 Windows Vista/7防火墙异常网络位置借用了RRUZ代码,我的代码如下所示:
program ChangeFW;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
ComObj;
var
ExecName: string;
procedure AddExceptionToFirewall(Const Caption, Executable: String);
const
NET_FW_PROFILE2_DOMAIN = 1;
NET_FW_PROFILE2_PRIVATE = 2;
NET_FW_PROFILE2_PUBLIC = 4;
NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_ACTION_ALLOW = 1;
var
fwPolicy2 : OleVariant;
RulesObject : OleVariant;
Profile : Integer;
NewRule : OleVariant;
begin
Profile := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
fwPolicy2 := CreateOleObject('HNetCfg.FwPolicy2');
RulesObject := fwPolicy2.Rules;
NewRule := CreateOleObject('HNetCfg.FWRule');
NewRule.Name := Caption;
NewRule.Description := Caption;
NewRule.Applicationname := Executable;
NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
NewRule.Enabled …Run Code Online (Sandbox Code Playgroud) 我通过win32com.client.Distpatch函数连接到MS Word,并且在第二个请求中我遇到错误:'CoInitialize尚未被调用.' 我找到了这个话题:
http://www.velocityreviews.com/forums/t328097-coinitialize-error-when-using-adodbapi.html
并得到我必须在新线程中调用CoInitialize.所以问题是在金字塔中调用CoInitialize函数的位置.