def RegisterPythonServer(filename, progids=None, verbose=0): if progids: if isinstance(progids, str): progids = [progids] # we know the CLSIDs we need, but we might not be an admin user # and otherwise unable to register them. So as long as the progids # exist and the DLL points at our version, assume it already is. why_not = None for progid in progids: try: clsid = pythoncom.MakeIID(progid) except pythoncom.com_error: # no progid - not registered. break # have a CLSID - open it. try: HKCR = winreg.HKEY_CLASSES_ROOT hk = winreg.OpenKey(HKCR, "CLSID\\%s" % clsid) dll = winreg.QueryValue(hk, "InprocServer32") except WindowsError: # no CLSID or InProcServer32 - not good! break ok_files = [os.path.basename(pythoncom.__file__), 'pythoncomloader%d%d.dll' % (sys.version_info[0], sys.version_info[1])] if os.path.basename(dll) not in ok_files: why_not = "%r is registered against a different Python version (%s)" % (progid, dll) break else: #print "Skipping registration of '%s' - already registered" % filename return # needs registration - see if its likely! try: from win32com.shell.shell import IsUserAnAdmin except ImportError: print("Can't import win32com.shell - no idea if you are an admin or not?") is_admin = False else: try: is_admin = IsUserAnAdmin() except pythoncom.com_error: # old, less-secure OS - assume *is* admin. is_admin = True if not is_admin: msg = "%r isn't registered, but I'm not an administrator who can register it." % progids[0] if why_not: msg += "\n(registration check failed as %s)" % why_not # throw a normal "class not registered" exception - we don't report # them the same way as "real" errors. raise pythoncom.com_error(winerror.CO_E_CLASSSTRING, msg, None, -1) # so theoretically we are able to register it. cmd = '%s "%s" --unattended > nul 2>&1' % (win32api.GetModuleFileName(0), filename) if verbose: print("Registering engine", filename) # print cmd rc = os.system(cmd) if rc: print("Registration command was:") print(cmd) raise RuntimeError("Registration of engine '%s' failed" % filename)
def __init__(self, myobject, name=None): if type(myobject) == type(''): myobject = pythoncom.MakeIID(myobject) if name is None: try: name = pythoncom.ProgIDFromCLSID(myobject) except pythoncom.com_error: name = str(myobject) name = "IID: " + name HLICOM.__init__(self, myobject, name)
def testComplex(self): clsid = pythoncom.MakeIID("{CD637886-DB8B-4b04-98B5-25731E1495BE}") ctime, atime, wtime = self._getTestTimes() d = dict(cFileName="foo.txt", clsid=clsid, sizel=(1, 2), pointl=(3, 4), dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL, ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, nFileSize=sys_maxsize + 1) self._testRT(d)
def testComplex(self): if sys.hexversion < 0x2030000: # no kw-args to dict in 2.2 - not worth converting! return clsid = pythoncom.MakeIID("{CD637886-DB8B-4b04-98B5-25731E1495BE}") d = dict(cFileName="foo.txt", clsid=clsid, sizel=(1, 2), pointl=(3, 4), dwFileAttributes=win32con.FILE_ATTRIBUTE_NORMAL, ftCreationTime=pythoncom.MakeTime(10), ftLastAccessTime=pythoncom.MakeTime(11), ftLastWriteTime=pythoncom.MakeTime(12), nFileSize=sys.maxint + 1) self._testRT(d)
def get_issue_plugins(): cm = pythoncom.CoCreateInstance(pythoncom.CLSID_StdComponentCategoriesMgr, None, pythoncom.CLSCTX_INPROC, pythoncom.IID_ICatInformation) CATID_BugTraqProvider = pythoncom.MakeIID( "{3494FA92-B139-4730-9591-01135D5E7831}") ret = [] enumerator = cm.EnumClassesOfCategories((CATID_BugTraqProvider, ), ()) while 1: try: clsid = enumerator.Next() if clsid == (): break except pythoncom.com_error: break ret.extend(clsid) return ret
def _wrap_(self, object): """Wraps up the specified object. This function keeps a reference to the passed object, and may interogate it to determine how to respond to COM requests, etc. """ # We "clobber" certain of our own methods with ones # provided by the wrapped object, iff they exist. self._name_to_dispid_ = {} ob = self._obj_ = object if hasattr(ob, '_query_interface_'): self._query_interface_ = ob._query_interface_ if hasattr(ob, '_invoke_'): self._invoke_ = ob._invoke_ if hasattr(ob, '_invokeex_'): self._invokeex_ = ob._invokeex_ if hasattr(ob, '_getidsofnames_'): self._getidsofnames_ = ob._getidsofnames_ if hasattr(ob, '_getdispid_'): self._getdispid_ = ob._getdispid_ # Allow for override of certain special attributes. if hasattr(ob, '_com_interfaces_'): self._com_interfaces_ = [] # Allow interfaces to be specified by name. for i in ob._com_interfaces_: if type(i) != pywintypes.IIDType: # Prolly a string! if i[0] != "{": i = pythoncom.InterfaceNames[i] else: i = pythoncom.MakeIID(i) self._com_interfaces_.append(i) else: self._com_interfaces_ = []
# Test dynamic policy, and running object table. import pythoncom import winerror from win32com.server.exception import Exception error = "testDynamic error" iid = pythoncom.MakeIID("{b48969a0-784b-11d0-ae71-d23f56000000}") class VeryPermissive: def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_METHOD: return getattr(self, name)(*args) if wFlags & pythoncom.DISPATCH_PROPERTYGET: try: # to avoid problems with byref param handling, tuple results are converted to lists. ret = self.__dict__[name] if type(ret) == type(()): ret = list(ret) return ret except KeyError: # Probably a method request. raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) if wFlags & (pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF): setattr(self, name, args[0]) return
def echo(self, *args): self.last = ''.join(map(str, args)) if self.verbose: for arg in args: print(arg, end=' ') print() # self._connect_server_.Broadcast(last) #### Connections currently wont work, as there is no way for the engine to #### know what events we support. We need typeinfo support. IID_ITestEvents = pythoncom.MakeIID("{8EB72F90-0D44-11d1-9C4B-00AA00125A98}") class TestConnectServer(connect.ConnectableServer): _connect_interfaces_ = [IID_ITestEvents] # The single public method that the client can call on us # (ie, as a normal COM server, this exposes just this single method. def __init__(self, object): self.object = object def Broadcast(self, arg): # Simply broadcast a notification. self._BroadcastNotify(self.NotifyDoneIt, (arg,)) def NotifyDoneIt(self, interface, arg):
def _query_interface_(self, iid): """ Return this main interface if the IController class is queried. """ IID_IController = pythoncom.MakeIID( '{CE9ECC7C-960F-407E-B27B-62E39AB1E30F}') if iid == IID_IController: return win32com.server.util.wrap(self)
class IGames: _public_methods_ = [] _public_attrs_ = [ 'Settings'] def Settings(self): settings = ISettings() Settings = wrap( settings ) return Settings def SetSettings(self): settings = ISettings() Settings = wrap( settings ) return Settings IID_IController = pythoncom.MakeIID('{CE9ECC7C-960F-407E-B27B-62E39AB1E30F}') class Controller: """Main Visual Pinball COM interface class.""" _public_methods_ = [ 'Run', 'Stop', 'PrintGlobal'] _reg_progid_ = "VPinMAME.Controller" _reg_clsid_ = "{F389C8B7-144F-4C63-A2E3-246D168F9D39}" _public_attrs_ = [ 'Version', 'GameName', 'Games', 'SplashInfoLine', 'ShowTitle', 'ShowFrame', 'ShowDMDOnly',
This example shows how to solve this problem using the 'Running Object Table'. References: https://msdn.microsoft.com/en-us/library/windows/desktop/ms695276%28v=vs.85%29.aspx https://msdn.microsoft.com/en-us/library/windows/desktop/ms684004(v=vs.85).aspx """ from pyxll import xl_func, get_active_object from multiprocessing import Process import win32com.client import pythoncom import logging import time import os IID_Workbook = pythoncom.MakeIID("{000208DA-0000-0000-C000-000000000046}") def get_xl_app(parent=None): """ Return an Excel Application instance. Unlike using win32com.client.Dispatch("Excel.Application") the Application returned will always be the one that corresponds to the parent process. """ # Get the window handle set by the parent process parent_hwnd = os.environ["PYXLL_EXCEL_HWND"] # Iterate over the running object table looking for the Excel Workbook # object from the parent process' Application object.
#!/usr/bin/env python # -*- coding: utf-8 -*- import win32com.client from win32com.server.util import wrap, unwrap from win32com.server.dispatcher import DefaultDebugDispatcher from ctypes import * import commands import pythoncom import winerror from win32com.server.exception import Exception clsid = "{55C2F76F-5136-4614-A397-12214CC011E5}" iid = pythoncom.MakeIID(clsid) appid = "python.server" class VeryPermissive: def __init__(self): self.data = [] self.handle = 0 self.dobjects = {} def __del__(self): pythoncom.RevokeActiveObject(self.handle) def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_METHOD: return getattr(self, name)(*args) if wFlags & pythoncom.DISPATCH_PROPERTYGET: try: # to avoid problems with byref param handling, tuple results are converted to lists.
# Implements _both_ a connectable client, and a connectable server. # # Note that we cheat just a little - the Server in this demo is not created # via Normal COM - this means we can avoid registering the server. # However, the server _is_ accessed as a COM object - just the creation # is cheated on - so this is still working as a fully-fledged server. import pythoncom import win32com.server.util import win32com.server.connect from win32com.server.exception import Exception from pywin32_testutil import str2bytes # This is the IID of the Events interface both Client and Server support. IID_IConnectDemoEvents = pythoncom.MakeIID("{A4988850-49C3-11d0-AE5D-52342E000000}") # The server which implements # Create a connectable class, that has a single public method # 'DoIt', which echos to a single sink 'DoneIt' class ConnectableServer(win32com.server.connect.ConnectableServer): _public_methods_ = ["DoIt"] + win32com.server.connect.ConnectableServer._public_methods_ _connect_interfaces_ = [IID_IConnectDemoEvents] # The single public method that the client can call on us # (ie, as a normal COM server, this exposes just this single method. def DoIt(self,arg): # Simply broadcast a notification. self._BroadcastNotify(self.NotifyDoneIt, (arg,)) def NotifyDoneIt(self, interface, arg): interface.Invoke(1000, 0, pythoncom.DISPATCH_METHOD, 1, arg)
def __init__(self): self.handle = 0 self.clsID = pythoncom.CreateGuid() self.IID = pythoncom.MakeIID(self.clsID) self.appID = "pyprogAC" self.AHKAppID = "ahkprogAC"