def _DumpObject(ob, level = 0):
prefix = " " * level
print "%s%s object: %s" % (prefix, ob.Class, ob.Name)
# Do the directory object thing
try:
dir_ob = ADsGetObject(ob.ADsPath, IID_IDirectoryObject)
except pythoncom.com_error:
dir_ob = None
if dir_ob is not None:
info = dir_ob.GetObjectInformation()
print "%s RDN='%s', ObjectDN='%s'" % (prefix, info.RDN, info.ObjectDN)
# Create a list of names to fetch
names = ["distinguishedName"]
attrs = dir_ob.GetObjectAttributes(names)
for attr in attrs:
for val, typ in attr.Values:
print "%s Attribute '%s' = %s" % (prefix, attr.AttrName, val)
for child in ob:
_DumpObject(child, level+1)
python类com_error()的实例源码
def check_is_admin():
global _is_admin
if _is_admin is None:
from win32com.shell.shell import IsUserAnAdmin
import pythoncom
try:
_is_admin = IsUserAnAdmin()
except pythoncom.com_error, exc:
if exc.hresult != winerror.E_NOTIMPL:
raise
# not impl on this platform - must be old - assume is admin
_is_admin = True
return _is_admin
# If this exception is raised by a test, the test is reported as a 'skip'
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
self.editwindow = self.GetDlgItem(132)
self.editwindow.HookAllKeyStrokes(self.OnKey)
self.olectl = MySerialControl(self)
try:
self.olectl.CreateControl("OCX",
win32con.WS_TABSTOP | win32con.WS_VISIBLE,
(7,43,500,300), self._obj_, 131)
except win32ui.error:
self.MessageBox("The Serial Control could not be created")
self.olectl = None
self.EndDialog(win32con.IDCANCEL)
if self.olectl:
self.olectl.Settings = SERIAL_SETTINGS
self.olectl.CommPort = SERIAL_PORT
self.olectl.RThreshold = 1
try:
self.olectl.PortOpen = 1
except pythoncom.com_error, details:
print "Could not open the specified serial port - %s" % (details.excepinfo[2])
self.EndDialog(win32con.IDCANCEL)
return rc
def _build_typeinfos_(self):
# Can only ever be one for now.
tlb_guid = getattr(self._obj_, '_typelib_guid_', None)
if tlb_guid is None:
return []
tlb_major, tlb_minor = getattr(self._obj_, '_typelib_version_', (1,0))
tlb = pythoncom.LoadRegTypeLib(tlb_guid, tlb_major, tlb_minor)
typecomp = tlb.GetTypeComp()
# Not 100% sure what semantics we should use for the default interface.
# Look for the first name in _com_interfaces_ that exists in the typelib.
for iname in self._obj_._com_interfaces_:
try:
type_info, type_comp = typecomp.BindType(iname)
if type_info is not None:
return [type_info]
except pythoncom.com_error:
pass
return []
def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bGUIProgress = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
"""Generate support for a type library.
Given the IID, LCID and version information for a type library, generate
and import the necessary support files.
Returns the Python module. No exceptions are caught.
Params
typelibCLSID -- IID of the type library.
major -- Integer major version.
minor -- Integer minor version.
lcid -- Integer LCID for the library.
progressInstance -- Instance to use as progress indicator, or None to
use the GUI progress bar.
"""
if bGUIProgress is not None:
print "The 'bGuiProgress' param to 'MakeModuleForTypelib' is obsolete."
import makepy
try:
makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
except pywintypes.com_error:
return None
return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
def MakeModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
"""Generate support for a type library.
Given a PyITypeLib interface generate and import the necessary support files. This is useful
for getting makepy support for a typelibrary that is not registered - the caller can locate
and load the type library itself, rather than relying on COM to find it.
Returns the Python module.
Params
typelib_ob -- The type library itself
progressInstance -- Instance to use as progress indicator, or None to
use the GUI progress bar.
"""
import makepy
try:
makepy.GenerateFromTypeLibSpec( typelib_ob, progressInstance=progressInstance, bForDemand = bForDemandDefault, bBuildHidden = bBuildHidden)
except pywintypes.com_error:
return None
tla = typelib_ob.GetLibAttr()
guid = tla[0]
lcid = tla[1]
major = tla[3]
minor = tla[4]
return GetModuleForTypelib(guid, lcid, major, minor)
def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on!
"""Given a COM prog_id, return an object that is using makepy support, building if necessary"""
disp = win32com.client.Dispatch(prog_id)
if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
try:
ti = disp._oleobj_.GetTypeInfo()
disp_clsid = ti.GetTypeAttr()[0]
tlb, index = ti.GetContainingTypeLib()
tla = tlb.GetLibAttr()
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
GetModuleForCLSID(disp_clsid)
# Get the class from the module.
import CLSIDToClass
disp_class = CLSIDToClass.GetClass(str(disp_clsid))
disp = disp_class(disp._oleobj_)
except pythoncom.com_error:
raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
return disp
def Dispatch(IDispatch, userName = None, createClass = None, typeinfo = None, UnicodeToString=None, clsctx = pythoncom.CLSCTX_SERVER):
assert UnicodeToString is None, "this is deprecated and will go away"
IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx)
if createClass is None:
createClass = CDispatch
lazydata = None
try:
if typeinfo is None:
typeinfo = IDispatch.GetTypeInfo()
if typeinfo is not None:
try:
#try for a typecomp
typecomp = typeinfo.GetTypeComp()
lazydata = typeinfo, typecomp
except pythoncom.com_error:
pass
except pythoncom.com_error:
typeinfo = None
olerepr = MakeOleRepr(IDispatch, typeinfo, lazydata)
return createClass(IDispatch, olerepr, userName, lazydata=lazydata)
def _Build_CoClass(self, type_info_tuple):
info, infotype, doc, attr = type_info_tuple
# find the source and dispinterfaces for the coclass
child_infos = []
for j in range(attr[8]):
flags = info.GetImplTypeFlags(j)
try:
refType = info.GetRefTypeInfo(info.GetRefTypeOfImplType(j))
except pythoncom.com_error:
# Can't load a dependent typelib?
continue
refAttr = refType.GetTypeAttr()
child_infos.append( (info, refAttr.typekind, refType, refType.GetDocumentation(-1), refAttr, flags) )
# Done generating children - now the CoClass itself.
newItem = CoClassItem(info, attr, doc)
return newItem, child_infos
def __init__(self, oobj=None):
if oobj is None:
oobj = pythoncom.new(self.CLSID)
elif isinstance(oobj, DispatchBaseClass):
try:
oobj = oobj._oleobj_.QueryInterface(self.CLSID, pythoncom.IID_IDispatch) # Must be a valid COM instance
except pythoncom.com_error, details:
import winerror
# Some stupid objects fail here, even tho it is _already_ IDispatch!!??
# Eg, Lotus notes.
# So just let it use the existing object if E_NOINTERFACE
if details.hresult != winerror.E_NOINTERFACE:
raise
oobj = oobj._oleobj_
self.__dict__["_oleobj_"] = oobj # so we dont call __setattr__
# Provide a prettier name than the CLSID
def test():
import win32com.client
oldcwd = os.getcwd()
try:
session = gencache.EnsureDispatch("MAPI.Session")
try:
session.Logon(GetDefaultProfileName())
except pythoncom.com_error, details:
print "Could not log on to MAPI:", details
return
except pythoncom.error:
# no mapi.session - let's try outlook
app = gencache.EnsureDispatch("Outlook.Application")
session = app.Session
try:
TestUser(session)
TestAddress(session)
DumpFolders(session)
finally:
session.Logoff()
# It appears Exchange will change the cwd on us :(
os.chdir(oldcwd)
def DispExTest(ob):
if not __debug__: print "WARNING: Tests dressed up as assertions are being skipped!"
assert ob.GetDispID("Add", 0)==10, "Policy did not honour the dispid"
# Not impl
# assert ob.GetMemberName(10, 0)=="add", "Policy did not give me the correct function for the dispid"
assert ob.GetDispID("Remove", 0)==11, "Policy did not honour the dispid"
assert ob.GetDispID("In", 0)==1000, "Allocated dispid unexpected value"
assert ob.GetDispID("_NewEnum", 0)==pythoncom.DISPID_NEWENUM, "_NewEnum() got unexpected DISPID"
dispids = []
dispid = -1
while 1:
try:
dispid = ob.GetNextDispID(0, dispid)
dispids.append(dispid)
except pythoncom.com_error, (hr, desc, exc, arg):
assert hr==winerror.S_FALSE, "Bad result at end of enum"
break
dispids.sort()
if dispids != [pythoncom.DISPID_EVALUATE, pythoncom.DISPID_NEWENUM, 10, 11, 1000]:
raise Error("Got back the wrong dispids: %s" % dispids)
def testShellLink(self):
desktop = str(shell.SHGetSpecialFolderPath(0, CSIDL_DESKTOP))
num = 0
shellLink = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
persistFile = shellLink.QueryInterface(pythoncom.IID_IPersistFile)
names = [os.path.join(desktop, n) for n in os.listdir(desktop)]
programs = str(shell.SHGetSpecialFolderPath(0, CSIDL_PROGRAMS))
names.extend([os.path.join(programs, n) for n in os.listdir(programs)])
for name in names:
try:
persistFile.Load(name,STGM_READ)
except pythoncom.com_error:
continue
# Resolve is slow - avoid it for our tests.
#shellLink.Resolve(0, shell.SLR_ANY_MATCH | shell.SLR_NO_UI)
fname, findData = shellLink.GetPath(0)
unc = shellLink.GetPath(shell.SLGP_UNCPRIORITY)[0]
num += 1
if num == 0:
# This isn't a fatal error, but is unlikely.
print "Could not find any links on your desktop or programs dir, which is unusual"
def add_group_member( groupLoc, group, userLoc, user ):
try:
ad_obj=win32com.client.GetObject( "LDAP://cn=%s,%s" % (group, groupLoc) )
ad_obj.Add( "LDAP://cn=%s,%s" % (user, userLoc) )
ad_obj.SetInfo()
except pythoncom.com_error,( hr,msg,exc,arg ):
print "Error adding user %s to group %s..." % (user, group)
print hr, msg, exc, arg
def FavDumper(nothing, path, names):
# called by os.path.walk
for name in names:
print name,
try:
DumpLink(name)
except pythoncom.com_error:
print " - not a link"
def GetUIObjectOf(self, hwndOwner, pidls, iid, inout):
# delegate to the shell.
assert len(pidls)==1, "oops - arent expecting more than one!"
pidl = pidls[0]
folder, child_pidl = self._GetFolderAndPIDLForPIDL(pidl)
try:
inout, ret = folder.GetUIObjectOf(hwndOwner, [child_pidl], iid,
inout, iid)
except pythoncom.com_error, (hr, desc, exc, arg):
raise COMException(hresult=hr)
return inout, ret
# return object of IID
def __init__(self, description = None, scode = None,
source = None, helpfile = None, helpContext = None,
desc = None, hresult = None):
"""Initialize an exception
**Params**
description -- A string description for the exception.
scode -- An integer scode to be returned to the server, if necessary.
The pythoncom framework defaults this to be DISP_E_EXCEPTION if not specified otherwise.
source -- A string which identifies the source of the error.
helpfile -- A string which points to a help file which contains details on the error.
helpContext -- An integer context in the help file.
desc -- A short-cut for description.
hresult -- A short-cut for scode.
"""
# convert a WIN32 error into an HRESULT
scode = scode or hresult
if scode and scode != 1: # We dont want S_FALSE mapped!
if scode >= -32768 and scode < 32768:
# this is HRESULT_FROM_WIN32()
scode = -2147024896 | (scode & 0x0000FFFF)
self.scode = scode
self.description = description or desc
if scode==1 and not self.description:
self.description = "S_FALSE"
elif scode and not self.description:
self.description = pythoncom.GetScodeString(scode)
self.source = source
self.helpfile = helpfile
self.helpcontext = helpContext
# todo - fill in the exception value
pythoncom.com_error.__init__(self, scode, self.description, None, -1)
def IsCOMException(t = None):
if t is None:
t = sys.exc_info()[0]
try:
return issubclass(t, pythoncom.com_error)
except TypeError: # 1.5 in -X mode?
return t is pythoncon.com_error