在pythonrpyc服务器上初始化COM对象并重用它?

2024-05-12 22:01:38 发布

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

我使用rpycpython服务器来处理通过电子邮件发送的请求。我正在将它们加载到一个Excel吸墨器中,其思想是在收到新请求后通过运行宏来自动更新Excel。你知道吗

但是,我无法初始化工作簿对象。下面的代码可以打开工作簿(startExcel),但是当我运行RunThis方法时,它会打印0,因为工作簿中没有初始化。你知道吗

有什么办法解决这个问题吗?你知道吗

from threading import Thread, Lock
import rpyc
from rpyc.utils.server import ThreadedServer
import win32com.client
from win32com.client import DispatchEx
import pythoncom
import os
import time


class MyService(rpyc.Service):

    excelInitialized = False
    xl = 0
    wb = 0

    def exposed_startExcel(self):

        pythoncom.CoInitialize()

        xl, wb = loadExcelEnv()
        print wb
        ws = wb.Sheets('RequestBlotter')
        xl.Application.Run("ThisWorkbook.cleardata")
        xl.Application.Run("ThisWorkbook.UpdateBlotter")

    def exposed_RunThis(self):
        print self.wb


def loadExcelEnv():

    xl = DispatchEx('Excel.Application')
    xl.DisplayAlerts = True
    xl.Visible = True

    wb = xl.Workbooks.Open(dir_path + '\\Repo Blotter.xlsm')

    return xl, wb

server = ThreadedServer(MyService, port = 33445, protocol_config = {"allow_public_attrs" : True})
dir_path = os.path.dirname(os.path.realpath(__file__))


t = Thread(target = server.start)
t.daemon = True

t.start()

conn = rpyc.connect("localhost", 33445)
c = conn.root
c.startExcel()

while True:
    time.sleep(10)
    c.exposed_RunThis()

Tags: pathfromimportselftrueserverosdef