我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用pythoncom.error()。
def _find_localserver_module(): import win32com.server path = win32com.server.__path__[0] baseName = "localserver" pyfile = os.path.join(path, baseName + ".py") try: os.stat(pyfile) except os.error: # See if we have a compiled extension if __debug__: ext = ".pyc" else: ext = ".pyo" pyfile = os.path.join(path, baseName + ext) try: os.stat(pyfile) except os.error: raise RuntimeError("Can not locate the Python module 'win32com.server.%s'" % baseName) return pyfile
def open_writer(self, filename, encoding="mbcs"): # A place to put code to open a file with the appropriate encoding. # Does *not* set self.file - just opens and returns a file. # Actually *deletes* the filename asked for and returns a handle to a # temp file - finish_writer then puts everything back in place. This # is so errors don't leave a 1/2 generated file around causing bizarre # errors later. # Could be a classmethod one day... try: os.unlink(filename) except os.error: pass filename = filename + ".temp" if sys.version_info > (3,0): ret = open(filename, "wt", encoding=encoding) else: import codecs # not available in py3k. ret = codecs.open(filename, "w", encoding) return ret
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 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 rdkit_descriptor(self, smiles, descriptor=u'MolLogP'): try: self.rdkit_info_num_calls = self.rdkit_info_num_calls + 1 # win32api.OutputDebugString(str(type(smiles)) + " " + str(type(descriptor))) smiles = dispatch_to_str(smiles) descriptor = dispatch_to_str(descriptor) myfunction = getattr(Descriptors, descriptor) mol = Chem.MolFromSmiles(smiles) if mol != None: return myfunction(mol) else: # OK, so you are wondering how on Earth a function that is marked up # as out:float can return a string ?! Me too, but it works :-), and # makes it possible to show a decent error to the end user. # Apparently COM returns the value as a variant regardless of the # specified IDL retval type (?)... return 'ERROR: Cannot parse SMILES input.' except Exception as e: return "ERROR: " + str(e) # Generates a molfile with 2D coordinates from SMILES input. Useful for depiction. #RDKITXL: in:smiles:str, out:str
def UseCommandLine(*classes, **flags): unregisterInfo = '--unregister_info' in sys.argv unregister = '--unregister' in sys.argv flags['quiet'] = flags.get('quiet',0) or '--quiet' in sys.argv flags['debug'] = flags.get('debug',0) or '--debug' in sys.argv flags['unattended'] = flags.get('unattended',0) or '--unattended' in sys.argv if unregisterInfo: return UnregisterInfoClasses(*classes, **flags) try: if unregister: UnregisterClasses(*classes, **flags) else: RegisterClasses(*classes, **flags) except win32api.error, exc: # If we are on xp+ and have "access denied", retry using # ShellExecuteEx with 'runas' verb to force elevation (vista) and/or # admin login dialog (vista/xp) if flags['unattended'] or exc.winerror != winerror.ERROR_ACCESS_DENIED \ or sys.getwindowsversion()[0] < 5: raise ReExecuteElevated(flags)
def UseCommandLine(*classes, **flags): unregisterInfo = '--unregister_info' in sys.argv unregister = '--unregister' in sys.argv flags['quiet'] = flags.get('quiet',0) or '--quiet' in sys.argv flags['debug'] = flags.get('debug',0) or '--debug' in sys.argv flags['unattended'] = flags.get('unattended',0) or '--unattended' in sys.argv if unregisterInfo: return UnregisterInfoClasses(*classes, **flags) try: if unregister: UnregisterClasses(*classes, **flags) else: RegisterClasses(*classes, **flags) except win32api.error as exc: # If we are on xp+ and have "access denied", retry using # ShellExecuteEx with 'runas' verb to force elevation (vista) and/or # admin login dialog (vista/xp) if flags['unattended'] or exc.winerror != winerror.ERROR_ACCESS_DENIED \ or sys.getwindowsversion()[0] < 5: raise ReExecuteElevated(flags)
def test(): import win32com.client oldcwd = os.getcwd() try: session = gencache.EnsureDispatch("MAPI.Session") try: session.Logon(GetDefaultProfileName()) except pythoncom.com_error as 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 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 _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 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 _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' }