2017-12-18 168 views
0

我使用的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) 

再次感謝您的幫助,夥計!

+0

最後一行說'com_error:...',所以你的異常的類型是'com_error'。你仍然需要包名。在google中鍵入'python com_error'產生'pythoncom.com_error',所以這是你的完整異常類型。 – pschill

回答

0

發生這種情況是因爲sys.exit()也會引發異常。

0

我相信你的問題是,sys.exit()拋出一個異常。

Sys.exit()通過拋出系統出口異常退出。你不能把它放在那裏,只是使用一個普通的catch語句。

希望這會有所幫助!

0

從上sys.exit Python文檔(),你可以看到的問題是什麼在這裏:

This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

所以會發生什麼是正在執行的sys.exit()並試圖通過拋出SystemExit結束程序例外。但是,既然你寫了一個通用的,除了你捕獲異常,然後打印消息。

爲此,您提供了一個很好的例子,說明爲什麼編寫泛型異常是一個糟糕的主意,因爲您最終可能會捕獲您不想捕獲的異常。你應該尋找那種類型的例外,

win32com.client.GetActiveObject("Excel.Application") 

拋出,只有在這裏捕捉。

相關問題