From terabaap@yumpee.org Wed May 1 04:32:21 2002 From: terabaap@yumpee.org (Manoj Plakal) Date: Tue, 30 Apr 2002 22:32:21 -0500 Subject: [python-win32] Re: [wxPython] any hope for a wxWindows COM server? References: Message-ID: <3CCF61C5.4040307@yumpee.org> I had started work on a small cross-platform library for inter-app communication, wrapping existing platform-specific facilities like COM, AppleEvents, DCOP, ORBit. The Win32 COM version includes a sample where a wxPython app acts as a COM server. There's also a client that connects to the running COM server See qasid.sourceforge.net and browse around in the CVS repository. Manoj Dave Primmer wrote: > Has anybody got sample code of a working wxWindows COM server? I'm > actually using PythonCard but if I could see how it was done in > wxWindows that might help. I also have some basic questions about how to > connect with a client. The client would want to attach to a running copy > of the COM server the same way you can use the copy of Word that's > running if it's already started. > > I've got the COM server and client samples from win32all working so I > know how to do the Non-GUI stuff. > > Here's an attempt to wxPython a simple example. This is the text sample > from the wxWiki tutorial with added basic COM server stuff: > > ######################################### > #comserver.py > > from wxPython.wx import * > > class MainWindow(wxFrame): > _reg_clsid_ = "{0D583BF3-1106-4CEF-A540-7D3D9AC336A8}" > _reg_desc_ = "Python Test COM Server" > _reg_progid_ = "wxPython.COMserver" > _public_methods_ = ['Hello'] > > def __init__(self,parent,id,title): > wxFrame.__init__(self,parent,-4, title, size = ( 200,100), > style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) > self.control = wxTextCtrl(self, 1, style=wxTE_MULTILINE) > self.control.WriteText("hello ") > self.Show(true) > > def Hello(self, who): > self.control.WriteText("Hello " + who) > > if __name__=='__main__': > import win32com.server.register > win32com.server.register.UseCommandLine(MainWindow) > > app = wxPySimpleApp() > frame = MainWindow(None, -1, "Small editor") > frame.Show(1) > app.MainLoop() > > ################################### > #and comclient.py > > import win32com.client > w = win32com.client.Dispatch('wxPython.COMserver') > w.Hello('bob') > > > ############################ > here's the error I get when I try to run the com client > > File "C:\web\scripts\python\comclient.py", line 2, in ? > w = win32com.client.Dispatch('wxPython.COMserver') > File "C:\Python22\lib\site-packages\win32com\client\__init__.py", line > 92, in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", line > 81, in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python22\lib\site-packages\win32com\client\dynamic.py", line > 72, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > com_error: (-2147467259, 'Unspecified error', None, None) > > > > _________________________________________________________________ > MSN Photos is the easiest way to share and print your photos: > http://photos.msn.com/support/worldwide.aspx > > > _______________________________________________ > wxpython-users mailing list > wxpython-users@lists.wxwindows.org > http://lists.wxwindows.org/mailman/listinfo/wxpython-users > > From natesain@yahoo.com Wed May 1 22:56:43 2002 From: natesain@yahoo.com (Nathan Sain) Date: Wed, 1 May 2002 14:56:43 -0700 (PDT) Subject: [python-win32] User admin with ADSI / LDAP and python Message-ID: <20020501215643.26776.qmail@web20402.mail.yahoo.com> I've been working on creating a simple script to manage users in different parts of a directory on a Win2000 AD server. From looking around the following code seems to be correct, but always results in an error. If anyone that has any experience working with AD via ADSI and python would please review the following code and make suggestions I would appreciate it! the code is as follows: import win32com.client import sys def getDSO(dirPath,dirUser,password): adsi = win32com.client.Dispatch('ADsNameSpaces') ldap = adsi.getobject('','LDAP:') DSO = ldap.OpenDSObject(dirPath,dirUser,password,0) print DSO.ADsPath return DSO def makeUser(DSO,fullName,logonName,**kwargs): newUser = DSO.create("User","cn=%s" % fullName) print newUser.Class print newUser.ADsPath newUser.put("samccountname",logonName) newUser.put("displayname",fullName) newUser.Put("useraccountcontrol",1) newUser.SetInfo() return 1 if __name__ == '__main__': logon_name = 'cn=Administrator,cn=Users,dc=school,dc=us' password = 'password' student_ou = 'LDAP://server/ou=Students,dc=school,dc=us' DSO = getDSO(student_ou,logon_name,password) print makeUser(DSO,'Joe User','juser') results in the error: File "C:\usertools\setupUser.py", line 28, in makeUser newUser.SetInfo() File ">", line 2, in SetInfo com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147016694), None) __________________________________________________ Do You Yahoo!? Yahoo! Health - your guide to health and wellness http://health.yahoo.com From jens.jorgensen@tallan.com Thu May 2 18:30:56 2002 From: jens.jorgensen@tallan.com (Jens B. Jorgensen) Date: Thu, 02 May 2002 12:30:56 -0500 Subject: [python-win32] User admin with ADSI / LDAP and python References: <20020501215643.26776.qmail@web20402.mail.yahoo.com> Message-ID: <3CD177D0.4060401@tallan.com> I've used the LDAP namespace of ADSI but not for hitting an actual Active Directory, but rather against an exchange server and for manipulating local users. I'm going to be though that if the below is actual code then your problem is that newUser.put("samccountname",logonName) should be: newUser.put("samaccountname",logonName) Nathan Sain wrote: >I've been working on creating a simple script to >manage users in different parts of a directory on a >Win2000 AD server. From looking around the following >code seems to be correct, but always results in an >error. If anyone that has any experience working with >AD via ADSI and python would please review the >following code and make suggestions I would appreciate >it! > >the code is as follows: > >import win32com.client >import sys > >def getDSO(dirPath,dirUser,password): > adsi = win32com.client.Dispatch('ADsNameSpaces') > ldap = adsi.getobject('','LDAP:') > DSO = >ldap.OpenDSObject(dirPath,dirUser,password,0) > print DSO.ADsPath > return DSO > >def makeUser(DSO,fullName,logonName,**kwargs): > newUser = DSO.create("User","cn=%s" % fullName) > print newUser.Class > print newUser.ADsPath > newUser.put("samccountname",logonName) > newUser.put("displayname",fullName) > newUser.Put("useraccountcontrol",1) > newUser.SetInfo() > return 1 > >if __name__ == '__main__': > logon_name = >'cn=Administrator,cn=Users,dc=school,dc=us' > password = 'password' > student_ou = >'LDAP://server/ou=Students,dc=school,dc=us' > DSO = getDSO(student_ou,logon_name,password) > print makeUser(DSO,'Joe User','juser') > >results in the error: > > File "C:\usertools\setupUser.py", line 28, in >makeUser > newUser.SetInfo() > File ">", line 2, in SetInfo >com_error: (-2147352567, 'Exception occurred.', (0, >None, None, None, 0, -2147016694), None) > >__________________________________________________ >Do You Yahoo!? >Yahoo! Health - your guide to health and wellness >http://health.yahoo.com > > >_______________________________________________ >Python-win32 mailing list >Python-win32@python.org >http://mail.python.org/mailman/listinfo/python-win32 > > > -- Jens B. Jorgensen jens.jorgensen@tallan.com From andrew-pywin32@puzzling.org Mon May 6 06:43:58 2002 From: andrew-pywin32@puzzling.org (Andrew Bennetts) Date: Mon, 6 May 2002 15:43:58 +1000 Subject: [python-win32] default_interface missing Message-ID: <20020506054358.GA6546@ritsuko.xware.cx> Hi, I'm getting the following error trying to instantiate a COM object: --- Traceback (most recent call last): File "", line 1, in ? mod.WLXMLWriter() File "C:\Python22\lib\site-packages\win32com\gen_py\2F7F6580-4166-4728-B165-361888BBAF93x0x1x0.py", line 26, in __init__ self.__dict__["_dispobj_"] = self.default_interface(oobj) File "C:\Python22\lib\site-packages\win32com\gen_py\2F7F6580-4166-4728-B165-361888BBAF93x0x1x0.py", line 32, in __getattr__ d=self.__dict__["_dispobj_"] KeyError: _dispobj_ --- The problem seems to be that default_interface isn't defined in the module generated by makepy, causing a dud call to CoClassBaseClass.__getattr__ to find it: --- # This CoClass is known by the name 'WLXML.WLXMLWriter.1' class WLXMLWriter(CoClassBaseClass): # A CoClass # WLXMLWriter Class CLSID = pythoncom.MakeIID("{5625CFA5-A60F-408D-A26D-19D39A58B38D}") coclass_sources = [ ] coclass_interfaces = [ ] ### default_interface = XXX should go here? --- Is this a bug in win32com or in the COM object? -Andrew. From Juhani.Mantila@novogroup.com Mon May 6 07:40:44 2002 From: Juhani.Mantila@novogroup.com (Mantila Juhani) Date: Mon, 6 May 2002 09:40:44 +0300 Subject: [python-win32] default_interface missing Message-ID: Got it the same way. I've got a huge type library from ESRI and most of the interface classes are not wrapped by makepy, so most of the coclasses look similar, no interfaces at all. In VB and MS VC++ everything is visible and usable... Some more information, yet. The library is imported into C++ like this : #ifndef _IMPORTED_ #define _IMPORTED_ #pragma warning(push) #pragma warning(disable : 4146) #pragma warning(disable : 4192) #import "d:\esri\arcexe81\bin\esriCore.olb" raw_interfaces_only, raw_native_types, no_namespace, named_guids, exclude("OLE_HANDLE", "OLE_COLOR") #pragma warning(pop) #endif The final question is the same as Andrew's. Juhani > -----Original Message----- > From: Andrew Bennetts [mailto:andrew-pywin32@puzzling.org] > Sent: Monday, May 06, 2002 8:44 AM > To: python-win32@python.org > Subject: [python-win32] default_interface missing > > > Hi, > > I'm getting the following error trying to instantiate a COM object: > > --- > Traceback (most recent call last): > File "", line 1, in ? > mod.WLXMLWriter() > File > "C:\Python22\lib\site-packages\win32com\gen_py\2F7F6580-4166-4 > 728-B165-361888BBAF93x0x1x0.py", line 26, in __init__ > self.__dict__["_dispobj_"] = self.default_interface(oobj) > File > "C:\Python22\lib\site-packages\win32com\gen_py\2F7F6580-4166-4 > 728-B165-361888BBAF93x0x1x0.py", line 32, in __getattr__ > d=self.__dict__["_dispobj_"] > KeyError: _dispobj_ > --- > > The problem seems to be that default_interface isn't defined in the > module generated by makepy, causing a dud call to > CoClassBaseClass.__getattr__ to find it: > > --- > # This CoClass is known by the name 'WLXML.WLXMLWriter.1' > class WLXMLWriter(CoClassBaseClass): # A CoClass > # WLXMLWriter Class > CLSID = > pythoncom.MakeIID("{5625CFA5-A60F-408D-A26D-19D39A58B38D}") > coclass_sources = [ > ] > coclass_interfaces = [ > ] > > ### default_interface = XXX should go here? > --- > > Is this a bug in win32com or in the COM object? > > -Andrew. > > > > _______________________________________________ > Python-win32 mailing list > Python-win32@python.org > http://mail.python.org/mailman/listinfo/python-win32 > From stefan.holmgren@accalon.se Mon May 6 11:08:23 2002 From: stefan.holmgren@accalon.se (Holmgren Stefan) Date: Mon, 6 May 2002 12:08:23 +0200 Subject: [python-win32] Add a new icon to a window? Message-ID: <143AE708B7F3D311B34500508B5D551F646547@box6.accalon.se> Hi... I dont know if I'm in the right forum ....... but here is my Q: I'm a python beginner ........... and I'm playing around with Tkinter.... But how do I add an icon to the root window? I can change title, but I want my own icon too!! Send an example, please... Thanx Stefan Holmgren From tsg.parker@aafes.com Mon May 6 17:48:46 2002 From: tsg.parker@aafes.com (Parker, Edward) Date: Mon, 6 May 2002 11:48:46 -0500 Subject: [python-win32] WSH, WMI, references? Message-ID: <59ED071EB5C1D511A76900B0D0D1CB2C01BAB4AF@hqexch07.hq.aafes.com> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C1F51D.E3D68CB0 Content-Type: text/plain All, I am new to this board and Python. I have used VBScript and WSH for a while now and can perform most administrative scripting to most of my W32 systems. I am working with cross platform scripting (with WBEM/WMI) and would like to use the same language on all platforms (W32, Linux, OS X). I am thinking Python over Perl. Is there any reference/book available that focuses on W32 administrative scripting using Python? ------_=_NextPart_001_01C1F51D.E3D68CB0 Content-Type: text/html

