如何每隔一小时中断一次 PumpWaitingMessages 并检查是否有任何未读邮件

How to break PumpWaitingMessages for every one hour and check for any unread mails

我想每隔一小时中断一次 PumpWaitingMessages 并检查是否有任何未读邮件,我尝试使用以下代码。

但是,如果我增加 time.time()-starttime>10 那么我的 outlook 就挂了,无法进步,有时我什至会得到以下错误:

这与

有关
 pTraceback (most recent call last):
 File "final.py", line 94, in <module>
 outlook_open=processExists('OUTLOOK.EXE')
 File "final.py", line 68, in processExists
 print('process "%s" is running!' % processname)
 IOError: [Errno 0] Error

请检查代码并帮助我解决这个问题。

 import win32com.client
 import ctypes # for the VM_QUIT to stop PumpMessage()
 import pythoncom
 import re
 import time
 import os
 import subprocess
 import pyodbc

 class Handler_Class(object):

    def __init__(self):
      # First action to do when using the class in the DispatchWithEvents     
      outlook=self.Application.GetNamespace("MAPI")
      inbox=outlook.Folders['mymail@gmail.com'].Folders['Inbox']
      messages = inbox.Items
      print "checking Unread mails"
      # Check for unread emails when starting the event   
      for message in messages:
         if message.UnRead:
           print message.Subject.encode("utf-8") # Or whatever code you wish to execute.
           message.UnRead=False

    def OnQuit(self):
       # To stop PumpMessages() when Outlook Quit
       # Note: Not sure it works when disconnecting!!
       print "Inside handler onQuit"
       ctypes.windll.user32.PostQuitMessage(0)

    def OnNewMailEx(self, receivedItemsIDs):
      # RecrivedItemIDs is a collection of mail IDs separated by a ",".
      # You know, sometimes more than 1 mail is received at the same moment.
      for ID in receivedItemsIDs.split(","):
          mail = self.Session.GetItemFromID(ID)
          subject = mail.Subject
          print subject.encode("utf-8")
          mail.UnRead=False
          try: 
            command = re.search(r"%(.*?)%", subject).group(1)
            print command # Or whatever code you wish to execute.
          except:
            pass

 # Function to check if outlook is open
 def processExists(processname):
   tlcall = 'TASKLIST', '/V', '/FI', 'imagename eq %s' % processname
   # shell=True hides the shell window, stdout to PIPE enables
   # communicate() to get the tasklist command result
   tlproc = subprocess.Popen(tlcall, shell=True, stdout=subprocess.PIPE)
   # trimming it to the actual lines with information
   tlout = tlproc.communicate()[0].strip().split('\r\n')
   # if TASKLIST returns single line without processname: it's not running
   if len(tlout) > 1 and processname in tlout[-1]:
      if "Not Responding" in tlout[2]:
         print('process "%s" is not responding' % processname)
         os.system("taskkill /f /im  outlook.exe")
         return False
      print('process "%s" is running!' % processname)
      return True
   else:
      print('process "%s" is NOT running!' % processname)
      return False

# Loop 
while True:
  try:
     outlook_open = processExists('OUTLOOK.EXE') 
  except: 
     outlook_open = False
  #If outlook opened then it will start the DispatchWithEvents
  if outlook_open == True:
     outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)
     while True:
         starttime=time.time()
         while (int(time.time()-starttime)<10):
             pythoncom.PumpWaitingMessages()    
         ctypes.windll.user32.PostQuitMessage(0)     
         outlook_open=processExists('OUTLOOK.EXE')
         if outlook_open == False:
             break
         #Handler_Class.__init__(outlook)
         # To not check all the time (should increase 10 depending on your needs)
  if outlook_open == False:
     print "outlook not opened"
     os.startfile("outlook")
  time.sleep(10)

因此,要在 #Handler_Class.__init__(outlook) 处查看未读电子邮件,只需执行以下操作:

win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)

(真的不需要赋值)。但我看不出你的代码有什么意义,因为在剩下的时间里你会用 pythoncom.PumpWaitingMessages() 监控传入的电子邮件,并且可以做同样的事情。

由于您的 outlook 问题悬而未决,不确定是什么问题,我自己尝试 运行 几个小时后就成功了。也许为了减少一些 CPU 的使用(这可能是您的问题,具体取决于您的计算机),您可以尝试在循环中添加一个 time.sleep(),例如:

while (int(time.time()-starttime)<100):
    pythoncom.PumpWaitingMessages()
    time.sleep(0.1)

虽然我在回答,但我认为您代码中的两个 ctypes.windll.user32.PostQuitMessage(0) 都不再需要 pythoncom.PumpWaitingMessages(),它们被用来停止 pythoncom.PumpMessages()。有或没有我的行为没有区别。

告诉我