Giter VIP home page Giter VIP logo

comtypes's Introduction

comtypes

Works on Windows only
PyPI version PyPI - Python Version PyPI - License PyPI - Downloads
GitHub Repo stars GitHub forks
Tidelift Subscription

About

comtypes is a lightweight Python COM package, based on the ctypes FFI library.

comtypes allows to define, call, and implement custom and dispatch-based COM interfaces in pure Python.

This package works on Windows only.

Available on Python 3.7-3.12.

  • comtypes==1.2.1 is the last version supporting Python 2.7 and 3.3-3.6.
  • In Python 3.7.6 and 3.8.1, comtypes would not work as reported in GH-202.
    This bug has been fixed in Python >= 3.7.7 and >= 3.8.2.
  • In Python 3.8 and 3.9, some of comtypes functionalities may not work correctly as reported in GH-212.
    This bug has been fixed in Python >= 3.10.10 and >= 3.11.2.

Where to get it

The source code is currently hosted on GitHub at: https://github.com/enthought/comtypes

An installer for the latest released version is available at the Python Package Index (PyPI).

# PyPI
pip install comtypes

Dependencies

comtypes requires no third-party packages to run - this is truly pure Python package.

Optional features include the follows...

  • to process arrays as numpy's ndarray
  • type hints be interpreted by mypy or several static type checkers

But these third-parties are not required as a prerequisite for runtime.

Community of the developers

Tracking issues, reporting bugs and contributing to the codebase and documentation are on GitHub at: https://github.com/enthought/comtypes

For Enterprise

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

Learn more.

Frequently Asked Questions

Q: Why does this package not support platforms other than Windows?

A: The Microsoft Component Object Model (COM) is a technology that is unique to Windows and is not supported on other platforms.

The phrase "COM is a platform-independent" in the MS documentation means that COM maintains compatibility across different versions of Windows, and does NOT imply that it is supported on Linux or Mac.

As long as COM is not supported outside of Windows, this project does not plan to port to other platforms.

Q: Why does cannot import name 'COMError' from '_ctypes' error occur when using this package on platforms other than Windows?

A: The _ctypes is part of the internal implementation of the ctypes standard library that exists for Python on all platforms.
However, COMError and COM-related features are implemented only in Python for Windows.

In cross-platform software development, care must be taken to ensure that codebase dependent on comtypes does not execute in environments other than Windows.

Q: Despite a script that depends on comtypes having run successfully before, a error (ImportError, NameError, or SyntaxError) is raised now, and the same error occurs again and again.

A: Executing py -m comtypes.clear_cache and then running the script again might resolve the problem.

When comtypes.client.GetModule is called (either directly or indirectly), comtypes generates Python module files.
If Python is forced to terminate or crashes in the middle of file generation, the codebase written to the file becomes partial.
When Python tries to import this unexecutable partial codebase module, an error occurs.

Executing py -m comtypes.clear_cache identifies the directories where the "cache module files" are stored and deletes them.
After deleting these partial modules and running the script again, comtypes.client.GetModule is called and executable modules are generated anew.

However, if the script implementation does not use comtypes.client.GetModule or processes generated files, it may not be a solution.

Documentation:

The documentation is currently hosted on pythonhosted at: https://pythonhosted.org/comtypes

comtypes's People

Contributors

bennyrowland avatar bgilbert avatar cfarrow avatar chaoste avatar cmin764 avatar dmwyatt avatar forderud avatar fusentasticus avatar fxthomas avatar geppi avatar j0ker70 avatar jaraco avatar jonschz avatar junkmd avatar kdschlosser avatar kylemr avatar laripk avatar maphew avatar mdickinson avatar mobiusklein avatar muddi900 avatar orf avatar pfmoore avatar robind42 avatar skaytsner avatar totaam avatar vasily-v-ryabov avatar vijairaj avatar wkschwartz avatar yhchen0906 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

comtypes's Issues

COM server not working?

The COM servers are not working in with Python 2.6.1 and Windows XP.
I'm suspecting this is related to python issue 4566 (http://bugs.python.org/issue4566).
I'm trying to run the ./test/TestComServer.py script on windows (I'm opening another issue about some missing files needed to run it) and I'm getting error R6034 messages when trying to view the COM object with the OleView utility, this is the same message.
Previously when some of my py2exe'd apps didn't work with Python 2.6.1 I was able to fix this kind of issue by using a manifest file (which was needed for the packaged .exe but not for the .py script). Now I was not able to find any solution by using manifest files (but I'm not discarding this would be an option, once a proper manifest is somewhere defined).
I'm hopping this gets fixed in the next Python 2.6.x release as a python patch is already available, but in the mean time, can we still get some sort of solution?

ERROR in test_jscript

Seen under 64-bit python.

======================================================================
ERROR: test_jscript (comtypes.test.test_msscript.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_msscript.py", line 19, in test_jscript
    engine = CreateObject("MSScriptControl.ScriptControl")
  File "build\lib\comtypes\client\__init__.py", line 238, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File "build\lib\comtypes\__init__.py", line 1179, in CoCreateInstance
    _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
  File "_ctypes/callproc.c", line 945, in GetResult
WindowsError: [Error -2147221164] Class not registered

Frozen ctypes com server can't load OLE typelib

When registering a frozen inproc com server, an exception is thrown when LoadTypeLibEx is passed a c_wchar_p string instead of a unicode string.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "boot_ctypes_com_server.py", line 80, in DllRegisterServer
  File "C:\Python34\lib\site-packages\comtypes\server\register.py", line 328, in register
    Registrar().register(cls)
  File "C:\Python34\lib\site-packages\comtypes\server\register.py", line 135, in register
    self._register(cls, executable)
  File "C:\Python34\lib\site-packages\comtypes\server\register.py", line 152, in _register
    LoadTypeLibEx(dll, REGKIND_REGISTER)
  File "C:\Python34\lib\site-packages\comtypes\typeinfo.py", line 485, in LoadTypeLibEx
    _oleaut32.LoadTypeLibEx(c_wchar_p(szFile), regkind, byref(ptl))
TypeError: unicode string or integer address expected instead of bytes instance
DEBUG:comtypes.server.register:Unregister <class 'server.RemotePrint.RemotePrintImpl'>

Didn't handle VT_DECIMAL in automation.py

...
D:\Project\Python26\lib\site-packages\comtypes\automation.pyc in _get_value(self
, dynamic)
397 return cast(self._.pparray, _midlSAFEARRAY(typ)).unpack()
398 else:
--> 399 raise NotImplementedError("typecode %d = 0x%x)" % (vt, vt))
400
401 def __getitem__(self, index):
NotImplementedError: typecode 14 = 0xe)

This bug is triggered by when I used ADO to do some mssql query that table contained column of numeric(or decimal) type .

FAIL in test_QueryService

Seen under 64-bit python.

======================================================================
FAIL: test (comtypes.test.test_QueryService.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_QueryService.py", line 13, in test
    sp = ie.Document.Body.QueryInterface(comtypes.IServiceProvider)
  File "build\lib\comtypes\client\__init__.py", line 44, in wrap_outparam
    return GetBestInterface(punk)
  File "build\lib\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "build\lib\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "build\lib\comtypes\client\_generate.py", line 188, in _CreateWrapper
    mod = _my_import(fullname)
  File "build\lib\comtypes\client\_generate.py", line 26, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "build\lib\comtypes\gen\_3050F1C5_98B5_11CF_BB82_00AA00BDCE0B_0_4_0.py", line 19399, in <module]]
]]>

    assert sizeof(tagSAFEARRAY) == 20, sizeof(tagSAFEARRAY)
