Python/win32com/try and except/检查应用程序是否正在运行

2024-09-25 06:29:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows7上使用Python3.6.2。在

我有一个小函数,它应该检查msexcel是否已经在运行。功能有点奇怪,在这里您的帮助将非常感谢。在

如果Excel正在运行,则函数应进行检查。如果是,则打印文本并退出应用程序。如果没有,一切正常,继续。在

我现在的问题是,当Excel运行时,执行try块,包括打印,但不包括系统出口()同时执行except块!? 如果Excel没有运行,则一切正常,try块中止,只执行except块。在

为什么它在运行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运行时):

^{pr2}$

提前谢谢!在

更新:

好吧,我明白了,我一般不应该在没有指定要处理的异常的情况下执行“except”。但是我如何确定我想要捕捉的异常类型呢。如果我看一下错误信息,我就不清楚了。在

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)

再次感谢你们的帮助,各位!在


Tags: clientifischeckrunserrorexcelrunning
3条回答

从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异常来结束程序。但是由于您编写了一个泛型except,所以您捕捉到异常并打印消息。在

因此,您提供了一个很好的例子,说明为什么编写泛型异常不是一个好主意,因为您最终可能会捕获不想捕获的异常。您应该查找异常类型

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

把球扔出去,只在这里接住。在

我相信你的问题是系统出口()正在引发异常。在

在系统出口()通过引发系统出口异常退出。你不能把它放在那里,只使用一个笼统的语句。在

希望这有帮助!在

这是因为系统出口()也引发异常。在

相关问题 更多 >