All,

I am new to this board and Python.  I have used VBScript and WSH for a while now and can perform most administrative scripting to most of my W32 systems.  I am working with cross platform scripting (with WBEM/WMI) and would like to use the same language on all platforms (W32, Linux, OS X).  I am thinking Python over Perl.  Is there any reference/book available that focuses on W32 administrative scripting using Python?

------_=_NextPart_001_01C1F51D.E3D68CB0-- From Jim.Vickroy@noaa.gov Mon May 6 18:44:55 2002 From: Jim.Vickroy@noaa.gov (Jim Vickroy) Date: Mon, 06 May 2002 11:44:55 -0600 Subject: [python-win32] WSH, WMI, references? References: <59ED071EB5C1D511A76900B0D0D1CB2C01BAB4AF@hqexch07.hq.aafes.com> Message-ID: <3CD6C117.92C5DF7B@noaa.gov> --------------8462E6AF56BD3C218B9CD50E Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hello Edward and welcome! The book, "Python Programming on Win32" by Mark Hammond and Andy Robinson contains the following chapters that may be relevant: - Windows NT Administration - Processes and Files - Windows NT Services - Active Scripting I highly recommend this book for Windows programmers, and Mark Hammond frequently answers questions on this forum. "Parker, Edward" wrote: > All, > > I am new to this board and Python. I have used VBScript and WSH for a > while now and can perform most administrative scripting to most of my > W32 systems. I am working with cross platform scripting (with > WBEM/WMI) and would like to use the same language on all platforms > (W32, Linux, OS X). I am thinking Python over Perl. Is there any > reference/book available that focuses on W32 administrative scripting > using Python? > --------------8462E6AF56BD3C218B9CD50E Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Hello Edward and welcome!

The book,
    "Python Programming on Win32"
by
    Mark Hammond and Andy Robinson

contains the following chapters that may be relevant:
    - Windows NT Administration
    - Processes and Files
    - Windows NT Services
    - Active Scripting

I highly recommend this book for Windows programmers, and Mark Hammond frequently answers questions on this forum.

"Parker, Edward" wrote:

All,

I am new to this board and Python.  I have used VBScript and WSH for a while now and can perform most administrative scripting to most of my W32 systems.  I am working with cross platform scripting (with WBEM/WMI) and would like to use the same language on all platforms (W32, Linux, OS X).  I am thinking Python over Perl.  Is there any reference/book available that focuses on W32 administrative scripting using Python?

