I have a script that checks my Outlook folder. The inconvenience is that my Outlook can either be already opened, or if not, the script will open Outlook in the background for me. I wanted to streamline it so that if my Outlook is already opened, keep it. If it was dispatched by the script, quit outlook afterwards.
So I have my script like this:
from win32com.client import Dispatch, GetActiveObject
class Outlook:
def __init__(self):
self.app_str = "Outlook.Application"
try:
self.app = GetActiveObject(self.app_str)
self.dispatched = False
except: # I know I should catch the specific error, but let's neglect it for this MCVE
self.app = Dispatch(self.app_str)
self.dispatched = True
The dispatch differentiation works. I've looked around and found some of these answers:
COM: excelApplication.Application.Quit() preserves the process
Can't close Excel completely using win32com on Python
And tried my hands on these quit conditions, but they don't quit Outlook properly:
# attempt 1
def quit(self):
print(self.dispatched, self.app)
if self.dispatched and not self.app is None:
print('quit!')
self.app.Application.Quit()
# I've also tried self.app.Quit()
# attempt 2
import pythoncom
def __init__(self):
...
except:
pythoncom.CoInitialize()
self.app = Dispatch(self.app_str)
self.dispatched = True
def quit(self):
print(self.dispatched, self.app)
if self.dispatched and not self.app is None:
print('quit!')
self.app.Application.Quit()
pythoncom.CoUninitialize()
This method seems to work for Excel based on the questions I've linked. Is there something different about Outlook that makes it stay open on background? I know for sure the condition is met because of print('quit')
, and no errors were encountered.
I also saw this: Check with Python if Outlook is already open, if not open it, but I'd rather not import another module just for the sole purpose of closing Outlook. I want to know if there is an innate function within win32com
that quits Outlook properly because it seems awkward that it doesn't.