如何在 PyCharm 中完成 COM 编程的代码? [英] How to get code-completion for COM programming in PyCharm?

查看:41
本文介绍了如何在 PyCharm 中完成 COM 编程的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 app = win32com.client.Dispatch('Some.Application') 时,有没有可行的方法在 PyCharm 中完成代码?必须从 API 文档重新键入(或复制粘贴)所有内容相当繁琐,因此创建

现在,除了感觉很脏之外,这种方法依赖于已经生成的相关类型,并且代码完成仅限于对象发布的方法,所以我想它在实践中的用处可能会有所限制;特别是,任何处理代码的人都必须生成代码,否则注释将导致 NameErrors.就个人而言,我可能更喜欢将 Jupyter 用于实施过程的探索性部分,并且在上述答案,Jupyter 可以通过 win32com 进行扩展以实现完整的代码补全.

When using app = win32com.client.Dispatch('Some.Application'), is there any feasible way get code-completion in PyCharm? It is rather tedious having to retype (or copy-paste) everything from an API documentation, so would creating skeletons be. Is there no other way to let PyCharm know about the Interface provided via COM, especially if I can provide a .tlb file? Or is there at least some way automatically generate such a skeleton (or a wrapping module?) from the TypeLib?

解决方案

Since there is no way for PyCharm to know the runtime type of app, you shouldn't expect to get code completion on app directly; at least not until they decide to add built-in support for generating code from type libraries.

However, you can exploit the fact that win32com implicitly generates code based on the type library as described in the first part of this answer, together with PyCharm's support for type hinting, to get code completion on COM methods.

  1. Make sure that the Python types have been generated; their location is determined by the GUID of the COM object. For example, the types for Microsoft Word 2016 on my machine are available in C:Usersusernameappdatalocal empgen_py3.60020905-0000-0000-c000-000000000046x0x8x7.
  2. Add this folder to the path of your PyCharm Python interpreter; see e.g. this answer.
  3. Import the modules for which you want code completion.

In the screenshots below, we use this approach with Word's Find:

Now, besides feeling dirty, this approach relies on the relevant types having been generated and the code completion is limited to the methods published by the object, so I imagine its usefulness in practice might be somewhat limited; in particular, anybody working on the code will have to generate the code, or the annotations will cause NameErrors. Personally, I would probably prefer using Jupyter for the exploratory part of the implementation process, and with minimal tweaks outlined in the answer mentioned above, Jupyter can be extended to have full code completion with win32com.

这篇关于如何在 PyCharm 中完成 COM 编程的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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