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