我使用的Python 3.6.2在Windows 7的Python/win32com /嘗試/除外檢查,如果應用程序正在運行
我有一個小的功能,應該檢查是否MS Excel中已經運行與否。該功能有點奇怪,在這裏你的幫助將非常感激。
該函數應該檢查,如果Excel正在運行。如果是,則打印文本並退出應用程序。如果否,一切都很好,繼續。
我現在的問題是,當Excel 是運行在try塊執行包括打印,但不是sys.exit()和的除了塊執行以及!? 如果Excel是不是正在運行,那麼一切正常,try-block將中止並且僅執行except-block。
爲什麼在Excel運行時它同時執行兩個print語句?
請幫忙!
這裏是我的代碼:
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!
提前感謝!
UPDATE:
好吧,我也明白了,我不該一般做「除了」無specifiying我要處理異常。但是,如何確定我想要捕捉的異常類型。如果我查看錯誤消息,則不清楚。
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)
再次感謝您的幫助,夥計!
最後一行說'com_error:...',所以你的異常的類型是'com_error'。你仍然需要包名。在google中鍵入'python com_error'產生'pythoncom.com_error',所以這是你的完整異常類型。 – pschill