Python/win32com - 检查程序是否打开 [英] Python/win32com - Check if Program is Open

查看:42
本文介绍了Python/win32com - 检查程序是否打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,我在其中使用 win32com 与 COM 服务进行交互.当程序已经打开时,它按预期工作.我使用 win32com.client.dynamic.Dispatch 连接到它,然后与应该已经打开的文档进行交互.假设程序已经打开,我可以轻松检查文档是否打开,但我不确定如何检查程序是否已经打开.当我使用提到的 Dispatch 时,如果程序尚未打开,它只会启动程序,这不是我想要的.

I have a script where I use win32com to interact with a COM service. It works as intended when the program is already open. I connect to it using win32com.client.dynamic.Dispatch, then interact with a document that should already be open. Assuming the program is already open, I can easily check if a document is open, but I'm not sure how to check if the program is already open or not. When I use the Dispatch mentioned, it just starts the program if it isn't already open, which is not what I want.

推荐答案

试试 win32com.client.GetActiveObject() 方法.这是我在我编写的一些便利函数中使用的,这个是用于 Excel 的:

try win32com.client.GetActiveObject() method. This is what I use in some convenience functions I've written, this one for Excel:

def Excel(visible=True):
    '''Get running Excel instance if possible, else 
    return new instance. 
    '''
    try: 
        excel = win32com.client.GetActiveObject("Excel.Application")
        print("Running Excel instance found, returning object")

    except:
        excel = new_Excel(visible=visible)
        print("No running Excel instances, returning new instance")

    else:
        if not excel.Workbooks.Count:
            excel.Workbooks.Add(1)
        excel.Visible = visible

    return excel

new_Excel 只是用于打开 Excel 应用程序对象的新实例的另一个便利函数.

new_Excel is just another convenience function for opening new instances of the Excel application object.

这篇关于Python/win32com - 检查程序是否打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