带有python / COM的Windows应用程序自动化

时间:2018-07-24 15:33:05

标签: python automation com win32com

我试图在后台为用户自动执行ChemDraw,最好避免使用SendKeys(),因为我认为这需要ChemDraw实例才能可见。我需要做的是以编程方式单击“编辑”->“复制为”->“ InChI”,然后从Windows剪贴板中检索结果。

enter image description here

我们当前正在使用Python和COM脚本来尝试此操作。这是我们当前的代码:

    # Opens ChemDraw and loads the file, while keeping the window hidden.
    ChemDraw = w32.DispatchEx('ChemDraw.Application') # ChemDraw Application Object
    ChemDraw.Visible = False                          # Makes Invisible
    Compound= ChemDraw.Documents.Open(cdx_filepath)      # ChemDraw File Object (Can be seen with ChemDraw.Activate())

    # Selects the whole molecule.
    Compound.Objects.Select()

    # Here is where we need to figure out how to do CopyAs and Save off clipboard content.

    # Saves the file and Quits afterwards.
    Compound.SaveAs(jpg_filepath)
    ChemDraw.Quit()

我想我有两个问题:如何访问工具栏中的“编辑”及其中的结果?如何从类似“ ChemDraw = w32.DispatchEx('ChemDraw.Application')”的行中生成的对象,并确定您可以做什么?问题的一部分是我们似乎无法自省最终的DispatchEx对象,因此我们很难回答自己的问题。

2 个答案:

答案 0 :(得分:1)

关于如何访问“编辑”菜单内容的第一个问题将特定于ChemDraw本身,而没有解决这个问题,我无法对此立即给出解决方案。

但是,也许对第二个问题有一个答案将使您自己回答第一个问题,因此,这里是这样:假设ChemDraw COM对象允许它,则可以使用win32com.client.gencache.EnsureDispatch代替{{ 1}},以便为该对象自动生成Python类;这使您可以更详细地检查对象。除了使用DispatchEx,您还可以直接访问基础的代码生成功能,这可能更适用于您的工作流程。有关更多详细信息,请参见this questionthis guide

答案 1 :(得分:0)

由于COM脚本的复杂性,我认为您无法真正“访问编辑菜单”,但是有一种解决方案可以访问和存储InChI字符串:

对于初学者,我强烈建议您使用comtypes,而不是win32com,因为使用dir()时,它会提供更多信息,据我所知,语法几乎相同。 Win32com几乎一无所获,因此您实质上是在暗室中寻找仅用于功能的针脚(除非您有可用的SDK)。从那里,打开ChemDraw文件,访问Objects类,然后使用Data()方法并输入“ chemical / x-inchi”(在您的情况下)。我也一直在与ChemDraw合作开发一个项目,而且我必须做同样的事情,所以这就是你想要的:

import comtypes.client as w32
# Path for experimental ChemDraw File.
cdx_file = # Insert ChemDraw file path here

# Creates invisible ChemDraw object.
ChemDraw = w32.CreateObject("ChemDraw.Application")
ChemDraw.Visible = True

# Creates file object.
Compound = ChemDraw.Documents.Open(cdx_file)

# Converts file to InChI string.
file_inchi = Compound.Objects.Data("chemical/x-inchi")
print(file_inchi)

# Closes ChemDraw
ChemDraw.Quit()

P.S.:CreateObject是win32com的DispatchEx()的等效类型。