[英]Python / win32com / try and except / check if application is running
我在Windows 7上使用python 3.6.2。
我有一個小功能,應該檢查MS Excel是否已在運行。 該功能表現有些奇怪,在這里您的幫助將不勝感激。
該功能應檢查Excel是否正在運行。 如果是,請打印文本並退出應用程序。 如果否,則一切正常,請繼續。
我現在的問題是,當Excel運行在try塊執行包括打印,但不是sys.exit() 和除塊執行以及!? 如果沒有運行Excel,則一切正常,try塊將中止,僅執行except塊。
為什么在Excel運行時執行兩個打印語句?
請幫忙!
這是我的代碼:
def check_if_Excel_runs():
import win32com.client
import sys
try:
win32com.client.GetActiveObject("Excel.Application")
# If there is NO error at this stage, Excel is already running
print('Excel is running, please close first')
sys.exit()
except:
print('Excel is NOT running, this is good!')
return
check_if_Excel_runs()
我的輸出(運行Excel時):
Excel is running, please close first
Excel is NOT running, this is good!
提前致謝!
更新:
好的,我已經知道,在沒有指定要處理的異常的情況下,通常不應該執行“除外”操作。 但是我如何確定要捕獲的異常類型。 如果我查看錯誤消息,對我來說還不清楚。
com_error Traceback (most recent call last)
<ipython-input-39-70980aa1c5df> in <module>()
11 return
12
---> 13 check_if_Excel_runs()
<ipython-input-39-70980aa1c5df> in check_if_Excel_runs()
3 import sys
4 try:
----> 5 win32com.client.GetActiveObject("Excel.Application")
6 # If there is NO error at this stage, Excel is already running
7 print('Excel is running, please close first')
c:\users\chnn\appdata\local\programs\python\python36-32\lib\site-packages\win32com\client\__init__.py in GetActiveObject(Class, clsctx)
77 """
78 resultCLSID = pywintypes.IID(Class)
---> 79 dispatch = pythoncom.GetActiveObject(resultCLSID)
80 dispatch = dispatch.QueryInterface(pythoncom.IID_IDispatch)
81 return __WrapDispatch(dispatch, Class, resultCLSID = resultCLSID, clsctx = clsctx)
com_error: (-2147221021, 'Operation unavailable', None, None)
再次感謝大家的幫助!
這是因為sys.exit()也會引發異常。
我相信您的問題是sys.exit()引發異常。
Sys.exit()通過引發系統退出異常退出。 您不能將其放在其中,而只能使用常規的catch all語句。
希望這可以幫助!
從sys.exit()上的python文檔中,您可以看到問題出在哪里:
這是通過引發SystemExit異常來實現的,因此可以使用try語句的finally子句指定的清除操作,並且可以在外部級別攔截出口嘗試。
因此,發生的情況是sys.exit()
正在執行,並嘗試通過sys.exit()
SystemExit異常來結束程序。 但是由於您編寫了泛型,否則您會捕獲異常,然后打印消息。
因此,您提供了一個極好的示例,說明編寫通用異常為什么不是一個好主意,因為您最終可能會捕獲不想捕獲的異常。 您應該尋找的異常類型
win32com.client.GetActiveObject("Excel.Application")
拋出並僅在此處捕獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.