2017-12-18 170 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") 

抛出,只有在这里捕捉。

相关问题