--------------8462E6AF56BD3C218B9CD50E-- From mrroach@uhg.net Wed May 8 15:08:56 2002 From: mrroach@uhg.net (Roach, Mark R.) Date: 08 May 2002 09:08:56 -0500 Subject: [python-win32] OpenOffice automation Message-ID: <1020866936.8692.2.camel@tncorpmrr001.uhg> Has anyone had any luck getting OpenOffice's COM objects working? this is what I'm getting Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com >>> import win32com.client >>> objServiceManager = win32com.client.Dispatch("com.sun.star.ServiceManager") >>> objServiceManager >>> objDesktop = objServiceManager.createInstance("com.sun.star.frame.Desktop") Traceback (most recent call last): File "", line 1, in ? TypeError: 'NoneType' object is not callable Am I not translating the instructions to python properly? http://udk.openoffice.org/common/man/tutorial/office_automation.html Thanks, Mark Roach From mhammond@skippinet.com.au Thu May 9 06:26:51 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Thu, 9 May 2002 15:26:51 +1000 Subject: [python-win32] default_interface missing In-Reply-To: Message-ID: > The final question is the same as Andrew's. It is a bug in win32com - it should load all dependent type libraries, and find referenced interfaces there. If you were masochists you could try and get the same error by modifying the win32com test suite. Mark. From yee@uclink.berkeley.edu Thu May 9 07:43:16 2002 From: yee@uclink.berkeley.edu (Raymond Yee) Date: Wed, 08 May 2002 23:43:16 -0700 Subject: [python-win32] OpenOffice automation References: <20020508160012.2585.67878.Mailman@mail.python.org> Message-ID: <3CDA1A84.E87308B0@uclink.berkeley.edu> I'm not a Python expert -- but I get the same results as Mark using Python 2.2. However, I was able to get the OpenOffice COM objects working with both VB: Private Sub Form_Load() Set objServiceManager = CreateObject("com.sun.star.ServiceManager") 'Create the Desktop Set objDesktop = objServiceManager.createInstance("com.sun.star.frame.Desktop") 'Open a new empty writer document Dim args() Set objDocument = objDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args) 'Create a text object Set objText = objDocument.GetText 'Create a cursor object Set objCursor = objText.createTextCursor 'Inserting some Text objText.insertString objCursor, "The first line in the newly created text document." & vbLf, False End Sub and with Perl: # establish COM connection to Ecco use Win32::OLE; $objServiceManager = Win32::OLE->new("com.sun.star.ServiceManager", 'Quit'); $objDesktop = $objServiceManager->createInstance("com.sun.star.frame.Desktop"); @args = (); $objDocument = $objDesktop->loadComponentFromURL("private:factory/swriter", "_blank", 0, \@args); $objText = $objDocument->GetText(); $objCursor = $objText->createTextCursor(); $objText->insertString($objCursor, "The first line in the newly created text document." . "\n", 0); I believe that the syntax that Mark is using with Python is the correct one -- and the OpenOffice objects do work. Are we actually using the wrong Python syntax or is there a bug in pythoncom? -Raymond > > Message: 1 > From: "Roach, Mark R." > To: python-win32@python.org > Date: 08 May 2002 09:08:56 -0500 > Subject: [python-win32] OpenOffice automation > > Has anyone had any luck getting OpenOffice's COM objects working? > > this is what I'm getting > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import win32com > >>> import win32com.client > >>> objServiceManager = > win32com.client.Dispatch("com.sun.star.ServiceManager") > >>> objServiceManager > > >>> objDesktop = > objServiceManager.createInstance("com.sun.star.frame.Desktop") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'NoneType' object is not callable > > Am I not translating the instructions to python properly? > http://udk.openoffice.org/common/man/tutorial/office_automation.html > > Thanks, > > Mark Roach > > --__--__-- From mhammond@skippinet.com.au Thu May 9 08:54:50 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Thu, 9 May 2002 17:54:50 +1000 Subject: [python-win32] OpenOffice automation In-Reply-To: <3CDA1A84.E87308B0@uclink.berkeley.edu> Message-ID: > > >>> objDesktop = > > objServiceManager.createInstance("com.sun.star.frame.Desktop") > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: 'NoneType' object is not callable It appears that the COM object is returning "None" when a *property* called "createInstance" is requested. However, "createInstance" is a method, so an attempt to reference it as a property should fail. You could confirm this by printing "objServiceManager.createInstance" - try that in any language - you should find None/Nothing/NULL is returned instead of an error. Mark. From yee@uclink.berkeley.edu Fri May 10 06:36:35 2002 From: yee@uclink.berkeley.edu (Raymond Yee) Date: Thu, 09 May 2002 22:36:35 -0700 Subject: [python-win32] OpenOffice automation References: Message-ID: <3CDB5C63.7D6990D@uclink.berkeley.edu> Please clarify. We typed objDesktop = objServiceManager.createInstance("com.sun.star.frame.Desktop") Isn't the syntax we used calling the *method* creatInstance with the parameter "com.sun.star.frame.Desktop" of objServiceManager -- not the property? (I consulted http://aspn.activestate.com//ASPN/Python/Reference/Products/ActivePython/win32com/win32com/win32com/HTML/QuickStartClientCom.html which gives the example: import win32com.client o = win32com.client.Dispatch("Object.Name") o.Method() o.property = "New Value" print o.property to distinguish between calling a method and a property What am I missing here? -Raymond Mark Hammond wrote: > > > >>> objDesktop = > > > objServiceManager.createInstance("com.sun.star.frame.Desktop") > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > TypeError: 'NoneType' object is not callable > > It appears that the COM object is returning "None" when a *property* called > "createInstance" is requested. However, "createInstance" is a method, so an > attempt to reference it as a property should fail. > > You could confirm this by printing "objServiceManager.createInstance" - try > that in any language - you should find None/Nothing/NULL is returned instead > of an error. > > Mark. > > _______________________________________________ > Python-win32 mailing list > Python-win32@python.org > http://mail.python.org/mailman/listinfo/python-win32 From mhammond@skippinet.com.au Fri May 10 06:44:54 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Fri, 10 May 2002 15:44:54 +1000 Subject: [python-win32] OpenOffice automation In-Reply-To: <3CDB5C63.7D6990D@uclink.berkeley.edu> Message-ID: > Please clarify. We typed > > objDesktop = > objServiceManager.createInstance("com.sun.star.frame.Desktop") > > Isn't the syntax we used calling the *method* creatInstance with > the parameter > "com.sun.star.frame.Desktop" of objServiceManager -- not the property? Exactly, and this is why we have a problem ;) In Python, foo.bar() will result in: * get attribute "bar" from object "foo" * call it. In "normal" Python: object.methodName will return a function object. 'object.methodName()' gets the function object as a property, then calls it. Unfortunately, this is also the way things work for pythoncom - obj.foo() first asks the object for a property named "foo", then attempts to call it. win32com.client intercepts this, and if it sees what it believes to be a method, it returns a method object. But if the attempt to reference the object proeprty succeeded, then it assumes the property reference is valid. makepy would solve this, but I am assuming you can not run makepy over this object. If the star office framework does have a type library, then run makepy over it and it should work. Mark. From yee@uclink.berkeley.edu Fri May 10 07:52:13 2002 From: yee@uclink.berkeley.edu (Raymond Yee) Date: Thu, 09 May 2002 23:52:13 -0700 Subject: [python-win32] OpenOffice automation References: Message-ID: <3CDB6E1D.6B6C3A8B@uclink.berkeley.edu> Thanks, Mark, for walking me through this. OK -- I think I get it now. I'm in the process of looking for a type library for OpenOffice but have not succeeded yet. What if there is no available type library? Am I then out of luck in terms of using Pythoncom to access OpenOffice? I've had luck using Perl and VB to access OpenOffice. Is the reason I'm able to use those COM client implementations that through the syntax of those implementations, I'm able to clear indicate that createInstance is a *method* and not a *property*? For example, in Perl Win32::OLE, the following works:: $objDesktop = $objServiceManager->createInstance("com.sun.star.frame.Desktop"); If I wanted to access createInstance -- the *property*, I would write: $objDesktop = $objServiceManager->createInstance; Is there a way with pythoncom but having no access to any type library to say "I know it's a method and not a property, don't try to access the property -- just go for the method"? -Raymond Mark Hammond wrote: > > Please clarify. We typed > > > > objDesktop = > > objServiceManager.createInstance("com.sun.star.frame.Desktop") > > > > Isn't the syntax we used calling the *method* creatInstance with > > the parameter > > "com.sun.star.frame.Desktop" of objServiceManager -- not the property? > > Exactly, and this is why we have a problem ;) > > In Python, foo.bar() will result in: > * get attribute "bar" from object "foo" > * call it. > > In "normal" Python: > > object.methodName > > will return a function object. 'object.methodName()' gets the function > object as a property, then calls it. > > Unfortunately, this is also the way things work for pythoncom - obj.foo() > first asks the object for a property named "foo", then attempts to call it. > win32com.client intercepts this, and if it sees what it believes to be a > method, it returns a method object. But if the attempt to reference the > object proeprty succeeded, then it assumes the property reference is valid. > > makepy would solve this, but I am assuming you can not run makepy over this > object. If the star office framework does have a type library, then run > makepy over it and it should work. > > Mark. From mhammond@skippinet.com.au Fri May 10 07:59:57 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Fri, 10 May 2002 16:59:57 +1000 Subject: [python-win32] OpenOffice automation In-Reply-To: <3CDB6E1D.6B6C3A8B@uclink.berkeley.edu> Message-ID: > I've had luck using Perl and VB to access OpenOffice. Is the > reason I'm able > to use those COM client implementations that through the syntax of those > implementations, I'm able to clear indicate that createInstance > is a *method* > and not a *property*? > > For example, in Perl Win32::OLE, the following works:: > > $objDesktop = > $objServiceManager->createInstance("com.sun.star.frame.Desktop"); > > If I wanted to access createInstance -- the *property*, I would write: > > $objDesktop = $objServiceManager->createInstance; Can you check if the latter does indeed return None. If so, you should report a bug. > Is there a way with pythoncom but having no access to any type > library to say > "I know it's a method and not a property, don't try to access the > property -- > just go for the method"? Nope :( It would be pretty easy to add though, and would be generally useful (a similar issue has come up before). One way would be to add support so you could say: ob = Dispatch("...") ob._MarkAsMethod("createInstance") # hack around problems with staroffice. ob.createInstance() would then work as expected. Sound reasonable? If so, what is a better spelling of "_MarkAsMethod"? Mark. From Juhani.Mantila@novogroup.com Fri May 10 07:59:07 2002 From: Juhani.Mantila@novogroup.com (Mantila Juhani) Date: Fri, 10 May 2002 09:59:07 +0300 Subject: [python-win32] default_interface missing Message-ID: I'm not. I just wanted get the advanteges of Python over VB. Is there any hope, I've gotta use that typelib ? Should I try to experiment with those individual DLLs (many) ? Oh no... Juhani > -----Original Message----- > From: Mark Hammond [mailto:mhammond@skippinet.com.au] > Sent: Thursday, May 09, 2002 8:27 AM > To: Mantila Juhani; python-win32@python.org > Subject: RE: [python-win32] default_interface missing > > > > The final question is the same as Andrew's. > > It is a bug in win32com - it should load all dependent type > libraries, and > find referenced interfaces there. If you were masochists you > could try and > get the same error by modifying the win32com test suite. > > Mark. > From mhammond@skippinet.com.au Fri May 10 08:08:04 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Fri, 10 May 2002 17:08:04 +1000 Subject: [python-win32] default_interface missing In-Reply-To: Message-ID: > I'm not. I just wanted get the advanteges of Python over VB. > Is there any hope, I've gotta use that typelib ? > Should I try to experiment with those individual DLLs (many) ? Oh no... Try running makepy over the dependent typelibs first. Mark. From yee@uclink.berkeley.edu Fri May 10 08:20:35 2002 From: yee@uclink.berkeley.edu (Raymond Yee) Date: Fri, 10 May 2002 00:20:35 -0700 Subject: [python-win32] OpenOffice automation References: Message-ID: <3CDB74C3.EFDB0B6C@uclink.berkeley.edu> Mark Hammond wrote: > > I've had luck using Perl and VB to access OpenOffice. Is the > > reason I'm able > > to use those COM client implementations that through the syntax of those > > implementations, I'm able to clear indicate that createInstance > > is a *method* > > and not a *property*? > > > > For example, in Perl Win32::OLE, the following works:: > > > > $objDesktop = > > $objServiceManager->createInstance("com.sun.star.frame.Desktop"); > > > > If I wanted to access createInstance -- the *property*, I would write: > > > > $objDesktop = $objServiceManager->createInstance; > > Can you check if the latter does indeed return None. If so, you should > report a bug. > Yes, in Python: >>> `objServiceManager.CreateInstance` 'None' So how do I report this as a bug? > > > Is there a way with pythoncom but having no access to any type > > library to say > > "I know it's a method and not a property, don't try to access the > > property -- > > just go for the method"? > > Nope :( It would be pretty easy to add though, and would be generally > useful (a similar issue has come up before). One way would be to add > support so you could say: > > ob = Dispatch("...") > ob._MarkAsMethod("createInstance") # hack around problems with staroffice. > > ob.createInstance() would then work as expected. > > Sound reasonable? If so, what is a better spelling of "_MarkAsMethod"? > Sounds reasonable to me, if it does to you. I'm happy with being to have a workaround.... -Raymond From m_konermann@gmx.de Tue May 14 08:39:55 2002 From: m_konermann@gmx.de (Marcus) Date: Tue, 14 May 2002 09:39:55 +0200 Subject: [python-win32] getting access violation error in kernel32.dll while debugging References: <3CDFE2A4.3030500@gmx.de> <25634.1021313642@www51.gmx.net> Message-ID: <3CE0BF4B.8000001@gmx.de> Hello! I want to embbed C source code with a python script, named modulefile.py. Here´s the intresting part of my c code: void getValues(char **firstName, char **lastName, char **profession) { FILE *fp = NULL; PyObject *module, *fn, *ln, *prof; int res; module = PyImport_AddModule("__main__"); fp = fopen("modulefile.py","r"); res = PyRun_SimpleFile(fp,"modulefile.py"); } void main(int argc, char *argv[]) { char *firstName, *lastName, *profession; Py_Initialize(); PySys_SetArgv(argc, argv); getValues(&firstName, &lastName, &profession); After the debugger reaches the statemant: res = PyRun_SimpleFile(fp,"modulefile.py"); I get a access violation error in kernel32.dll. Have anyone got an idea what happend ? All the examples in the source code (D:\home\...\Python-2.2.1\Demo\embed) are working, so it does´nt seem to be a compiler configuration error. Thanks a lot, greetings Marcus From mhammond@skippinet.com.au Tue May 14 12:21:02 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Tue, 14 May 2002 21:21:02 +1000 Subject: [python-win32] getting access violation error in kernel32.dll while debugging In-Reply-To: <3CE0BF4B.8000001@gmx.de> Message-ID: You probably don't have the runtime libraries set correctly. You must use "multi-threaded in a DLL", aka the /MD compiler option (/MDd for debug builds) Mark. > -----Original Message----- > From: python-win32-admin@python.org > [mailto:python-win32-admin@python.org]On Behalf Of Marcus > Sent: Tuesday, 14 May 2002 5:40 PM > To: Python > Subject: [python-win32] getting access violation error in kernel32.dll > while debugging > > > Hello! > I want to embbed C source code with a python script, named > modulefile.py. Here´s the intresting part of my c code: > > void getValues(char **firstName, char **lastName, char **profession) { > > FILE *fp = NULL; > PyObject *module, *fn, *ln, *prof; > int res; > > module = PyImport_AddModule("__main__"); > > fp = fopen("modulefile.py","r"); > res = PyRun_SimpleFile(fp,"modulefile.py"); > } > void main(int argc, char *argv[]) { > > char *firstName, *lastName, *profession; > > Py_Initialize(); > PySys_SetArgv(argc, argv); > getValues(&firstName, &lastName, &profession); > > After the debugger reaches the statemant: > > res = PyRun_SimpleFile(fp,"modulefile.py"); > > I get a access violation error in kernel32.dll. Have anyone got an idea > what happend ? > All the examples in the source code > (D:\home\...\Python-2.2.1\Demo\embed) are working, so it does´nt seem to > be a compiler configuration error. > > Thanks a lot, greetings > Marcus > > > > > > > _______________________________________________ > Python-win32 mailing list > Python-win32@python.org > http://mail.python.org/mailman/listinfo/python-win32 From mrroach@uhg.net Tue May 14 19:33:32 2002 From: mrroach@uhg.net (Roach, Mark R.) Date: 14 May 2002 13:33:32 -0500 Subject: [python-win32] OpenOffice automation In-Reply-To: <3CDB74C3.EFDB0B6C@uclink.berkeley.edu> References: <3CDB74C3.EFDB0B6C@uclink.berkeley.edu> Message-ID: <1021401212.20012.2.camel@tncorpmrr001.uhg> On Fri, 2002-05-10 at 02:20, Raymond Yee wrote: [snip] > > So how do I report this as a bug? Hello, Raymond. Did you ever report this? If not, I will try to do so Thanks, Mark Roach From mrussell8081@pacbell.net Thu May 16 05:10:01 2002 From: mrussell8081@pacbell.net (Mark Russell) Date: Wed, 15 May 2002 21:10:01 -0700 Subject: [python-win32] Problem wtih httplib and winsock on Win2K Message-ID: Hi to all, I am working through a simple SOAP example from the IBM developer developer series. The full article is here: http://www-106.ibm.com/developerworks/webservices/library/ws-pyth6/?dwzone=w ebservices My platform is Python 2.2 on Win2K. On the client side I need to use httplib to make a request of a SOAP.py based service. Every time I run the client I get a winsock error. The client and server code is reproduced below. Running the client produces the following: Any help would be greatly appreciated. --run-- C:\home\developer\distinct>python pycal.py connect: (127.0.0.1, 8888) send: 'POST cal-server HTTP/1.0\r\n' send: 'Host: 127.0.0.1\r\n' send: 'Content-Type: text/plain; charset="utf-8"\r\n' send: 'Content-Lenget: 514\r\n' send: 'SOAPAction: http://uche.ogbuji.net/eg/ws/simple-cal\r\n' send: '\r\n' send: '\n \n \n 2001\n 12\n \n \n' reply: 'HTTP/1.0 500 Internal error\r\n' header: Server: SOAP.py 0.9.7 (Python 2.2a2+) header: Date: Wed, 15 May 2002 19:48:16 GMT Traceback (most recent call last): File "pycal.py", line 43, in ? GetMonth() File "pycal.py", line 36, in GetMonth reply_body = requestor.getfile().read() File "c:\python22\lib\socket.py", line 229, in read new = self._sock.recv(k) socket.error: (10054, 'Connection reset by peer') --server code-- import sys, calendar #Import the SOAP.py machinery from WebServices import SOAP CAL_NS = "http://uche.ogbuji.net/eg/ws/simple-cal" class Calendar: def getMonth(self, year, month): return calendar.month(year, month) def getYear(self, year): return calendar.calendar(year) server = SOAP.SOAPServer(("localhost", 8888)) cal = Calendar() server.registerObject(cal, CAL_NS) print "Starting server..." server.serve_forever() --client code-- import sys, httplib SERVER_ADDR = "127.0.0.1" SERVER_PORT = 8888 CAL_NS = "http://uche.ogbuji.net/ws/eg/simple-cal" BODY_TEMPLATE = """ %s %s """ def GetMonth(): year = 2001 month = 12 body = BODY_TEMPLATE%(year, month) blen = len(body) requestor = httplib.HTTP(SERVER_ADDR, SERVER_PORT) requestor.putrequest("POST", "cal-server") requestor.putheader("Host", SERVER_ADDR) requestor.putheader("Content-Type", "text/plain; charset="utf-8"") requestor.putheader("Content-Length", str(blen)) requestor.putheader("SOAPAction", "http://uche.ogbuji.net/eg/ws/simple-car") requestor.endheaders() requestor.send(body) (status_code, message, reply_headers) = requestor.getreply() reply_body = requestor.getfile().read() print "status code:", status_code print "status message:", message print "HTTP reply body:\n", reply_body if __name__ == "__main__": GetMonth() From mrroach@uhg.net Thu May 16 15:54:09 2002 From: mrroach@uhg.net (Roach, Mark R.) Date: 16 May 2002 09:54:09 -0500 Subject: [python-win32] OpenOffice automation In-Reply-To: <1021401212.20012.2.camel@tncorpmrr001.uhg> References: <3CDB74C3.EFDB0B6C@uclink.berkeley.edu> <1021401212.20012.2.camel@tncorpmrr001.uhg> Message-ID: <1021560849.26350.29.camel@tncorpmrr001.uhg> --=-7rU/FdBwTZXQtnUZUa7s Content-Type: text/plain Content-Transfer-Encoding: 7bit On Tue, 2002-05-14 at 13:33, Roach, Mark R. wrote: > On Fri, 2002-05-10 at 02:20, Raymond Yee wrote: > [snip] > > > > So how do I report this as a bug? > > Hello, Raymond. Did you ever report this? If not, I will try to do so Sorry to reply to my own post, Raymond asked me to summarize the solution that he and Mark Hammond worked out. As they said, flagging (what Python believes to be) a property as a method should fix it. This should resolve similar problems with other COM objects as well. Mark came up with the attached replacement for win32com\client\dynamic.py. here are his instructions """ After replacing your existing file, you should be able to say: ob = Dispatch("...") ob._FlagAsMethod("method1", "method2", ...) ob.method1() should then work correctly. """ Based on this fix, Raymond was able to run the following code, a translation of the example code at http://udk.openoffice.org/common/man/tutorial/office_automation.html import win32com.client objServiceManager = win32com.client.Dispatch("com.sun.star.ServiceManager") objServiceManager._FlagAsMethod("CreateInstance") objDesktop = objServiceManager.CreateInstance("com.sun.star.frame.Desktop") objDesktop._FlagAsMethod("loadComponentFromURL") args = [] objDocument = objDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args) objDocument._FlagAsMethod("GetText") objText = objDocument.GetText() objText._FlagAsMethod("createTextCursor","insertString") objCursor = objText.createTextCursor() objText.insertString(objCursor, "The first line in the newly created text document.\n", 0) Thanks to both of these guys -Mark Roach --=-7rU/FdBwTZXQtnUZUa7s Content-Disposition: attachment; filename=dynamic.py Content-Transfer-Encoding: quoted-printable Content-Type: text/x-python; name=dynamic.py; charset=ISO-8859-1 """Support for dynamic COM client support. Introduction Dynamic COM client support is the ability to use a COM server without prior knowledge of the server. This can be used to talk to almost all COM servers, including much of MS Office. =20 In general, you should not use this module directly - see below. =20 Example >>> import win32com.client >>> xl =3D win32com.client.Dispatch("Excel.Application") # The line above invokes the functionality of this class. # xl is now an object we can use to talk to Excel. >>> xl.Visible =3D 1 # The Excel window becomes visible. """ import traceback import string import new import pythoncom import winerror import build from types import StringType, IntType, TupleType, ListType from pywintypes import UnicodeType, IIDType import win32com.client # Needed as code we eval() references it. from win32com.client import NeedUnicodeConversions debugging=3D0 # General debugging debugging_attr=3D0 # Debugging dynamic attribute lookups. LCID =3D 0x0 # These errors generally mean the property or method exists, # but can't be used in this context - eg, property instead of a method, etc= . # Used to determine if we have a real error or not. ERRORS_BAD_CONTEXT =3D [ winerror.DISP_E_MEMBERNOTFOUND, winerror.DISP_E_BADPARAMCOUNT, winerror.DISP_E_PARAMNOTOPTIONAL, winerror.DISP_E_TYPEMISMATCH, winerror.E_INVALIDARG, ] def debug_print(*args): if debugging: for arg in args: print arg, print def debug_attr_print(*args): if debugging_attr: for arg in args: print arg, print # get the dispatch type in use. dispatchType =3D pythoncom.TypeIIDs[pythoncom.IID_IDispatch] iunkType =3D pythoncom.TypeIIDs[pythoncom.IID_IUnknown] _StringOrUnicodeType=3D[StringType, UnicodeType] _GoodDispatchType=3D[StringType,IIDType,UnicodeType] _defaultDispatchItem=3Dbuild.DispatchItem def _GetGoodDispatch(IDispatch, clsctx =3D pythoncom.CLSCTX_SERVER): if type(IDispatch) in _GoodDispatchType: try: IDispatch =3D pythoncom.connect(IDispatch) except pythoncom.ole_error: IDispatch =3D pythoncom.CoCreateInstance(IDispatch, None, clsctx, python= com.IID_IDispatch) return IDispatch def _GetGoodDispatchAndUserName(IDispatch,userName,clsctx): if userName is None: if type(IDispatch) in _StringOrUnicodeType: userName =3D IDispatch else: userName =3D "" return (_GetGoodDispatch(IDispatch, clsctx), userName) def Dispatch(IDispatch, userName =3D None, createClass =3D None, typeinfo = =3D None, UnicodeToString=3DNeedUnicodeConversions, clsctx =3D pythoncom.CL= SCTX_SERVER): IDispatch, userName =3D _GetGoodDispatchAndUserName(IDispatch,userName,cls= ctx) if createClass is None: createClass =3D CDispatch lazydata =3D None try: if typeinfo is None: typeinfo =3D IDispatch.GetTypeInfo() try: #try for a typecomp typecomp =3D typeinfo.GetTypeComp() lazydata =3D typeinfo, typecomp except pythoncom.com_error: pass except pythoncom.com_error: typeinfo =3D None olerepr =3D MakeOleRepr(IDispatch, typeinfo, lazydata) return createClass(IDispatch, olerepr, userName,UnicodeToString, lazydata) def MakeOleRepr(IDispatch, typeinfo, typecomp): olerepr =3D None if typeinfo is not None: try: attr =3D typeinfo.GetTypeAttr() # If the type info is a special DUAL interface, magically turn it into # a DISPATCH typeinfo. if attr[5] =3D=3D pythoncom.TKIND_INTERFACE and attr[11] & pythoncom.TYP= EFLAG_FDUAL: # Get corresponding Disp interface; # -1 is a special value which does this for us. href =3D typeinfo.GetRefTypeOfImplType(-1); typeinfo =3D typeinfo.GetRefTypeInfo(href) attr =3D typeinfo.GetTypeAttr() if typecomp is None: olerepr =3D build.DispatchItem(typeinfo, attr, None, 0) else: olerepr =3D build.LazyDispatchItem(attr, None) except pythoncom.ole_error: pass if olerepr is None: olerepr =3D build.DispatchItem() return olerepr def DumbDispatch(IDispatch, userName =3D None, createClass =3D None,Unicode= ToString=3DNeedUnicodeConversions, clsctx=3Dpythoncom.CLSCTX_SERVER): "Dispatch with no type info" IDispatch, userName =3D _GetGoodDispatchAndUserName(IDispatch,userName,cls= ctx) if createClass is None: createClass =3D CDispatch return createClass(IDispatch, build.DispatchItem(), userName,UnicodeToStri= ng) class CDispatch: def __init__(self, IDispatch, olerepr, userName =3D None, UnicodeToString= =3DNeedUnicodeConversions, lazydata =3D None): if userName is None: userName =3D "" self.__dict__['_oleobj_'] =3D IDispatch self.__dict__['_username_'] =3D userName self.__dict__['_olerepr_'] =3D olerepr self.__dict__['_mapCachedItems_'] =3D {} self.__dict__['_builtMethods_'] =3D {} self.__dict__['_enum_'] =3D None self.__dict__['_unicode_to_string_'] =3D UnicodeToString self.__dict__['_lazydata_'] =3D lazydata def __call__(self, *args): "Provide 'default dispatch' COM functionality - allow instance to be call= ed" if self._olerepr_.defaultDispatchName: invkind, dispid =3D self._find_dispatch_type_(self._olerepr_.defaultDisp= atchName) else: invkind, dispid =3D pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPE= RTYGET, pythoncom.DISPID_VALUE if invkind is not None: allArgs =3D (dispid,LCID,invkind,1) + args return self._get_good_object_(apply(self._oleobj_.Invoke,allArgs),self._= olerepr_.defaultDispatchName,None) raise TypeError, "This dispatch object does not define a default method" def __nonzero__(self): return 1 # ie "if object:" should always be "true" - without this, __len_= _ is tried. # _Possibly_ want to defer to __len__ if available, but Im not sure this = is # desirable??? def __repr__(self): return "" % (self._username_) def __str__(self): # __str__ is used when the user does "print object", so we gracefully # fall back to the __repr__ if the object has no default method. try: return str(self.__call__()) except pythoncom.com_error, details: if details[0] not in ERRORS_BAD_CONTEXT: raise return self.__repr__() # Delegate comparison to the oleobjs, as they know how to do identity. def __cmp__(self, other): other =3D getattr(other, "_oleobj_", other) return cmp(self._oleobj_, other) def __int__(self): return int(self.__call__()) def __len__(self): invkind, dispid =3D self._find_dispatch_type_("Count") if invkind: return self._oleobj_.Invoke(dispid, LCID, invkind, 1) raise TypeError, "This dispatch object does not define a Count method" def _NewEnum(self): invkind, dispid =3D self._find_dispatch_type_("_NewEnum") if invkind is None: return None =09 enum =3D self._oleobj_.InvokeTypes(pythoncom.DISPID_NEWENUM,LCID,invkind,= (13, 10),()) import util return util.WrapEnum(enum, None) def __getitem__(self, index): # syver modified # Improved __getitem__ courtesy Syver Enstad # Must check _NewEnum before Item, to ensure b/w compat. if isinstance(index, IntType): if self.__dict__['_enum_'] is None: self.__dict__['_enum_'] =3D self._NewEnum() if self.__dict__['_enum_'] is not None: return self._get_good_object_(self._enum_.__getitem__(index)) # See if we have an "Item" method/property we can use (goes hand in hand = with Count() above!) invkind, dispid =3D self._find_dispatch_type_("Item") if invkind is not None: return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind= , 1, index)) raise TypeError, "This object does not support enumeration" def __setitem__(self, index, *args): # XXX - todo - We should support calling Item() here too! # print "__setitem__ with", index, args if self._olerepr_.defaultDispatchName: invkind, dispid =3D self._find_dispatch_type_(self._olerepr_.defaultDisp= atchName) else: invkind, dispid =3D pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_= PROPERTYPUTREF, pythoncom.DISPID_VALUE if invkind is not None: allArgs =3D (dispid,LCID,invkind,0,index) + args return self._get_good_object_(apply(self._oleobj_.Invoke,allArgs),self._= olerepr_.defaultDispatchName,None) raise TypeError, "This dispatch object does not define a default method" def _find_dispatch_type_(self, methodName): if self._olerepr_.mapFuncs.has_key(methodName): item =3D self._olerepr_.mapFuncs[methodName] return item.desc[4], item.dispid if self._olerepr_.propMapGet.has_key(methodName): item =3D self._olerepr_.propMapGet[methodName] return item.desc[4], item.dispid try: dispid =3D self._oleobj_.GetIDsOfNames(0,methodName) except: ### what error? return None, None return pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSI= D, *args): result =3D apply(self._oleobj_.InvokeTypes, (dispid, LCID, wFlags, retTyp= e, argTypes) + args) return self._get_good_object_(result, user, resultCLSID) def _wrap_dispatch_(self, ob, userName =3D None, returnCLSID =3D None, Uni= codeToString =3D NeedUnicodeConversions): # Given a dispatch object, wrap it in a class return Dispatch(ob, userName, UnicodeToString=3DUnicodeToString) def _get_good_single_object_(self,ob,userName =3D None, ReturnCLSID=3DNone= ): if iunkType=3D=3Dtype(ob): try: ob =3D ob.QueryInterface(pythoncom.IID_IDispatch) # If this works, we then enter the "is dispatch" test below. except pythoncom.com_error: # It is an IUnknown, but not an IDispatch, so just let it through. pass if dispatchType=3D=3Dtype(ob): # make a new instance of (probably this) class. return self._wrap_dispatch_(ob, userName, ReturnCLSID) elif self._unicode_to_string_ and UnicodeType=3D=3Dtype(ob): =20 return str(ob) else: return ob =09 def _get_good_object_(self,ob,userName =3D None, ReturnCLSID=3DNone): """Given an object (usually the retval from a method), make it a good obj= ect to return. Basically checks if it is a COM object, and wraps it up. Also handles the fact that a retval may be a tuple of retvals""" if ob is None: # Quick exit! return None elif type(ob)=3D=3DTupleType: return tuple(map(lambda o, s=3Dself, oun=3DuserName, rc=3DReturnCLSID: s= ._get_good_single_object_(o, oun, rc), ob)) else: return self._get_good_single_object_(ob) =09 def _make_method_(self, name): "Make a method object - Assumes in olerepr funcmap" methodName =3D build.MakePublicAttributeName(name) # translate keywords e= tc. methodCodeList =3D self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[= name], methodName,0) methodCode =3D string.join(methodCodeList,"\n") try: # print "Method code for %s is:\n" % self._username_, methodCode # self._print_details_() codeObject =3D compile(methodCode, "" % self._username_,"e= xec") # Exec the code object tempNameSpace =3D {} exec codeObject in globals(), tempNameSpace # self.__dict__, self.__dict= __ name =3D methodName # Save the function in map. fn =3D self._builtMethods_[name] =3D tempNameSpace[name] newMeth =3D new.instancemethod(fn, self, self.__class__) return newMeth except: debug_print("Error building OLE definition for code ", methodCode) traceback.print_exc() return None =09 def _Release_(self): """Cleanup object - like a close - to force cleanup when you dont=20 want to rely on Python's reference counting.""" for childCont in self._mapCachedItems_.values(): childCont._Release_() self._mapCachedItems_ =3D {} if self._oleobj_: self._oleobj_.Release() self.__dict__['_oleobj_'] =3D None if self._olerepr_: self.__dict__['_olerepr_'] =3D None self._enum_ =3D None def _proc_(self, name, *args): """Call the named method as a procedure, rather than function. Mainly used by Word.Basic, which whinges about such things.""" try: item =3D self._olerepr_.mapFuncs[name] dispId =3D item.dispid return self._get_good_object_(apply( self._oleobj_.Invoke, (dispId, LCID= , item.desc[4], 0 ) + (args) )) except KeyError: raise AttributeError, name =09 def _print_details_(self): "Debug routine - dumps what it knows about an object." print "AxDispatch container",self._username_ try: print "Methods:" for method in self._olerepr_.mapFuncs.keys(): print "\t", method print "Props:" for prop, entry in self._olerepr_.propMap.items(): print "\t%s =3D 0x%x - %s" % (prop, entry.dispid, `entry`) print "Get Props:" for prop, entry in self._olerepr_.propMapGet.items(): print "\t%s =3D 0x%x - %s" % (prop, entry.dispid, `entry`) print "Put Props:" for prop, entry in self._olerepr_.propMapPut.items(): print "\t%s =3D 0x%x - %s" % (prop, entry.dispid, `entry`) except: traceback.print_exc() def __LazyMap__(self, attr): try: if self._LazyAddAttr_(attr): debug_attr_print("%s.__LazyMap__(%s) added something" % (self._username= _,attr)) return 1 except AttributeError: return 0 # Using the typecomp, lazily create a new attribute definition. def _LazyAddAttr_(self,attr): if self._lazydata_ is None: return 0 res =3D 0 i =3D 0 typeinfo, typecomp =3D self._lazydata_ olerepr =3D self._olerepr_ try: x,t =3D typecomp.Bind(attr,i) if x=3D=3D1: #it's a FUNCDESC r =3D olerepr._AddFunc_(typeinfo,t,0) elif x=3D=3D2: #it's a VARDESC r =3D olerepr._AddVar_(typeinfo,t,0) else: #not found or TYPEDESC/IMPLICITAPP r=3DNone if not r is None: key, map =3D r[0],r[1] item =3D map[key] if map=3D=3Dolerepr.propMapPut: olerepr._propMapPutCheck_(key,item) elif map=3D=3Dolerepr.propMapGet: olerepr._propMapGetCheck_(key,item) res =3D 1 except: pass return res def _FlagAsMethod(self, *methodNames): """Flag these attribute names as being methods. Some objects do not correctly differentiate methods and properties, leading to problems when calling these methods. Specifically, trying to say: ob.SomeFunc() may yield an exception "None object is not callable" In this case, an attempt to fetch the *property*has worked and returned None, rather than indicating it is really a method. Calling: ob._FlagAsMethod("SomeFunc") should then allow this to work. """ for name in methodNames: details =3D build.MapEntry(self.__AttrToID__(name), (name,)) self._olerepr_.mapFuncs[name] =3D details def __AttrToID__(self,attr): debug_attr_print("Calling GetIDsOfNames for property %s in Dispatch cont= ainer %s" % (attr, self._username_)) return self._oleobj_.GetIDsOfNames(0,attr) def __getattr__(self, attr): if attr[0]=3D=3D'_' and attr[-1]=3D=3D'_': # Fast-track. raise AttributeError, attr # If a known method, create new instance and return. try: return new.instancemethod(self._builtMethods_[attr], self, self.__class_= _) except KeyError: pass # XXX - Note that we current are case sensitive in the method. #debug_attr_print("GetAttr called for %s on DispatchContainer %s" % (attr= ,self._username_)) # First check if it is in the method map. Note that an actual method # must not yet exist, (otherwise we would not be here). This # means we create the actual method object - which also means # this code will never be asked for that method name again. if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) # Delegate to property maps/cached items retEntry =3D None if self._olerepr_ and self._oleobj_: # first check general property map, then specific "put" map. if self._olerepr_.propMap.has_key(attr): retEntry =3D self._olerepr_.propMap[attr] if retEntry is None and self._olerepr_.propMapGet.has_key(attr): retEntry =3D self._olerepr_.propMapGet[attr] # Not found so far - See what COM says. if retEntry is None: try: if self.__LazyMap__(attr): if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(a= ttr) if self._olerepr_.propMap.has_key(attr): retEntry =3D self._olerepr_.propMap[attr] if retEntry is None and self._olerepr_.propMapGet.has_key(attr): retEntry =3D self._olerepr_.propMapGet[attr] if retEntry is None: retEntry =3D build.MapEntry(self.__AttrToID__(attr), (attr,)) except pythoncom.ole_error: pass # No prop by that name - retEntry remains None. if not retEntry is None: # see if in my cache try: ret =3D self._mapCachedItems_[retEntry.dispid] debug_attr_print ("Cached items has attribute!", ret) return ret except (KeyError, AttributeError): debug_attr_print("Attribute %s not in cache" % attr) # If we are still here, and have a retEntry, get the OLE item if not retEntry is None: debug_attr_print("Getting property Id 0x%x from OLE object" % retEntry.d= ispid) try: ret =3D self._oleobj_.Invoke(retEntry.dispid,0,pythoncom.DISPATCH_PROPE= RTYGET,1) except pythoncom.com_error, details: if details[0] in ERRORS_BAD_CONTEXT: # May be a method. self._olerepr_.mapFuncs[attr] =3D retEntry return self._make_method_(attr) raise pythoncom.com_error, details self._olerepr_.propMap[attr] =3D retEntry debug_attr_print("OLE returned ", ret) return self._get_good_object_(ret) # no where else to look. raise AttributeError, "%s.%s" % (self._username_, attr) def __setattr__(self, attr, value): if self.__dict__.has_key(attr): # Fast-track - if already in our dict, ju= st make the assignment. # XXX - should maybe check method map - if someone assigns to a method, # it could mean something special (not sure what, tho!) self.__dict__[attr] =3D value return # Allow property assignment. debug_attr_print("SetAttr called for %s.%s=3D%s on DispatchContainer" % (= self._username_, attr, `value`)) if self._olerepr_: # Check the "general" property map. if self._olerepr_.propMap.has_key(attr): self._oleobj_.Invoke(self._olerepr_.propMap[attr].dispid, 0, pythoncom.= DISPATCH_PROPERTYPUT, 0, value) return # Check the specific "put" map. if self._olerepr_.propMapPut.has_key(attr): self._oleobj_.Invoke(self._olerepr_.propMapPut[attr].dispid, 0, pythonc= om.DISPATCH_PROPERTYPUT, 0, value) return # Try the OLE Object if self._oleobj_: if self.__LazyMap__(attr): # Check the "general" property map. if self._olerepr_.propMap.has_key(attr): self._oleobj_.Invoke(self._olerepr_.propMap[attr].dispid, 0, pythoncom= .DISPATCH_PROPERTYPUT, 0, value) return # Check the specific "put" map. if self._olerepr_.propMapPut.has_key(attr): self._oleobj_.Invoke(self._olerepr_.propMapPut[attr].dispid, 0, python= com.DISPATCH_PROPERTYPUT, 0, value) return try: entry =3D build.MapEntry(self.__AttrToID__(attr),(attr,)) except pythoncom.com_error: # No attribute of that name entry =3D None if entry is not None: try: self._oleobj_.Invoke(entry.dispid, 0, pythoncom.DISPATCH_PROPERTYPUT, = 0, value) self._olerepr_.propMap[attr] =3D entry debug_attr_print("__setattr__ property %s (id=3D0x%x) in Dispatch cont= ainer %s" % (attr, entry.dispid, self._username_)) return except pythoncom.com_error: pass raise AttributeError, "Property '%s.%s' can not be set." % (self._usernam= e_, attr) --=-7rU/FdBwTZXQtnUZUa7s-- From gagenellina@softlab.com.ar Tue May 21 02:11:47 2002 From: gagenellina@softlab.com.ar (Gabriel Genellina) Date: Mon, 20 May 2002 22:11:47 -0300 Subject: [python-win32] Detecting Ctrl-Break Message-ID: <5.1.0.14.0.20020520220222.01d71c50@192.168.0.115> Hi How can I detect Ctrl-Break? Ctrl-C raises KeyboardInterrupt, but Ctrl-Break does not. Apparently it aborts the interpreter, even the try/finally block isn't honored. Test: import sys def test(): while 1: print '.', if __name__=='__main__': try: try: test() except KeyboardInterrupt: print "\nKeyboardInterrupt detected" sys.exit(0) except: print "\nAnother exception" sys.exit(0) finally: print "\nFinally" Gabriel Genellina Softlab SRL From itamarst@yahoo.com Tue May 21 23:24:35 2002 From: itamarst@yahoo.com (Itamar S.-T.) Date: Tue, 21 May 2002 15:24:35 -0700 (PDT) Subject: [python-win32] Detecting Ctrl-Break In-Reply-To: <5.1.0.14.0.20020520220222.01d71c50@192.168.0.115> Message-ID: <20020521222435.2089.qmail@web13002.mail.yahoo.com> In Python 2.2 there's a signal for Ctrl-Break, signal.SIGBREAK, so you can add a handler for it using the signal module. ===== Itamar Shtull-Trauring, itamar(at)shtull-trauring.org __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com From me@mikerobin.com Wed May 22 00:32:29 2002 From: me@mikerobin.com (Michael Robin) Date: Tue, 21 May 2002 16:32:29 -0700 Subject: [python-win32] IE BH object In-Reply-To: <20020521160010.29170.26395.Mailman@mail.python.org> Message-ID: I'd like to be able to inspect/modify the DOM belonging to instances of MS IE foreign to my application's process. I know one way to do this is to use a BrowserHelperObject. (Is there another way?) Does anyone know of any existing classes (pure python+pycom or native extension) to accomplish this, as well as GUI-related browser extensions? thanks, mike me@mikerobin.com From me@mikerobin.com Wed May 22 05:53:05 2002 From: me@mikerobin.com (Michael Robin) Date: Tue, 21 May 2002 21:53:05 -0700 Subject: [python-win32] RE: IE BH object In-Reply-To: <000001c20136$6247ce50$0301a8c0@JONAH> Message-ID: Yes, thanks - I'm doing this already. Note again that I want to attach to instances of the browser that aren't started by my application. thanks, mike -----Original Message----- From: Matthew Sherborne [mailto:miracle@paradise.net.nz] Sent: Tuesday, May 21, 2002 7:13 PM To: me@mikerobin.com; python-win32@python.org; activepython@listserv.ActiveState.com; pycom-dev@pythonpros.com Cc: Michael Robin Subject: Re: IE BH object PythonCOM from activestate allows you to get the IE Document COM object and this acts like a DOM. http://aspn.activestate.com/ASPN/Mail/Message/activepython/1014204 GBU Matthew Sherborne From miracle@paradise.net.nz Wed May 22 03:13:09 2002 From: miracle@paradise.net.nz (Matthew Sherborne) Date: Wed, 22 May 2002 14:13:09 +1200 Subject: [python-win32] Re: IE BH object References: Message-ID: <000001c20136$6247ce50$0301a8c0@JONAH> PythonCOM from activestate allows you to get the IE Document COM object and this acts like a DOM. http://aspn.activestate.com/ASPN/Mail/Message/activepython/1014204 GBU Matthew Sherborne From miracle@paradise.net.nz Wed May 22 07:22:10 2002 From: miracle@paradise.net.nz (Matthew Sherborne) Date: Wed, 22 May 2002 18:22:10 +1200 Subject: [python-win32] Re: IE BH object References: Message-ID: <001401c20159$018d74c0$0301a8c0@JONAH> You want GetActiveObject http://aspn.activestate.com/ASPN/Reference/Products/ActivePython/win32com/py thoncom__GetActiveObject_meth.html But I've never got it working myself. GBU Matthew Sherborne ----- Original Message ----- From: "Michael Robin" To: "Matthew Sherborne" ; ; ; Sent: Wednesday, May 22, 2002 4:53 PM Subject: RE: IE BH object > Yes, thanks - I'm doing this already. > Note again that I want to attach to instances of > the browser that aren't started by my application. > > thanks, > mike > > -----Original Message----- > From: Matthew Sherborne [mailto:miracle@paradise.net.nz] > Sent: Tuesday, May 21, 2002 7:13 PM > To: me@mikerobin.com; python-win32@python.org; > activepython@listserv.ActiveState.com; pycom-dev@pythonpros.com > Cc: Michael Robin > Subject: Re: IE BH object > > > PythonCOM from activestate allows you to get the IE Document COM object and > this acts like a DOM. > > http://aspn.activestate.com/ASPN/Mail/Message/activepython/1014204 > > GBU > Matthew Sherborne > > > > > From MarkA@sundance.com Wed May 22 10:35:43 2002 From: MarkA@sundance.com (Mark Ainsworth) Date: Wed, 22 May 2002 10:35:43 +0100 Subject: [python-win32] Silly com question really. Geting a value back Message-ID: I'm sorry if this seems trivial, and the answer is probably very simple for those of you who know. Unfortunately I'm not one of you yet. I am trying to get the value of a comments field in an excel spreadsheet. No matter what I try though I just keep on getting the bound object, rather than the object value. Can someone please tell me the simple answer. Thanks. from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlBook = xlApp.Workbooks.Open("product status v13 - internal.xls",0,1,1,"password") st = str(xlBook.Sheets("Modules").Range("a4").Comment.Text) print st > I don't want to know this. I want to see the contents of the comment field :-S Mark Ainsworth Quality Manager Sundance Multiprocessor Technology Ltd. Chiltern House, Waterside, Chesham, Bucks HP5 1PS Tel. +44 1494 793167 Fax. +44 1494 793168 MarkA@sundance.com http://www.sundance.com From niki@vintech.bg Wed May 22 10:54:08 2002 From: niki@vintech.bg (Niki Spahiev) Date: Wed, 22 May 2002 12:54:08 +0300 Subject: [python-win32] Silly com question really. Geting a value back References: Message-ID: <3CEB6AC0.6060504@vintech.bg> Mark Ainsworth wrote: [...] > st = str(xlBook.Sheets("Modules").Range("a4").Comment.Text) call 'Text' -> .Comment.Text() HTH Niki Spahiev From mrroach@uhg.net Tue May 28 22:17:50 2002 From: mrroach@uhg.net (Roach, Mark R.) Date: 28 May 2002 16:17:50 -0500 Subject: [python-win32] pty's in win32? Message-ID: <1022620670.20395.42.camel@tncorpmrr001.uhg> I am working on a server configuration utility that I want to be able to run from either the server itself(and have some shell commands executed locally) or from a client (and have an ssh session run the commands on the server). My problem is that while under linux I can use a pty for r/w to a process, I can't seem to find a way to use pty's in win32. Is there a way to do this, or another similar approach? Thanks, Mark Roach From mbg@apama.com Thu May 30 18:17:39 2002 From: mbg@apama.com (Moray B. Grieve) Date: Thu, 30 May 2002 18:17:39 +0100 Subject: [python-win32] exitCode for win32process.GetExitCodeProcess Message-ID: <7CD4BE0203A91845A17CE0E8BD9A1289092D39@UKCAMMS002.msapama.apama.com> The MSDN literature states that calling = win32process.GetExitCodeProcess(hProcess) on an active process returns = the integer exit code STILL_ACTIVE. I cannot see this constant defined = anywhere in the win32 extensions. From trying it out I seem to get an = exit code of 259 when I attempt the method call on an active process. Does anyone know if this is the value of the STILL_ACTIVE constant, or = where I can access it? I've tried looking through the source code but to = no avail. With thanks for any help Moray Grieve From terjeja@hotmail.com Thu May 30 20:39:17 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Thu, 30 May 2002 19:39:17 +0000 Subject: [python-win32] Date in Excel (Win32Com) Message-ID: I use Win32Com to move info from Excel to an AS/400 system. I need to check that the dates corespond in the two systems. In AS/400 I would use this to pick up the value: ex = accountcurrents.ex.ActiveSession.Screen.GetString(14, 15, 8) then if I type: >>>ex I get: u'10/30/00' However, when I do the same in Excel: xl = accountcurrents.xlSheet.Cells(9,2).Value And type: >>>xl I get: