问题
When opening e.g. a spreadsheet with pywin32, I found two options to do so:
excel1 = win32com.client.DispatchEx('Excel.Application')
wb = excel1.Workbooks.Open('myxls.xls')
or I could do
excel2 = win32com.client.Dispatch('Excel.Application')
wb = excel2.Workbooks.Open('myxls.xls')
and I'm wondering if this makes any difference. The docstrings don't help me much either:
>>> w32.Dispatch.__doc__
'Creates a Dispatch based COM object.\n '
>>> w32.DispatchEx.__doc__
'Creates a Dispatch based COM object on a specific machine.\n '
In this site they suggest that DispatchEx
might be for remote access.
Does it make any difference which method I use when I'm simply trying to automate spreadsheets on my own PC?
回答1:
It depends on what you want. If Excel is already open, using dispatch will create a new tab in the open Excel instance. If Excel is already open, using dispatchEx will open a new instance of Excel.
回答2:
DispatchEx
is not documented, and Dispatch
is, which already implies the practical answer: Just use Dispatch
, unless you have some very good reason to believe you have a special case.
However, if you want to know the differences under the covers:
From the pywin32 source, you can see that DispatchEx
tries to return a wrapped-up IDispatchEx
interface rather than IDispatch
. (Not too surprising, given the names.)
You can look up IDispatchEx at MSDN, and you'll see that it's
an extension of the IDispatch interface, supports features appropriate for dynamic languages such as scripting languages.
The idea is that, if the thing you're automating is a dynamic object (like the kind of object you have in Python or Javascript), rather than a static object (like the kind of object you have in C++ or Java), Visual Basic code can access its dynamic nature—enumerate, add, and remove members at runtime, etc.
And of course pywin32 can do almost everything VB can, you just need to be a bit more explicit sometimes. In this case, you need to create a DispatchEx
, and call its DeleteMemberByName
etc. methods.
回答3:
If you're using COM to automate, say, Excel there will come a time when you want .Dispatch to fire up a new instance of the application, not to interfere with the one already running on the desktop.
Use DispatchEx instead of Dispatch
来源:https://stackoverflow.com/questions/18648933/using-pywin32-what-is-the-difference-between-dispatch-and-dispatchex