[英]How to quit Outlook on win32com?
我有一個腳本來檢查我的 Outlook 文件夾。 不便之處在於我的 Outlook 可能已經打開,否則腳本會在后台為我打開 Outlook。 我想簡化它,以便如果我的 Outlook 已經打開,請保留它。 如果它是由腳本發送的,請在之后退出 Outlook。
所以我的腳本是這樣的:
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
調度差異化工作。 我環顧四周,找到了其中一些答案:
COM: excelApplication.Application.Quit() 保留進程
無法在 Python 上使用 win32com 完全關閉 Excel
並嘗試解決這些退出條件,但它們沒有正確退出 Outlook:
# 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()
根據我鏈接的問題,此方法似乎適用於 Excel。 Outlook 是否有什么不同之處使其在后台保持打開狀態? 由於print('quit')
,我確定滿足條件,並且沒有遇到錯誤。
我也看到了這一點: 如果 Outlook 已經打開,請使用 Python 檢查,如果沒有打開它,但我不想僅僅為了關閉 Outlook 的目的而導入另一個模塊。 我想知道是否有內部的先天功能win32com
是退出Outlook中正常,因為它似乎尷尬,它沒有。
我遇到了同樣的問題,我只是終止了 Outlook 進程。
import os
# Kill outlook and allow programmatic access (the script has to run as Administrator to edit the Windows Registry)
os.system('taskkill /im outlook.exe /f')
os.system('reg add HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Office\\16.0\\Outlook\\Security\\ /v ObjectModelGuard /t REG_DWORD /d 2 /f')
# ... use outlook
# Kill the outlook again and restore the warn on programmatic access setting
os.system('taskkill /im outlook.exe /f')
os.system('reg add HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Office\\16.0\\Outlook\\Security\\ /v ObjectModelGuard /t REG_DWORD /d 0 /f')
# Finally, restart outlook
os.system('start outlook')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.