问题
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?
回答1:
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.
- 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:\Users\username\appdata\local\temp\gen_py\3.6\00020905-0000-0000-c000-000000000046x0x8x7\
. - Add this folder to the path of your PyCharm Python interpreter; see e.g. this answer.
- 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 NameError
s. 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
.
来源:https://stackoverflow.com/questions/42273433/how-to-get-code-completion-for-com-programming-in-pycharm