pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

当我按原样尝试 运行 这段代码时,我得到了这个错误 "IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)" ,但是如果我单独 运行 stp_tracker 它工作正常,如果我 运行 单独通知 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):
        self.process(event)
        notify_stps()

    def on_deleted(self, event):
        self.process(event)
        notify_stps()


def stp_tracker():
    # /if __name__ == '__main__':
    path = r"W:\TestFolder"
    observer = Observer()
    observer.schedule(MyHandler(), path)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()


def notify_stps():
    const = win32com.client.constants
    olMailItem = 0x0
    obj = win32com.client.Dispatch("Outlook.Application")
    newMail = obj.CreateItem(olMailItem)
    newMail.Subject = "I AM SUBJECT!!"
    newMail.Body = "Step files in directory"
    # newMail.BodyFormat = 2 # olFormatHTML https://msdn.microsoft.com/en-us/library/office/aa219371(v=office.11).aspx
    # newMail.HTMLBody = "<HTML><BODY>Enter the <span style='color:red'>message</span> text here.</BODY></HTML>"
    newMail.To = 'Acoker251@outlook.com'
    # attachment1 = r"C:\Temp\example.pdf"
    # newMail.Attachments.Add(Source=attachment1)

    newMail.Send()


stp_tracker()

对此表示歉意,但在互联网上搜索后我发现了一些有用的东西。我早些时候遇到了相同的 post,并认为它是已弃用的信息,因为我在 pycharm 中的自动完成在键入 pythoncom.CoInitialize() 时没有拾取任何东西,所以这让我认为它是过时的信息。 Strive Sun 也解释了相同的信息

第一个:

import pythoncom

然后设置:

xl=win32com.client.Dispatch("Excel.Application",pythoncom.CoInitialize())