AssertionError: 32

Uncaught COMError with Automation in shell results in a leak

In either the CPython or IPython interactive shells:

>>> import comtypes.client
>>> xl = comtypes.client.CreateObject('Excel.Application', dynamic=True)
>>> wb = xl.Workbooks.Open('nonexistent.xlsx')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python33\lib\site-packages\comtypes\client\lazybind.py", line 182, in caller
    return self._comobj._invoke(descr.memid, descr.invkind, 0, *args)
  File "C:\Python33\lib\site-packages\comtypes\automation.py", line 729, in _invoke
    dp, var, None, argerr)
_ctypes.COMError: (-2146827284, None, ("'nonexistent.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", 'Microsoft Office Excel', 'C:\\Program Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, None))
>>> xl.Quit()
>>> del xl

Task Manager shows that an EXCEL.EXE instance still lingers. If I wrap the above inside a try statement with except: pass, then Excel shuts down.

Release 1.1

With the license file in the repository and several minor bug fixes merged, it would be a good time to issue a new release. I would like to merge the outstanding PRs (#29, #31, and #32) soon and document the guidelines for using NumPy. This, I believe, will be sufficient for a version bump to 1.1.

comtypes 1.1.0 and 1.1.1 does not work under pypy 2.51

>>>> import comtypes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\pypy\site-packages\comtypes\__init__.py", line 1171, in <module>
    class IPersist(IUnknown):
  File "C:\pypy\site-packages\comtypes\__init__.py", line 1176, in IPersist
    ( ['out'], POINTER(GUID), 'pClassID' )),
  File "C:\pypy\site-packages\comtypes\__init__.py", line 1093, in COMMETHOD
    from comtypes.automation import VARIANT
  File "C:\pypy\site-packages\comtypes\automation.py", line 538, in <module>
    VARIANT.null = VARIANT(None)
  File "C:\pypy\site-packages\comtypes\automation.py", line 187, in __init__
    self.value = args[0]
  File "C:\pypy\site-packages\comtypes\automation.py", line 220, in _set_value
    self.vt = VT_NULL
  File "C:\pypy\lib_pypy\_ctypes\structure.py", line 122, in __set__
    obj._buffer.__setattr__(self.name, arg)
AttributeError: C Structure has no attribute vt

comtypes 1.0.0 does work

Should comtypes support default properties

Default properties add syntactic sugar to interfaces, as described here. Item is usually a default property.

Comtypes always treats Item as a default property, as defined here, but perhaps should support default properties in a more general way.

Crash using the GetActiveObject,CreateObject

when I try to run this code:

from comtypes.client import GetActiveObject,CreateObject
td = GetActiveObject('TD_Appl.Application')

I got the following error:

Traceback (most recent call last):
File "C:\d\OmniaSolutions\Programming\EclipseWorkSpace\OpenErpPlmClient\plmintegration\Integrations\Cad\Thinkdesign\integration.py", line 1973, in <module>
test4()
File "C:\d\OmniaSolutions\Programming\EclipseWorkSpace\OpenErpPlmClient\plmintegration\Integrations\Cad\Thinkdesign\integration.py", line 1950, in test4
print "Result:",GerPropValue2('DOCNAME')
File "C:\d\OmniaSolutions\Programming\EclipseWorkSpace\OpenErpPlmClient\plmintegration\Integrations\Cad\Thinkdesign\integration.py", line 1960, in GerPropValue2
ent=_getCurrentEnt()
File "C:\d\OmniaSolutions\Programming\EclipseWorkSpace\OpenErpPlmClient\plmintegration\Integrations\Cad\Thinkdesign\integration.py", line 1956, in _getCurrentEnt
td = GetActiveObject('TD_Appl.Application') 
File "C:\Python27\lib\site-packages\comtypes\client\__init__.py", line 183, in GetActiveObject
return _manage(obj, clsid, interface=interface)
File "C:\Python27\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage
obj = GetBestInterface(obj)
File "C:\Python27\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface
mod = GetModule(tlib)
File "C:\Python27\lib\site-packages\comtypes\client\_generate.py", line 112, in GetModule
mod = _CreateWrapper(tlib, pathname)
File "C:\Python27\lib\site-packages\comtypes\client\_generate.py", line 188, in _CreateWrapper
mod = _my_import(fullname)
File "C:\Python27\lib\site-packages\comtypes\client\_generate.py", line 26, in _my_import
return __import__(fullname, globals(), locals(), ['DUMMY'])
File "C:\Python27\lib\site-packages\comtypes\gen\_F4503A16_F637_11D2_BD55_00500400405B_0_1_0.py", line 160, in <module>
( ['in'], POINTER(_midlSAFEARRAY(POINTER(c_int))), 'pCvBound' ),
File "C:\Python27\lib\site-packages\comtypes\safearray.py", line 18, in _midlSAFEARRAY
sa_type = _make_safearray_type(itemtype)
File "C:\Python27\lib\site-packages\comtypes\safearray.py", line 52, in _make_safearray_type
raise TypeError(itemtype)
TypeError: <class 'comtypes._safearray.LP_c_long'>
DEBUG:comtypes:Calling CoUnititialize()
DEBUG:comtypes:CoUnititialize() done.

regards,
Matteo

have 64-bit client check 32-bit registry hive

Suggestion (apologies if it's been done, I didn't find it). When a 64-bit client attempts to look up a class, interface, or object and can't find it, could we have it check the 32-bit registry hive automatically? Should we?

As long at the IDL stays away from pointers you can do out-of-process COM across bitnesses. But unless the server (or the user) takes special pains to register itself in both hives one won't be visible from the other.

Use the Visual Studio wizard to create a default MFC MDI exe project, check the "automation" box on the advanced tab, build in 32-bit mode. From a 64-bit python process you can't see the (vacuous but valid) document interface and class it exposes. Rebuild in 64-bit mode and you can talk to it successfully.

When you're developing the server side in both bitnesses everything about this is a pain. I end up running a stale "wrong bitness" build via the registry all the time. But for the important case of driving a (possibly legacy) 32-bit installed application from a 64-bit python making it just happen would be nice.

Clarity of code snippet in docs

It would be good if you clarified that GUIDs in this snippet should be completely different by alternating characters. E.g., instead of three xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx it'd be good to have xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy and zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz.

Of course, there's a sentence below the snippet that states that GUID must be unique ("separate"), but IMO it wouldn't hurt to clarify this in snippet itself.

Consolidate change log

The root directory contains two files with changelog information. It would be nice if the information is consolidated into one file.

List of 1-tuple not passed to Excel as column array

The following code fails, and I would expect it to fill the "A" column with the values 0-9. Instead, it blanks the cell values.

import comtypes.client as cc
xl = cc.CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Add()
sheet = xl.ActiveSheet

# Doesn't work as expected
sheet.Range("A1:A10").Value[:] = zip(range(10))

# Does work as expected
sheet.Range("A1:A10").Value[:] = np.array(zip(range(10)))

error with inout args

Problem outlined here: http://groups.google.com/group/peachfuzz/browse_thread/thread/b02ea0d0e19ae3a. If you comment out the if paramflags lines it seems to be resolved. Looks like a problem with the _cominterface_meta's _fix_inout_args. When calling something that takes an inout, you'll get a stack trace like this:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\buggery-0.1-py2.7.egg\buggery\debug.py", l
ine 69, in handle_event
retval = self.handlers[eventtype](event)
File "C:\Research\Buggery\Buggery\examples\lmtest.py", line 27, in onException
print self.dbg.registers.get_value_by_name("esp")
File "C:\Python27\lib\site-packages\buggery-0.1-py2.7.egg\buggery\idebug.py",
line 332, in get_value_by_name
self._build_map()
File "C:\Python27\lib\site-packages\buggery-0.1-py2.7.egg\buggery\idebug.py",
line 309, in _build_map
name = self._get_description(i)
File "C:\Python27\lib\site-packages\buggery-0.1-py2.7.egg\buggery\idebug.py",
line 322, in _get_description
reg = self._registers.GetDescription(index, ' '*12, 12)
File "C:\Python27\lib\site-packages\comtypes\__init__.py", line 596, in call_w
ith_inout
v = atyp.from_param(v)
AttributeError: 'str' object has no attribute 'from_param'

Minimum NumPy version?

What should be the minimum supported NumPy version? NumPy is not required to use comtypes, but NumPy arrays can be converted to safearrays when encountered. Optionally, safearrays can be converted to NumPy arrays with the safearray_as_ndarray context manager.
#29 extends the use of NumPy arrays so that arrays of arbitrary objects can be converted to safearrays, provided those objects can be packed inside of a VARIANT. This enhancement requires NumPy 1.7, which suggests 1.7 as the minimum NumPy version.

Generated code contains Python 3 syntax error

comtypes generated code looking like this:

# values for enumeration '_BoolValue'
True = 1
False = 0
BoolValue_Max = 2147483647
_BoolValue = c_int # enum
IHTMLDOMImplementation._methods_ = [

True and False are reserved words in Python 3, so this is a syntax error. It appears that the syntax error when loading the generated code made it repeatedly try to generate the code anew, slowing the application to a crawl. When I edited the cached file, commented out the two lines defining True and False, and re-ran, I stopped seeing errors and the code ran at a normal speed.

Scraps of information available on the web (e.g. here) indicate that _BoolValue is an enum provided by MSHTML. But I think that comtypes should do something to modify names that are Python keywords (e.g. True_ = 1? - I don't know what the constraints are).

It looks like the relevant bit of the code is comtypes.tools.codegenerator.Generator.EnumValue.

Here's the error I see:

# Generating comtypes.gen._3050F1C5_98B5_11CF_BB82_00AA00BDCE0B_0_4_0
Traceback (most recent call last):
  File "pkgs\comtypes\client\_events.py", line 117, in error_printer
    return func(*args, **kw)
  File "pkgs\webview\win32.py", line 253, in DocumentComplete
    custom_doc = self.browser.Document.QueryInterface(ICustomDoc)
  File "pkgs\comtypes\client\__init__.py", line 44, in wrap_outparam
    return GetBestInterface(punk)
  File "pkgs\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "pkgs\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "pkgs\comtypes\client\_generate.py", line 188, in _CreateWrapper
    mod = _my_import(fullname)
  File "pkgs\comtypes\client\_generate.py", line 26, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\Thomas\AppData\Roaming\Python\Python35\comtypes_cache\_3050F1C5
_98B5_11CF_BB82_00AA00BDCE0B_0_4_0.py", line 23290
    True = 1
           ^
SyntaxError: can't assign to keyword
ERROR:comtypes._comobject:Exception in DWebBrowserEvents2.DocumentComplete imple
mentation:
Traceback (most recent call last):
  File "pkgs\comtypes\_comobject.py", line 147, in call_without_this
    result = mth(*inargs)
  File "pkgs\comtypes\client\_events.py", line 117, in error_printer
    return func(*args, **kw)
  File "pkgs\webview\win32.py", line 253, in DocumentComplete
    custom_doc = self.browser.Document.QueryInterface(ICustomDoc)
  File "pkgs\comtypes\client\__init__.py", line 44, in wrap_outparam
    return GetBestInterface(punk)
  File "pkgs\comtypes\client\__init__.py", line 110, in GetBestInterface
    mod = GetModule(tlib)
  File "pkgs\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "pkgs\comtypes\client\_generate.py", line 188, in _CreateWrapper
    mod = _my_import(fullname)
  File "pkgs\comtypes\client\_generate.py", line 26, in _my_import
    return __import__(fullname, globals(), locals(), ['DUMMY'])
  File "C:\Users\Thomas\AppData\Roaming\Python\Python35\comtypes_cache\_3050F1C5
_98B5_11CF_BB82_00AA00BDCE0B_0_4_0.py", line 23290
    True = 1
           ^
SyntaxError: can't assign to keyword

UnicodeDecodeError:

I try
Autodesk MAYA 2008 windows operate from IE 7.0 use comtypes "CreateObject".
ex.
Click "openImageFile"

  1. IE (Maya.CommandEngine.MEL)
  2. MAYA (melCommand "python")
  3. comtypes ( CreateObject("Photoshop.Application") )
    open imageFile on PhotoShop.
1.------ test.html ------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<script type="text/vbscript">
<!--
Dim MEL
Set MEL = CreateObject("Maya.CommandEngine.MEL")
MEL.Connect()
//-->
</script>
</head>
<body>
<p><a href="#" title="open" onclick="MEL.Execute('nh_execPyTest')">openImageFile</a></p>
</body>
</html>
2.------ nh_execPyTest.mel ------
global proc nh_execPyTest(){
python("nh_openPSD2()");
}
3. ------ nh_openPSD2.py ------
from comtypes.client import CreateObject
def nh_openPSD2():
try:
psApp = CreateObject("Photoshop.Application")
docRef = psApp.Open(<IMAGEPATH>)
except Exception, x:
print x
====== ERROR ======
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# File "C:\Documents and Settings\hatori\My Documents\maya\7.0\scripts\opt\et1.py", line 32, in nh_openPSD2
# psApp = CreateObject("Photoshop.Application")
# File "C:\Python25\Lib\site-packages\comtypes\client\__init__.py", line 197, in CreateObject
# obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
# File "C:\Python25\Lib\site-packages\comtypes\__init__.py", line 1119, in CoCreateInstance
# _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
# File "..\Modules\_ctypes\callproc.c", line 754, in GetResult
# WindowsError: (-2147417843, '\x83A\x83v\x83......') #
...... is
UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 20: ordinal not in range(128)
=====================

--- sitecustomize.py ---
import sys
sys.setdefaultencoding('utf-8')
and win32com
http://techarttiki.blogspot.com/2008/08/photoshop-scripting-with-python.html
was error.
nh_execPyTest.mel and nh_openPSD2.py is operating.
Could advice be got?

Comtypes depends on numpy for wstring[] attributes

From the mailing list: http://sourceforge.net/p/comtypes/mailman/message/32392260/

I've just hit an issue using comtypes to interact with Virtualbox.
Here's the simplest test case I can create:

import comtypes.client
import comtypes.gen.VirtualBox

vbox = comtypes.client.CreateObject('VirtualBox.VirtualBox')
machine = vbox.FindMachine('Ahri')
adapter = machine.getNetworkAdapter(0)
nat = adapter.NATEngine
print(repr(nat.redirects))

This gets the redirects property from the NatEngine object, which is
documented as follows:

readonly attribute wstring[] redirects
Array of NAT port-forwarding rules in string representation, in the
following format: "name,protocol id,host ip,host port,guest ip,guest
port".

When I run this test, I get:

python .\test.py
Traceback (most recent call last):
File ".\test.py", line 8, in
print(repr(nat.redirects))
File "C:\Work\Projects\vm\ve\lib\site-packages\comtypes__init__.py",
line 279, in getattr
return getattr(self, fixed_name)
File "C:\Work\Projects\vm\ve\lib\site-packages\comtypes\safearray.py",
line 218, in ctypes_from_outparam
return self[0]
File "C:\Work\Projects\vm\ve\lib\site-packages\comtypes\safearray.py",
line 209, in getitem
return self.unpack()
File "C:\Work\Projects\vm\ve\lib\site-packages\comtypes\safearray.py",
line 234, in unpack
result = self._get_elements_raw(num_elements)
File "C:\Work\Projects\vm\ve\lib\site-packages\comtypes\safearray.py",
line 301, in _get_elements_raw
import numpy.ctypeslib
ImportError: No module named 'numpy'

As far as I can tell, comtypes is interpreting the array of wstring
objects as a 2-dimensional array, and as a result thinks it needs
numpy.

Two suggestions here:

  1. If numpy isn't available, fall back to something core Python can
    handle like a tuple of tuples.
  2. In this particular case, the code should be returning a tuple of
    (Unicode) strings.

The equivalent code works with pywin32, for what it's worth.

python comtypes how to pass numpy float32 (singe-precision float) as scalar?

http://stackoverflow.com/questions/32617904/python-comtypes-how-to-pass-numpy-float32-singe-precision-float-as-scalar

According to comtypes documentation is is possible to pass numpy arrays to comtypes objects, but how to I pass scalar values, e.g. numpy.float32(1.0)?

https://pythonhosted.org/comtypes/#numpy-interop

I get following error:

---------------------------------------------------------------------------
ArgumentError                             Traceback (most recent call last)
<ipython-input-67-9e7e5859c6a5> in <module>()
----> 1 com_obj.Update("string_name",np.float32(6.6e-6))
ArgumentError: argument 2: <type 'exceptions.TypeError'>: Cannot put 6.5999998e-06 in VARIANT

NumPy API breakage

Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import comtypes
{'offsets': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'names':
['VT_BOOL', 'VT_I1', 'VT_I2', 'VT_I4', 'VT_I8', 'VT_INT', 'VT_UI1', 'VT_UI2', 'V
T_UI4', 'VT_UI8', 'VT_UINT', 'VT_R4', 'VT_R8', 'VT_CY', 'c_wchar_p', 'c_void_p',
 'pparray', 'bstrVal', '_tagBRECORD'], 'formats': ['<i2', '<i1', '<i2', '<i4', '
<i8', '<i4', '<u1', '<u2', '<u4', '<u8', '<u4', '<f4', '<f8', '<i8', '<u8', '<u8
', '<u8', '<u8', [('pvRecord', '<u8'), ('pRecInfo', '<u8')]]}Traceback (most rec
ent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\comtypes-1.1.1-py2.7.egg\comtypes\__init__
.py", line 1171, in <module>
    class IPersist(IUnknown):
  File "C:\Python27\lib\site-packages\comtypes-1.1.1-py2.7.egg\comtypes\__init__
.py", line 1176, in IPersist
    ( ['out'], POINTER(GUID), 'pClassID' )),
  File "C:\Python27\lib\site-packages\comtypes-1.1.1-py2.7.egg\comtypes\__init__
.py", line 1093, in COMMETHOD
    from comtypes.automation import VARIANT
  File "C:\Python27\lib\site-packages\comtypes-1.1.1-py2.7.egg\comtypes\automati
on.py", line 12, in <module>
    from comtypes import npsupport
  File "C:\Python27\lib\site-packages\comtypes-1.1.1-py2.7.egg\comtypes\npsuppor
t.py", line 96, in <module>
    com_null_date64 = datetime64("1899-12-30T00:00:00", "ns")
TypeError: function takes at most 1 argument (2 given)
>>> import numpy
>>> numpy.__version__
'1.6.2'

Apparently the datetime api has changed between 1.6 and 1.7.

I think a explicit version check would be nice instead of flat out failing.

ERROR in test_dyndispatch

Seen under 64-bit python.

======================================================================
ERROR: test (comtypes.test.test_dyndispatch.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_dyndispatch.py", line 7, in test
    d = CreateObject("MSScriptControl.ScriptControl")
  File "build\lib\comtypes\client\__init__.py", line 238, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File "build\lib\comtypes\__init__.py", line 1179, in CoCreateInstance
    _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
  File "_ctypes/callproc.c", line 945, in GetResult
WindowsError: [Error -2147221164] Class not registered

broken test scripts using ConnectableObjectMixin

Both ./test/TestComServer.py and ./TestDispServer.py scripts are broken in 0.6.0 (tested on Windows XP, both .zip and .exe distribution).
I was able to debug for the actual cause, the reason is that classes using ConnectableObjectMixin (comtypes.server.connectionpoints.ConnectableObjectMixin) require that outgoing_interfaces be declared in the class definition.
So line 107 in server/connectionpoints.py fails when creating a client tries to use the com object.
Actually, TestDispServer.tlb is missing (yes, this time I confirmed it's missing from the .exe distribution), I just focused on the TestComServer.py script, but I'm sure it will fail when having the .tlb file due to the same reason.
I don't know what's best, just simple remove the ConnectableObjectMixin from the class (I don't like this, but works) or implement the outgoing_interfaces classes (yes, I would like this!) so we have a great hint on how to use it.
R. Aguirre

safearray __del__ raises AttributeError on interpreter shutdown

#a.py
from comtypes.automation import _midlSAFEARRAY
from comtypes.automation import VARIANT

foo = _midlSAFEARRAY(VARIANT).from_param([0, 1, 2])
#b.py
class Bar:
    __metaclass__ = type
    import a
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win 32
Type "help", "copyright", "credits" or "license" for more information.

C:\test>python b.py
Exception AttributeError: "'NoneType' object has no attribute 'SafeArrayDestroy'" in <bound method LP_SAFEARRAY_tagVARIANT.__del__ of comtypes.safearray.LP_SAFEARRAY_tagVARIANT object at 0x01FEFA30>> ignored

This seems to be the same issue as http://bugs.python.org/issue5099.

https://hg.python.org/cpython/rev/ca496bfacd1b/

subprocess.Popen.del referenced global objects, which is a no-no thanks to interpreter shutdown semantics. Same issue goes for the methods that del called. Now all the methods capture the global objects it needs as default values to private parameters (could have stuck them on the class object itself, but since the objects have nothing directly to do with the class that seemed wrong).

The same approach solves the problem for me.

        def __del__(self, SafeArrayDestroy=_safearray.SafeArrayDestroy):
            if self._needsfree:
                SafeArrayDestroy(self)

I haven't found out yet why my example triggers this issue.

access violation with wrong array.array type

i call a COM function waiting a uint32 with a wrong 16bits array.array('H').
The result is an access violation:
File "C:\Python27\lib\site-packages\comtypes__init__.py", line 604, in call_with_inout
v = atyp.from_param(v)
File "C:\Python27\lib\site-packages\comtypes\safearray.py", line 199, in from_param
value = cls.create(value, extra)
File "C:\Python27\lib\site-packages\comtypes\safearray.py", line 138, in create
memmove(ptr, addr, nbytes)
WindowsError: exception: access violation reading 0x04AFD000
May be a test on types is missing
regards

Crash caused by incorrectly generated code for VARIANT function input

While working with AutoCAD objects ran into app crash. It was reported sometimes as stack overflow or access violation.
Investigation showed that there was a method signature generated as:

IAcadBlock._methods_ = [
    COMMETHOD([dispid(0), helpstring(u'Gets the member object at a given index in a collection, group, or selection set')], HRESULT, 'Item',
              ( ['in'], VARIANT, 'Index' ),
              ( ['retval', 'out'], POINTER(POINTER(IAcadEntity)), 'pItem' )),

Manual tweaking and change to (Note POINTER(VARIANT) vs VARIANT as an input):

IAcadBlock._methods_ = [
    COMMETHOD([dispid(0), helpstring(u'Gets the member object at a given index in a collection, group, or selection set')], HRESULT, 'Item',
              ( ['in'], POINTER(VARIANT), 'Index' ),
              ( ['retval', 'out'], POINTER(POINTER(IAcadEntity)), 'pItem' )),

made it run as expected.

Not sure yet where this has to be fixed to make it permanent in the code generation logic.

I can provide tlb file used to produce generated code. Please let me know.

Convert Decimal to VT_DECIMAL instead of VT_CY?

Currently Decimal objects are converted to currency variants (VT_CY) when passed as a VARIANT argument. However, there is a decimal VARIANT (http://msdn.microsoft.com/en-us/library/cc234586.aspx), which seems like the less surprising conversion choice. I can think of some practical reasons for converting Decimals to currency, but those reasons are not universal and should probably not define the default conversion behavior.

Right now I see no reason to change this, except that it "feels wrong". Any other opinions?

Anaconda Python + comtypes 1.1.2

I had to switch from Active Python to Anaconda Python (2.7.10) under Windows 7 64bit. I installed the latest comtypes 1.1.2 and still get an error. But the code worked with Active Python well.

from ctypes import *
import comtypes.client
from comtypes.automation import *

print "test"

It throws the following error:

test
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    import comtypes.client
  File "C:\Program Files\Anaconda\lib\site-packages\comtypes-1.1.2-py2.7.egg\com
types\__init__.py", line 902
    class _compointer_base(c_void_p, metaclass=_compointer_meta):
                                              ^
SyntaxError: invalid syntax

Is this because of an incompability between Anaconda and comtypes?

FAIL in test_LoadTypeLibEx

Seen in the x86 tests for #32. The failure is not related to that PR.

======================================================================
FAIL: test_LoadTypeLibEx (comtypes.test.test_typeinfo.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_typeinfo.py", line 34, in test_LoadTypeLibEx
    self.failUnlessEqual(tlib, other_tlib)
AssertionError: <POINTER(ITypeLib) ptr=0x69f3a8 at 2600a30> != <POINTER(ITypeLib) ptr=0x69f7f8 at 709b8f0>

----------------------------------------------------------------------

TypeError: object is not iterable

Hello I've been running into this situation. Basically almost all com functions that's been calling to date returns a tuple. But this one returns a single pointer, which is causing this error.

Traceback (most recent call last):
  File "clisse.py", line 282, in <module>
    cont.delete_child(child)
  File "clisse.py", line 105, in delete_child
    self.content.Delete(0, object_ids)
  File "C:\Users\Francois\.dev\lib\site-packages\comtypes\__init__.py", line 657, in call_with_inout
    rescode = list(rescode)
TypeError: 'POINTER(IPortableDevicePropVariantCollection)' object is not iterable

I've been able to fix the problem locally, but I'm not sure if this is a needed fix or if i'm doing something wrong.

if isinstance(rescode, collections.Iterable):
    rescode = list(rescode)
else:
    rescode = [rescode]

Here is the snippet of code that I'm calling:

object_ids = comtypes.client.CreateObject(types.PortableDevicePropVariantCollection,
                                                    clsctx=comtypes.CLSCTX_INPROC_SERVER,
                                                    interface=port.IPortableDevicePropVariantCollection)
object_ids.Add(StringToPropVariant(child.objectID))
self.content.Delete(0, object_ids)

64-bit comtypes raise "Bad variable type."

The following code work fine in 32-bit comtypes:-

C:\Users\vm>python
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from comtypes.client import CreateObject
>>>
>>> ie = CreateObject("InternetExplorer.Application")
>>> ie.Visible = True
>>> ie.Navigate('www.google.com')
0
>>> ie.document.getElementsByName('q')[0].value = 'pypi comtypes'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\comtypes-1.1.0-py2.7.egg\comtypes\__init__.py", line 380, in __getitem__
    result = self.Item(*args)
_ctypes.COMError: (-2147352568, 'Bad variable type.', (None, None, None, 0, None))
>>>

Returned tuple from COM method doesn't include all outputs

I am accessing SolidWorks via COM using comtypes. I create a new application object as follows:
swApp=comtypes.client.CreateObject('sldworks.application')
To open files with this application, you use the OpenDoc6 method, which is as follows:
ModelDoc2 OpenDoc6(string FileName, int Type, int Options, String Configuration, [Out] int Errors, [Out] int Warnings) (taken from the api help files.
When I call swApp.OpenDoc6, the ModelDoc2 object is not returned. Instead I only get a tuple containing the Errors and Warnings.
I have possible solution, which might not necessarily be all that good:
If I change comtypes/init.py line 599 to use rescode (the return from the function) as opposed to outargs, then I get a tuple containing all three outputs. Not sure this would work for all COM libraries.
djm one five eight @ieee.org (where the numbers are really numbers) to ask questions of me.

List-index access to COM object array crashes python

This bug happened to me a year ago so I'm a little fuzzy on exactly what happened, but it was a doozy. Here is some code that repros the bug

items = (POINTER(IWiaItem) * NUM_OBJECTS_TO_REQUEST)()
num_fetched = enum.Next(NUM_OBJECTS_TO_REQUEST, items)
print items[0]
print items[0]

where enum.Next has a signature of

COMMETHOD([], HRESULT, 'Next',
( ['in'], ULONG, 'celt'),
( ['in, out'], POINTER(POINTER(IWiaItem)), 'ppIWiaItem'),
( ['out'], POINTER(ULONG), 'pceltFetched'))

The array items is an array of IWiaItems. When you do items[0], it helpfully turns the thing into an actual IWiaItem object for you to use, but when that object is destroyed, we call __com_Release. So when you do items[0] the second time, it does Release again (and it only did AddReference once). So eventually, crash! Yay.
Another user reported same in the user reviews on https://sourceforge.net/projects/comtypes/.

What copyright for the license file?

According to the setup.py, comtypes should be under an MIT license. The license statement should be added to the project.

The only question in my mind is how to display the copyright. For 2014 (and beyond), I would like to have the project copyright "Comtypes developers". This mirrors the NumPy license.

@jaraco, @mdickinson, as recent contributors to the code, does this work for you?

I will check with Tomas Heller about the copyright for 2006-2013.

comtypes com object's method returns: 'tuple' object has no attribute '__ctypes_from_outparam__'

http://stackoverflow.com/questions/32869070/comtypes-com-objects-method-returns-tuple-object-has-no-attribute-ctypes

I'm invoking a method of COM object with string argument using comtypes and method returns:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-102-009507ff0086> in <module>()
----> 1 obj1=xobjData.GetDataType('string_name')

C:\Python\Python27\lib\site-packages\comtypes\__init__.pyc in call_with_inout(self_, *args, **kw)
    657             # be iterable.
    658             if len(outargs) == 1:  # rescode is not iterable
--> 659                 return rescode.__ctypes_from_outparam__()
    660 
    661             rescode = list(rescode)

AttributeError: 'tuple' object has no attribute '__ctypes_from_outparam__'

Seems very cryptic error, any help?

%debug magic shows following:

> c:\python\python27\lib\site-packages\comtypes\__init__.py(659)call_with_inout()
    658             if len(outargs) == 1:  # rescode is not iterable
--> 659                 return rescode.__ctypes_from_outparam__()
    660 

ipdb> outargs
{0: VARIANT(vt=0x8, u'string_name')}
ipdb> rescode
(VARIANT(vt=0x8, u'string_name'), u'Long')
ipdb> exit

comtypes 1.1.2 fails, but pywin32 220 succeeds on python 2.7 32 bit

use_comtypes=True
if use_comtypes:
    import comtypes
    from comtypes.client import CreateObject
    from comtypes.safearray import safearray_as_ndarray
    xobjRegistry = CreateObject("MyApplication")
else:
    import win32com
    xobjRegistry = win32com.client.gencache.EnsureDispatch("MyApplication") 
import numpy as np
from ctypes import c_float

strComputerName = ''
strServerName = 'Server'
xobjServer = xobjRegistry.LocateObject(strComputerName, strServerName)

comtypes fails with the following exception and traceback:

---------------------------------------------------------------------------
COMError                                  Traceback (most recent call last)
<ipython-input-10-232f3dfedda5> in <module>()
     13 strComputerName = ''
     14 strServerName = 'Server'
---> 15 xobjServer = xobjRegistry.LocateObject(strComputerName, strServerName)
     16 
     17 xobjData = xobjServer.globaldata

c:\python\python27\lib\site-packages\comtypes\client\__init__.pyc in wrap_outparam(punk)
     42         return None
     43     if punk.__com_interface__ == comtypes.automation.IDispatch:
---> 44         return GetBestInterface(punk)
     45     return punk
     46 

c:\python\python27\lib\site-packages\comtypes\client\__init__.pyc in GetBestInterface(punk)
    124     # Could the above code, as an optimization, check that QI works,
    125     # *before* generating the wrapper module?
--> 126     result = punk.QueryInterface(interface)
    127     logger.debug("Final result is %s", result)
    128     return result

c:\python\python27\lib\site-packages\comtypes\__init__.pyc in QueryInterface(self, interface, iid)
   1156         if iid is None:
   1157             iid = interface._iid_
-> 1158         self.__com_QueryInterface(byref(iid), byref(p))
   1159         clsid = self.__dict__.get('__clsid')
   1160         if clsid is not None:

COMError: (-2147467262, 'No such interface supported', (None, None, None, 0, None))

ERROR in test_comtypes

Seen under 64-bit python.

======================================================================
ERROR: test_comtypes (comtypes.test.test_dispinterface.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_dispinterface.py", line 88, in test_comtypes
    d.eval("__import__('comtypes.client').client.CreateObject('MSScriptControl.ScriptControl')")
  File "build\lib\comtypes\__init__.py", line 533, in func
    return self.Invoke(obj, memid, _invkind=1, *args, **kw) # DISPATCH_METHOD
  File "build\lib\comtypes\automation.py", line 744, in Invoke
    byref(result), byref(excepinfo), byref(argerr))
COMError: (-2147221164, 'Class not registered', (None, None, None, 0, None))
```python

ERROR in test_comtypes (32- and 64-bit python)

Seen under 32- and 64-bit python.

======================================================================
ERROR: test_comtypes (comtypes.test.test_dispinterface.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_dispinterface.py", line 99, in test_comtypes
    self.assertEqual(d.id, server_id)
  File "build\lib\comtypes\__init__.py", line 539, in _get
    return obj.Invoke(memid, _invkind=2) # DISPATCH_PROPERTYGET
  File "build\lib\comtypes\automation.py", line 744, in Invoke
    byref(result), byref(excepinfo), byref(argerr))
COMError: (-2147467259, 'Unspecified error', (u"<type 'exceptions.TypeError'>: DTestDispServer__get_id() takes exactly 3 arguments (2 given)", u'TestDispServerLib.TestDispServer.1', None, 0, None))

VT_UNKNOWN safearray tests fail

======================================================================
ERROR: test_VT_UNKNOWN_multi (__main__.SafeArrayTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "comtypes/test/test_safearray.py", line 317, in test_VT_UNKNOWN_multi
    sa = t.from_param((punk,) * 4)
  File "c:\users\eric\projects\comtypes\comtypes\safearray.py", line 200, in from_param
    value = cls.create(value, extra)
  File "c:\users\eric\projects\comtypes\comtypes\safearray.py", line 142, in create
    ptr[index] = item
  File "c:\users\eric\projects\comtypes\comtypes\__init__.py", line 316, in __setitem__
    super(_, self).__setitem__(index, value)
NameError: global name '_' is not defined

======================================================================
ERROR: test_VT_UNKNOWN_multi_ndarray (__main__.SafeArrayTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "comtypes/test/test_safearray.py", line 372, in test_VT_UNKNOWN_multi_ndarray
    sa = t.from_param((punk,) * 4)
  File "c:\users\eric\projects\comtypes\comtypes\safearray.py", line 200, in from_param
    value = cls.create(value, extra)
  File "c:\users\eric\projects\comtypes\comtypes\safearray.py", line 142, in create
    ptr[index] = item
  File "c:\users\eric\projects\comtypes\comtypes\__init__.py", line 316, in __setitem__
    super(_, self).__setitem__(index, value)
NameError: global name '_' is not defined

Many failures in test_createwrappers under 64-bit python

This was acquired on Windows 7. The test attempts to create wrappers for everything it can find, which differs from system to system. (On 32-bit windows XP only about 1300 files are wrapped.)

An investigation of one of the failures indicated that unions may not be built or validated properly in all cases.

...............................................................E.....................................................................................................................................................................................................................c:\documents and settings\factory\projects\comtypes\comtypes\tools\codegenerator.py:477: UserWarning: Structure __MIDL_IOleAutomationTypes_0004: PACKING FAILED: total alignment (8/64)
  warnings.warn(message, UserWarning)
FF....F.F.............................................................................................................................................................................................................................................E.....................................................................................................................................................................................................................................................................................................F.........................................................................................................................................................................................................................................................................................................................................................FF..............................................................................................................................F......................................................F..........................................................................F..E......................................................................................................................................................................................................................................................................................................F.........................................................................................................................................................................................................
======================================================================
ERROR: test_1054 (__main__.Test)
test GetModule('C:\\Windows\\system32\\netprofm.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 415, in <module]]
]]>

  File "c:\documents and settings\factory\projects\comtypes\comtypes\__init__.py", line 330, in __setattr__
    self._make_specials()
  File "c:\documents and settings\factory\projects\comtypes\comtypes\__init__.py", line 385, in _make_specials
    class _(partial.partial, self):
  File "c:\documents and settings\factory\projects\comtypes\comtypes\partial.py", line 41, in __new__
    raise TypeError("%r already has %s" % (base, k))
TypeError: <class 'comtypes.gen._DCB00D01_570F_4A9B_8D69_199FDBA5723B_0_1_0.IEnumNetworks'> already has __iter__

======================================================================
ERROR: test_1469 (__main__.Test)
test GetModule('C:\\Windows\\system32\\sppcomapi.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 1167, in <module]]
]]>

  File "c:\documents and settings\factory\projects\comtypes\comtypes\__init__.py", line 330, in __setattr__
    self._make_specials()
  File "c:\documents and settings\factory\projects\comtypes\comtypes\__init__.py", line 385, in _make_specials
    class _(partial.partial, self):
  File "c:\documents and settings\factory\projects\comtypes\comtypes\partial.py", line 41, in __new__
    raise TypeError("%r already has %s" % (base, k))
TypeError: <class 'comtypes.gen._B0C2A63F_AFF8_40E3_B42D_8A542DC909EC_0_1_0.IEnumNetworks'> already has __iter__

======================================================================
ERROR: test_551 (__main__.Test)
test GetModule('C:\\Windows\\system32\\icardie.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 35, in <module]]
]]>

  File "c:\documents and settings\factory\projects\comtypes\comtypes\safearray.py", line 53, in _midlSAFEARRAY
    sa_type = _make_safearray_type(itemtype)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\safearray.py", line 87, in _make_safearray_type
    raise TypeError(itemtype)
TypeError: <class 'comtypes.safearray.LP_SAFEARRAY_c_ubyte'>

======================================================================
FAIL: test_1247 (__main__.Test)
test GetModule('C:\\Windows\\system32\\PortableDeviceApi.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 1871, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_1248 (__main__.Test)
test GetModule('C:\\Windows\\system32\\PortableDeviceClassExtension.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 989, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_1252 (__main__.Test)
test GetModule('C:\\Windows\\system32\\PortableDeviceTypes.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 118, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_1254 (__main__.Test)
test GetModule('C:\\Windows\\system32\\PortableDeviceWMDRM.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 340, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_1733 (__main__.Test)
test GetModule('C:\\Windows\\system32\\wiascanprofiles.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 830, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_316 (__main__.Test)
test GetModule('C:\\Windows\\system32\\DevicePairingHandler.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 299, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_317 (__main__.Test)
test GetModule('C:\\Windows\\system32\\DevicePairingProxy.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 113, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_431 (__main__.Test)
test GetModule('C:\\Windows\\system32\\EhStorAPI.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 1438, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_481 (__main__.Test)
test GetModule('C:\\Windows\\system32\\fundisc.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 1002, in <module]]
]]>

AssertionError: 8

======================================================================
FAIL: test_549 (__main__.Test)
test GetModule('C:\\Windows\\system32\\iassvcs.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 446, in <module]]
]]>

AssertionError: 4

======================================================================
FAIL: test_817 (__main__.Test)
test GetModule('C:\\Windows\\system32\\LocationApi.dll')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_createwrappers.py", line 46, in test
    comtypes.client.GetModule(fname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 112, in GetModule
    mod = _CreateWrapper(tlib, pathname)
  File "c:\documents and settings\factory\projects\comtypes\comtypes\client\_generate.py", line 183, in _CreateWrapper
    exec code in mod.__dict__
  File "<string>", line 1305, in <module]]
]]>

AssertionError: 8

----------------------------------------------------------------------
Ran 1921 tests in 21.246s

FAILED (failures=11, errors=3)

use logging consistently, but remember the newbies

This issue was raised during the discussion of #95, namely that there are some places where informational messages are printed directly instead of using logging.

I agree that it would be good to use logging consistently everywhere, but I would like to point out that I particularly like the usage of the __verbose__ flag in clients._generate.py to print the file generation messages.

I am a Python newbie and haven't spent the time to figure out how to use logging yet, but I was able to see right away when my files were generated, which is why I followed that pattern in my pull request.

When you replace these kludges with proper logging, please set up the defaults so that these code generation messages and my munge warnings still display by default for those who don't know how to use the logging module (or at least provide really good, really obvious instructions).

Thanks.

Incompatible change: 'null' instead of ''

Discover this incompatible change when checking on #66

import time
from comtypes.client import CreateObject
ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.Navigate('www.google.com')
time.sleep(3) # wait for navigation to complete
el = ie.document.getElementsByName('q')
el["", 0].value = ''

Older version of comtypes correctly assign '' (empty string), version 1.1 assign 'null' instead.

ERROR in test_with_args

Seen under 64-bit python.

======================================================================
ERROR: test_with_args (comtypes.test.test_dyndispatch.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_dyndispatch.py", line 19, in test_with_args
    d = CreateObject("MSScriptControl.ScriptControl")
  File "build\lib\comtypes\client\__init__.py", line 238, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File "build\lib\comtypes\__init__.py", line 1179, in CoCreateInstance
    _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
  File "_ctypes/callproc.c", line 945, in GetResult
WindowsError: [Error -2147221164] Class not registered

Failure in test_IEnumVARIANT

Seen under 64-bit python.

======================================================================
ERROR: test_IEnumVARIANT (comtypes.test.test_collections.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "build\lib\comtypes\test\test_collections.py", line 41, in test_IEnumVARIANT
    self.failUnlessEqual(cv[0].ProcessImageFileName, names[0])
  File "build\lib\comtypes\automation.py", line 571, in __getitem__
    raise IndexError
IndexError

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.