def _transform_args_(self, args, kwArgs, dispid, lcid, wFlags, serviceProvider):
ret = []
for arg in args:
arg_type = type(arg)
if arg_type == IDispatchType:
import win32com.client
arg = win32com.client.Dispatch(arg)
elif arg_type == IUnknownType:
try:
import win32com.client
arg = win32com.client.Dispatch(arg.QueryInterface(pythoncom.IID_IDispatch))
except pythoncom.error:
pass # Keep it as IUnknown
ret.append(arg)
return tuple(ret), kwArgs
python类error()的实例源码
def _get_string(path, base=win32con.HKEY_CLASSES_ROOT):
"Get a string value from the registry."
try:
return win32api.RegQueryValue(base, path)
except win32api.error:
return None
def _remove_key(path, base=win32con.HKEY_CLASSES_ROOT):
"Remove a string from the registry."
try:
win32api.RegDeleteKey(base, path)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_FILE_NOT_FOUND:
raise win32api.error(code, fn, msg)
def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT):
"""Recursively delete registry keys.
This is needed since you can't blast a key when subkeys exist.
"""
try:
h = win32api.RegOpenKey(base, path)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_FILE_NOT_FOUND:
raise win32api.error(code, fn, msg)
else:
# parent key found and opened successfully. do some work, making sure
# to always close the thing (error or no).
try:
# remove all of the subkeys
while 1:
try:
subkeyname = win32api.RegEnumKey(h, 0)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_NO_MORE_ITEMS:
raise win32api.error(code, fn, msg)
break
recurse_delete_key(path + '\\' + subkeyname, base)
# remove the parent key
_remove_key(path, base)
finally:
win32api.RegCloseKey(h)
def _find_localserver_exe(mustfind):
if not sys.platform.startswith("win32"):
return sys.executable
if pythoncom.__file__.find("_d") < 0:
exeBaseName = "pythonw.exe"
else:
exeBaseName = "pythonw_d.exe"
# First see if in the same directory as this .EXE
exeName = os.path.join( os.path.split(sys.executable)[0], exeBaseName )
if not os.path.exists(exeName):
# See if in our sys.prefix directory
exeName = os.path.join( sys.prefix, exeBaseName )
if not os.path.exists(exeName):
# See if in our sys.prefix/pcbuild directory (for developers)
if "64 bit" in sys.version:
exeName = os.path.join( sys.prefix, "PCbuild", "amd64", exeBaseName )
else:
exeName = os.path.join( sys.prefix, "PCbuild", exeBaseName )
if not os.path.exists(exeName):
# See if the registry has some info.
try:
key = "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % sys.winver
path = win32api.RegQueryValue( win32con.HKEY_LOCAL_MACHINE, key )
exeName = os.path.join( path, exeBaseName )
except (AttributeError,win32api.error):
pass
if not os.path.exists(exeName):
if mustfind:
raise RuntimeError("Can not locate the program '%s'" % exeBaseName)
return None
return exeName
def __del__(self):
try:
self.Disconnect()
except pythoncom.error:
# Ignore disconnection as we are torn down.
pass
def WriteEnumerationItems(self, stream):
num = 0
enumName = self.doc[0]
# Write in name alpha order
names = list(self.mapVars.keys())
names.sort()
for name in names:
entry = self.mapVars[name]
vdesc = entry.desc
if vdesc[4] == pythoncom.VAR_CONST:
val = vdesc[1]
use = repr(val)
# Make sure the repr of the value is valid python syntax
# still could cause an error on import if it contains a module or type name
# not available in the global namespace
try:
compile(use, '<makepy>', 'eval')
except SyntaxError:
# At least add the repr as a string, so it can be investigated further
# Sanitize it, in case the repr contains its own quotes. (??? line breaks too ???)
use = use.replace('"',"'")
use = '"' + use + '"' + ' # This VARIANT type cannot be converted automatically'
print >> stream, "\t%-30s=%-10s # from enum %s" % \
(build.MakePublicAttributeName(name, True), use, enumName)
num += 1
return num
def GetDefaultProfileName():
import win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles")
try:
return win32api.RegQueryValueEx(key, "DefaultProfile")[0]
finally:
key.Close()
except win32api.error:
return None
#
# Recursive dump of folders.
#
def testLogger():
assert not hasattr(win32com, "logger")
handler = TestLogHandler()
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
log = logging.getLogger("win32com_test")
log.addHandler(handler)
win32com.logger = log
# Now throw some exceptions!
# Native interfaces
com_server = wrap(TestServer(), pythoncom.IID_IStream)
try:
com_server.Commit(0)
raise RuntimeError("should have failed")
except pythoncom.error:
pass
assert handler.num_emits == 1, handler.num_emits
handler.num_emits = 0 # reset
com_server = Dispatch(wrap(TestServer()))
try:
com_server.Commit(0)
raise RuntimeError("should have failed")
except pythoncom.error:
pass
assert handler.num_emits == 1, handler.num_emits
def UnregisterTypelib():
k = CRDKitXL
try:
pythoncom.UnRegisterTypeLib(k._typelib_guid_,
k._typelib_version_[0],
k._typelib_version_[1],
0,
pythoncom.SYS_WIN32)
print("Unregistered typelib.")
except pythoncom.error as details:
if details[0]==winerror.TYPE_E_REGISTRYACCESS:
pass
else:
raise
def GetSpaceUsed(self, callback):
total = [0] # See _WalkCallback above
try:
for d in self._GetDirectories():
os.path.walk(d, self._WalkCallback, (callback, total))
print "After looking in", d, "we have", total[0], "bytes"
except pythoncom.error, (hr, msg, exc, arg):
# This will be raised by the callback when the user selects 'cancel'.
if hr != winerror.E_ABORT:
raise # that's the documented error code!
print "User cancelled the operation"
return total[0]
def Purge(self, amt_to_free, callback):
print "Purging", amt_to_free, "bytes..."
# we ignore amt_to_free - it is generally what we returned for
# GetSpaceUsed
try:
for d in self._GetDirectories():
os.path.walk(d, self._WalkCallback, (callback, None))
except pythoncom.error, (hr, msg, exc, arg):
# This will be raised by the callback when the user selects 'cancel'.
if hr != winerror.E_ABORT:
raise # that's the documented error code!
print "User cancelled the operation"
def CreateInstance(clsid, reqIID):
"""Create a new instance of the specified IID
The COM framework **always** calls this function to create a new
instance for the specified CLSID. This function looks up the
registry for the name of a policy, creates the policy, and asks the
policy to create the specified object by calling the _CreateInstance_ method.
Exactly how the policy creates the instance is up to the policy. See the
specific policy documentation for more details.
"""
# First see is sys.path should have something on it.
try:
addnPaths = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
regAddnPath % clsid).split(';')
for newPath in addnPaths:
if newPath not in sys.path:
sys.path.insert(0, newPath)
except win32api.error:
pass
try:
policy = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
regPolicy % clsid)
policy = resolve_func(policy)
except win32api.error:
policy = DefaultPolicy
try:
dispatcher = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
regDispatcher % clsid)
if dispatcher: dispatcher = resolve_func(dispatcher)
except win32api.error:
dispatcher = None
if dispatcher:
retObj = dispatcher(policy, None)
else:
retObj = policy(None)
return retObj._CreateInstance_(clsid, reqIID)
def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
"""A stub for _invokeex_ - should never be called.
Simply raises an exception.
"""
# Base classes should override this method (and not call the base)
raise error("This class does not provide _invokeex_ semantics")
def _transform_args_(self, args, kwArgs, dispid, lcid, wFlags, serviceProvider):
ret = []
for arg in args:
arg_type = type(arg)
if arg_type == IDispatchType:
import win32com.client
arg = win32com.client.Dispatch(arg)
elif arg_type == IUnknownType:
try:
import win32com.client
arg = win32com.client.Dispatch(arg.QueryInterface(pythoncom.IID_IDispatch))
except pythoncom.error:
pass # Keep it as IUnknown
ret.append(arg)
return tuple(ret), kwArgs
def _wrap_(self, object):
BasicWrapPolicy._wrap_(self, object)
if not hasattr(self._obj_, '_dynamic_'):
raise error("Object does not support Dynamic COM Policy")
self._next_dynamic_ = self._min_dynamic_ = 1000
self._dyn_dispid_to_name_ = {DISPID_VALUE:'_value_', DISPID_NEWENUM:'_NewEnum' }