From max at slimmersoft.com Tue Oct 4 07:13:35 2011 From: max at slimmersoft.com (Max Slimmer) Date: Mon, 3 Oct 2011 22:13:35 -0700 Subject: [python-win32] Problems with adodbapi Message-ID: I am trying to access a sqlbase database, In the past I had no problem, but after re-installing python and win32 etc and therefore getting latest version of adodbapi I get the following symptom When I do cursor.execute("select xxx from sometable") and xxx contains one of the following columns as described by the cursor.description attribute: (u'STATELVDINCODE', 200, None, 2, 255, 255, False) (u'LCLTYWRKEDINCODE', 200, None, 4, 255, 255, False) (u'LCLTYLVDINCODE', 200, None, 4, 255, 255, False) (u'EZLMEMPLOYEEID', 200, None, 32, 255, 255, False) By going back to version 2.2.5 I no longer get this failure. I have tried to walk into the code and have yet to determine just where it is failing, It fails in the execute setup, but doesn't error, just returns -1. can you give me an idea where to look in the code, maybe some exception is getting caught and not returned? A second problem with a different (foxpro) database, is field type 131 adDBDate is getting converted to a datetime and the value returned is datetime.datetime(yyyy, MM, dd, hh, mm) I would prefer to get datetime.date objects, Thanks for any piinters. I will try to find just where things are going astray, but as yet not familiar with the code. max -------------- next part -------------- An HTML attachment was scrubbed... URL: From amauryfa at gmail.com Tue Oct 4 14:11:20 2011 From: amauryfa at gmail.com (Amaury Forgeot d'Arc) Date: Tue, 4 Oct 2011 14:11:20 +0200 Subject: [python-win32] Problems with adodbapi In-Reply-To: References: Message-ID: Hi, 2011/10/4 Max Slimmer : > I am trying to access a sqlbase database, In the past I had no problem, but > after re-installing python and win32 etc and therefore getting latest > version of adodbapi I get the following symptom You did not tell us what the symptom is... > A second problem with a different (foxpro) database, is field type 131 adDBDate > is getting converted to a datetime and the value returned is > datetime.datetime(yyyy, MM, dd, hh, mm) I would prefer to get datetime.date > objects, I find datetime objects often easier to use. Can you call the .date() method? -- Amaury Forgeot d'Arc From anthony.mpofu at gmail.com Wed Oct 5 15:53:15 2011 From: anthony.mpofu at gmail.com (Anthony Mpofu) Date: Wed, 5 Oct 2011 15:53:15 +0200 Subject: [python-win32] read word contents including images and font format Message-ID: Hi All I want to read contents from a word document (source) and insert the contents to the (destination) word document. I have used the following code: # Read content from source word = win32.gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open("source.doc") data = word.Documents[0].Content # Insert data read from source to destination document dest_doc = word.Documents.Open("destination.doc") startAt = dest_doc.Range(4,4) startAt.InsertBefore(data) dest_doc.SaveAs( "destination.doc" ) The above solution only copies the text content from the source document. The read contents loses the original formating (font size, font type) The read contents fails to load images from the document. Is there a method that will allow reading word content with the original formatting as well as images. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Wed Oct 5 18:30:36 2011 From: timr at probo.com (Tim Roberts) Date: Wed, 5 Oct 2011 09:30:36 -0700 Subject: [python-win32] read word contents including images and font format In-Reply-To: References: Message-ID: <4E8C862C.5030601@probo.com> Anthony Mpofu wrote: > > I want to read contents from a word document (source) and insert the > contents to the (destination) word document. > ... > The above solution only copies the text content from the source document. > The read contents loses the original formating (font size, font type) > The read contents fails to load images from the document. > > Is there a method that will allow reading word content with the > original formatting as well as images. Do it exactly like you would do it by hand: go through the clipboard, using Copy and Paste methods. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From waldemar.osuch at gmail.com Wed Oct 5 19:45:51 2011 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 5 Oct 2011 11:45:51 -0600 Subject: [python-win32] read word contents including images and font format In-Reply-To: <4E8C862C.5030601@probo.com> References: <4E8C862C.5030601@probo.com> Message-ID: On Wed, Oct 5, 2011 at 10:30, Tim Roberts wrote: > Anthony Mpofu wrote: >> >> I want to read contents from a word document (source) and insert the >> contents to the (destination) word document. >> ... >> The above solution only copies the text content from the source document. >> The read contents loses the original formating (font size, font type) >> The read contents fails to load images from the document. >> >> Is there a method that will allow reading word content with the >> original formatting as well as images. > > Do it exactly like you would do it by hand: go through the clipboard, > using Copy and Paste methods. > Another option is to inject the source document into the destination using "range.InsertFile" It should preserve images and such. I have used this approach recently to generate one document out bunch of chunks stored in a database. Waldemar From hossain.iqbal at gmail.com Tue Oct 11 18:06:45 2011 From: hossain.iqbal at gmail.com (Riz Hossain) Date: Tue, 11 Oct 2011 12:06:45 -0400 Subject: [python-win32] iTunes control using win32.com Message-ID: Hello, I am trying to automate some of the iTunes control using python. So far I have been able to manage: - Add tracks to iTunes library - Create Playlist in iTunes - Delete Playlist in iTunes - Add tracks to Playlist I haven't found any help online for: - Renaming a playlist - Rename track info (Track Name, Album name, and artist name) Any kind of pointers or help would be greatly appreciated Example to add tracks to a playlist: import win32com.client iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") libraryTracks = iTunes.LibraryPlaylist.Tracks track = libraryTracks.Item(5) print track.Name playlist_1 = iTunes.LibrarySource.Playlists.Item(15) print playlist_1.Name #playlist = win32com.client.CastTo(iTunes.CreatePlaylist('Test'), 'IITUserPlaylist') playlist = win32com.client.CastTo(iTunes.LibrarySource.Playlists.Item(16), 'IITUserPlaylist') playlist.AddTrack(track) -- Riz Hossain Engineering Physics (B.Eng) Software Test Specialist Research In Motion 295 Phillip Street Waterloo, ON N2L 3L3 This transmission (including any attachments) may contain confidential information, privileged material (including material protected by the solicitor-client or other applicable privileges), or constitute non-public information. Any use of this information by anyone other than the intended recipient is prohibited. If you have received this transmission in error, please immediately reply to the sender and delete this information from your system. Use, dissemination, distribution, or reproduction of this transmission by unintended recipients is not authorized and may be unlawful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amauryfa at gmail.com Tue Oct 11 18:13:54 2011 From: amauryfa at gmail.com (Amaury Forgeot d'Arc) Date: Tue, 11 Oct 2011 18:13:54 +0200 Subject: [python-win32] iTunes control using win32.com In-Reply-To: References: Message-ID: 2011/10/11 Riz Hossain > Hello, > > I am trying to automate some of the iTunes control using python. So far I > have been able to manage: > > - Add tracks to iTunes library > - Create Playlist in iTunes > - Delete Playlist in iTunes > - Add tracks to Playlist > > I haven't found any help online for: > > - Renaming a playlist > - Rename track info (Track Name, Album name, and artist name) > > Any kind of pointers or help would be greatly appreciated > You'll probably find everything in the iTunes COM SDK, here is how to obtain it: http://stackoverflow.com/questions/2966992/where-is-itunes-sdk-api-documentation -- Amaury Forgeot d'Arc -------------- next part -------------- An HTML attachment was scrubbed... URL: From hossain.iqbal at gmail.com Tue Oct 11 18:31:07 2011 From: hossain.iqbal at gmail.com (Riz Hossain) Date: Tue, 11 Oct 2011 16:31:07 +0000 Subject: [python-win32] iTunes control using win32.com In-Reply-To: References: Message-ID: <1588109732-1318350671-cardhu_decombobulator_blackberry.rim.net-1253215411-@b16.c4.bise6.blackberry> Thanks Amaury for the quick reply. I was actually using it but, couldn't find much help for python. Thanks, Riz Sent from my BlackBerry Torch -----Original Message----- From: "Amaury Forgeot d'Arc" Date: Tue, 11 Oct 2011 18:13:54 To: Riz Hossain Cc: Subject: Re: [python-win32] iTunes control using win32.com 2011/10/11 Riz Hossain > Hello, > > I am trying to automate some of the iTunes control using python. So far I > have been able to manage: > > - Add tracks to iTunes library > - Create Playlist in iTunes > - Delete Playlist in iTunes > - Add tracks to Playlist > > I haven't found any help online for: > > - Renaming a playlist > - Rename track info (Track Name, Album name, and artist name) > > Any kind of pointers or help would be greatly appreciated > You'll probably find everything in the iTunes COM SDK, here is how to obtain it: http://stackoverflow.com/questions/2966992/where-is-itunes-sdk-api-documentation -- Amaury Forgeot d'Arc -------------- next part -------------- An HTML attachment was scrubbed... URL: From amauryfa at gmail.com Tue Oct 11 18:54:59 2011 From: amauryfa at gmail.com (Amaury Forgeot d'Arc) Date: Tue, 11 Oct 2011 18:54:59 +0200 Subject: [python-win32] iTunes control using win32.com In-Reply-To: <1588109732-1318350671-cardhu_decombobulator_blackberry.rim.net-1253215411-@b16.c4.bise6.blackberry> References: <1588109732-1318350671-cardhu_decombobulator_blackberry.rim.net-1253215411-@b16.c4.bise6.blackberry> Message-ID: 2011/10/11 Riz Hossain > I was actually using it but, couldn't find much help for python. But you don't need python documentation! A COM library implement objects, their attributes and methods. It's independent from the programming language, the available classes and functions are really the same. Try to find the documentation related to iTunes.Application.CreatePlaylist for example. I'm sure that the corresponding examples will look similar to the code you showed earlier. -- Amaury Forgeot d'Arc -------------- next part -------------- An HTML attachment was scrubbed... URL: From hossain.iqbal at gmail.com Tue Oct 11 21:23:32 2011 From: hossain.iqbal at gmail.com (Riz Hossain) Date: Tue, 11 Oct 2011 15:23:32 -0400 Subject: [python-win32] iTunes control using win32.com In-Reply-To: References: <1588109732-1318350671-cardhu_decombobulator_blackberry.rim.net-1253215411-@b16.c4.bise6.blackberry> Message-ID: Thanks for your help guys. I did get a webpage that has some of the items i was looking for. However, the iTunes SDK does not have any mention of "reanme" or "replace". I am not an expert at coding myself. Is there anyway i can share my work to control all the basic functionality to run any automation testing for iTunes? I was hoping to collaborate all my finding that are scattered on the web. example to edit: newval = track.Album.replace("old_Value", "New_Value") playlist_1.Name = newval Thanks, Riz On Tue, Oct 11, 2011 at 12:54 PM, Amaury Forgeot d'Arc wrote: > 2011/10/11 Riz Hossain > >> I was actually using it but, couldn't find much help for python. > > > But you don't need python documentation! > A COM library implement objects, their attributes and methods. > It's independent from the programming language, > the available classes and functions are really the same. > > Try to find the documentation related to iTunes.Application. > CreatePlaylist for example. > I'm sure that the corresponding examples will look similar to the code you > showed earlier. > > -- > Amaury Forgeot d'Arc > -- Riz Hossain Engineering Physics (B.Eng) Software Test Specialist Research In Motion 295 Phillip Street Waterloo, ON N2L 3L3 This transmission (including any attachments) may contain confidential information, privileged material (including material protected by the solicitor-client or other applicable privileges), or constitute non-public information. Any use of this information by anyone other than the intended recipient is prohibited. If you have received this transmission in error, please immediately reply to the sender and delete this information from your system. Use, dissemination, distribution, or reproduction of this transmission by unintended recipients is not authorized and may be unlawful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Wed Oct 12 03:24:53 2011 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 12 Oct 2011 12:24:53 +1100 Subject: [python-win32] New win32com.client.VARIANT object Message-ID: <4E94EC65.8010207@skippinet.com.au> I just pushed a change which introduces a new win32com.client.VARIANT object. This object can be used in some situations to control the specific types passed as parameters to COM objects and should address a relatively common problem people hit when COM objects are very picky about the types they accept. I'm purposely being a little vague in this message about how it works to encourage people to check out the new documentation and see if it makes sense and describes how and when it can be useful. The docs are at http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/raw-file/36b16bcc5c9a/com/win32com/HTML/variant.html (and will obviously be included in the help file in future builds) If anyone has any general comments or comments on the documentation, I'm all ears! I hope to release a new pywin32 within a few weeks with this feature, but if anyone has a specific usecase they would like to test it out on, please contact me privately with the version of Python you are using and I'll make a test build available. Thanks, Mark From graham.bloice at trihedral.com Wed Oct 12 11:55:22 2011 From: graham.bloice at trihedral.com (Graham Bloice) Date: Wed, 12 Oct 2011 10:55:22 +0100 Subject: [python-win32] New win32com.client.VARIANT object In-Reply-To: <4E94EC65.8010207@skippinet.com.au> References: <4E94EC65.8010207@skippinet.com.au> Message-ID: <4E95640A.90901@trihedral.com> On 12/10/2011 02:24, Mark Hammond wrote: > I just pushed a change which introduces a new win32com.client.VARIANT > object. This object can be used in some situations to control the specific > types passed as parameters to COM objects and should address a relatively > common problem people hit when COM objects are very picky about the types > they accept. > > I'm purposely being a little vague in this message about how it works to > encourage people to check out the new documentation and see if it makes > sense and describes how and when it can be useful. The docs are at > http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/raw-file/36b16bcc5c9a/com/win32com/HTML/variant.html > (and will obviously be included in the help file in future builds) > > If anyone has any general comments or comments on the documentation, I'm all > ears! I hope to release a new pywin32 within a few weeks with this feature, > but if anyone has a specific usecase they would like to test it out on, > please contact me privately with the version of Python you are using and > I'll make a test build available. > > Thanks, > > Mark > > Small typo in the docs, the text refers to 'DumpDispatch' in one place rather than 'DumbDispatch. I think this feature is great, the use case I run across most often is the last one mentioned, where the IDL specifies a VARIANT parameter but the COM object is actually much more picky about the accepted types. OPC suffers a fair bit from this, as the implementation quality of OPC servers varies a lot. -- Regards, Graham Bloice From michael.illgner at googlemail.com Wed Oct 12 15:16:26 2011 From: michael.illgner at googlemail.com (Michael Illgner) Date: Wed, 12 Oct 2011 15:16:26 +0200 Subject: [python-win32] New win32com.client.VARIANT object In-Reply-To: <4E95640A.90901@trihedral.com> References: <4E94EC65.8010207@skippinet.com.au> <4E95640A.90901@trihedral.com> Message-ID: 2011/10/12 Graham Bloice : > I think this feature is great, the use case I run across most often is the > last one mentioned, where the IDL specifies a VARIANT parameter but the COM > object is actually much more picky about the accepted types. That sounds great, but I just switched to comtypes :-( because the COM objects I had to use only specify VARIANT as parameter type but in fact they only want array's of I4. From skippy.hammond at gmail.com Thu Oct 13 02:45:17 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Thu, 13 Oct 2011 11:45:17 +1100 Subject: [python-win32] New win32com.client.VARIANT object In-Reply-To: References: <4E94EC65.8010207@skippinet.com.au> <4E95640A.90901@trihedral.com> Message-ID: <4E96349D.70209@gmail.com> On 13/10/2011 12:16 AM, Michael Illgner wrote: > 2011/10/12 Graham Bloice: Thanks Graham - I fixed the typo. > >> I think this feature is great, the use case I run across most often is the >> last one mentioned, where the IDL specifies a VARIANT parameter but the COM >> object is actually much more picky about the accepted types. > That sounds great, but I just switched to comtypes :-( because the COM > objects I had to use only specify VARIANT as parameter type but in > fact they only want array's of I4. That kinsa sucks - but if it is any consolation, your (currently unanswered) recent message on this issue was actually the catalyst for me finally implementing this feature :) Cheers, Mark From johnaherne at rocs.co.uk Fri Oct 14 10:47:50 2011 From: johnaherne at rocs.co.uk (John Aherne) Date: Fri, 14 Oct 2011 09:47:50 +0100 Subject: [python-win32] windows service problem and twisted Message-ID: I did post this to the twisted list but as I said in the original post, I think it is more a windows type issue than twisted. What I am trying to work out is should I import twisted.reactor etc inside the thread start in SvcDoRUn or import it globally as one of the examples does. And then should I be calling the reactor.fromthread in the SvcStop function. If I import reactor in SvcDoRun will the SvcStop be called in the same thread or not. One of the examples import reactor globally, starts the reactor in SvcDoRun - inside the thread - and in SvcStop, calls the reactorfromthread. This to me implies that SvcStop is in a different thread to SvcDoRun. But I could be completely wrong on this point. As you can see I am a little bit confused about what is happening here. I have been looking for some info on running twisted as a Windows Service. I have found various examples in mailing-lists and blogs that vary in what seem to be important respects. I have included them below as 3 examples. The problem I have is working out which scheme or combination I should be adopting. I have tried out some of the options and they appear to work. But I need something better than seems to work. My gut reaction is that I should be putting all my imports into SvcDoRun, since they will be used in the thread. But if I import the reactor in SvcDoRun, should I be using reactor.callfromthread(reactor.stop). I think not I think the use of waitforobject is the right thing to do as well without fully understanding it at the moment. If anyone can throw some light on what to do I shall be very grateful. It could be that I should post this question to python-windows mailing list since it seems to me more pertinent to windows than twisted. Thanks for any info. John Aherne Here is 1st example. The reactor is imported globally not in SvcDoRun It uses the waitforobject to detect stopping the service The reactor.stop is calledfromthread [Twisted-Python] How to run Twisted as a service in Windows? Thomas Jacob jacob at internet24.de Wed Aug 9 10:49:30 EDT 2006 Previous message: [Twisted-Python] How to run Twisted as a service in Windows? Next message: [Twisted-Python] How to run Twisted as a service in Windows? Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] AFAIK, twistd doesn't provide direct support for Windows Services yet (Is this planned?). But you can easily wrap a reactor,run() yourself by doing something like the following using the Win32-Python packages import win32serviceutil import win32service import win32event from twisted.internet import reactor import sys class IMSAgentBase(win32serviceutil.ServiceFramework): _svc_name_ = "myService" _svc_display_name_ = "My little Service" _svc_description_ = "My little Service" # Win2k or later _svc_deps_ = ["RpcSs"] # Start after the Network has come up... def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) reactor.callFromThread(reactor.stop) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # initialize your services here reactor.run() win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE) def HandleCommandLine(cls): win32serviceutil.HandleCommandLine(cls) Run the above as a script. Here is the 2nd example. The imports are global not in SvcDoRun And the reactor .stop is not called from thread. And the wait for stop event is in a timeout loop It uses waitforobject events It sets installsignalhandlers to 0 You can then test it out with the sample Echo client from the core docs. """qotdservice.py Sample Twisted Windows Service """ # Service Utilities import win32serviceutil import win32service import win32event # Twisted imports from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor class QOTD(Protocol): def connectionMade(self): self.transport.write("An apple a day keeps the doctor away\r\n") self.transport.loseConnection() class WindowsService(win32serviceutil.ServiceFramework): _svc_name_ = "TwistedWin32Service" _svc_display_name_ = "Twisted Win32 Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): import servicemanager self.CheckForQuit() factory = Factory() factory.protocol = QOTD reactor.listenTCP(8007, factory) reactor.run(installSignalHandlers=0) def CheckForQuit(self): retval = win32event.WaitForSingleObject(self.hWaitStop, 10) if not retval == win32event.WAIT_TIMEOUT: # Received Quit from Win32 reactor.stop() reactor.callLater(1.0, self.CheckForQuit) if __name__=='__main__': win32serviceutil.HandleCommandLine(WindowsService) Here is the 3rd example. The imports are done in SvcDoRun. There is no callfrom thread It does not use the waitforobject import sys, os import win32serviceutil, win32service class MyService(win32serviceutil.ServiceFramework): """NT Service.""" _svc_name_ = "MyService" _svc_display_name_ = "MyService server" def SvcDoRun(self): import server f = open(os.path.join(server.rootPath, "cyberhigh.log"), 'a') from twisted.python.log import startLogging from twisted.application.app import startApplication from twisted.internet import reactor startLogging(f) startApplication(server.application, 0) reactor.run() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) from twisted.internet import reactor reactor.stop() if __name__ == '__main__': win32serviceutil.HandleCommandLine(MyService) -------------- next part -------------- An HTML attachment was scrubbed... URL: From skippy.hammond at gmail.com Fri Oct 14 13:51:48 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 14 Oct 2011 22:51:48 +1100 Subject: [python-win32] windows service problem and twisted In-Reply-To: References: Message-ID: <4E982254.10803@gmail.com> On 14/10/2011 7:47 PM, John Aherne wrote: ... > What I am trying to work out is should I import twisted.reactor etc > inside the thread start in SvcDoRUn or import it globally as one of the > examples does. Dunno - does the example work? If it does, then "yes" but if it doesn't, then "maybe not" :) > And then should I be calling the reactor.fromthread in the SvcStop function. It has been a few years since I've used twisted, but I can't recall what that does. > If I import reactor in SvcDoRun will the SvcStop be called in the same > thread or not. Where you do the import doesn't impact this specific question; SvcStop will be almost certainly be called on a different thread than the main thread (ie, I'm pretty sure Windows itself always calls this on a different thread - python/pywin32/twisted have no say in this). > One of the examples import reactor globally, starts the reactor in > SvcDoRun - inside the thread - and in SvcStop, calls the > reactorfromthread. This to me implies that SvcStop is in a different > thread to SvcDoRun. But I could be completely wrong on this point. You are correct - it will be a different thread. But I think that the "run" function will be called on the same thread as the module import, so exactly when you import the twisted stuff probably doesn't matter - it sounds like you are just looking for a way to stop the reactor from a different thread (ie, from the SvcStop thread)? > > As you can see I am a little bit confused about what is happening here. > > > I have been looking for some info on running twisted as a Windows Service. > > I have found various examples in mailing-lists and blogs that vary in > what seem to be important respects. > > I have included them below as 3 examples. > > The problem I have is working out which scheme or combination I should > be adopting. > I have tried out some of the options and they appear to work. But I need > something better than seems to work. > > My gut reaction is that I should be putting all my imports into > SvcDoRun, since they will be used in the thread. Nope - the "top level" imports and the "run" function are almost certainly the same thread, and the "stop" function will be called on a thread created by Windows - but thread.get_ident() will tell you for sure. Hope this helps - but if you still have problems, post the shortest possible thing that doesn't work as you expect and I might be able to help more... Mark > > But if I import the reactor in SvcDoRun, should I be > using reactor.callfromthread(reactor.stop). I think not > > I think the use of waitforobject is the right thing to do as well > without fully understanding it at the moment. > > If anyone can throw some light on what to do I shall be very grateful. > > It could be that I should post this question to python-windows mailing > list since it seems to me more pertinent to windows than twisted. > > Thanks for any info. > > John Aherne > > Here is 1st example. > > The reactor is imported globally not in SvcDoRun > It uses the waitforobject to detect stopping the service > The reactor.stop is calledfromthread > > > [Twisted-Python] How to run Twisted as a service in Windows? > > Thomas Jacob jacob at internet24.de > Wed Aug 9 10:49:30 EDT 2006 > Previous message: [Twisted-Python] How to run Twisted as a service in > Windows? > Next message: [Twisted-Python] How to run Twisted as a service in Windows? > Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] > AFAIK, twistd doesn't provide direct support for Windows Services yet > (Is this planned?). > > But you can easily wrap a reactor,run() yourself by doing something > like the following using the Win32-Python packages > > import win32serviceutil > import win32service > import win32event > > from twisted.internet import reactor > > import sys > > > class IMSAgentBase(win32serviceutil.ServiceFramework): > _svc_name_ = "myService" > _svc_display_name_ = "My little Service" > _svc_description_ = "My little Service" # Win2k or later > _svc_deps_ = ["RpcSs"] # Start after the Network has come up... > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > reactor.callFromThread(reactor.stop) > win32event.SetEvent(self.hWaitStop) > > def SvcDoRun(self): > # initialize your services here > reactor.run() > win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE) > > def HandleCommandLine(cls): > win32serviceutil.HandleCommandLine(cls) > > > Run the above as a script. > > > Here is the 2nd example. > > The imports are global not in SvcDoRun > > And the reactor .stop is not called from thread. > > And the wait for stop event is in a timeout loop > > It uses waitforobject events > > It sets installsignalhandlers to 0 > > You can then test it out with the sample Echo client from the core docs. > """qotdservice.py > Sample Twisted Windows Service > """ > # Service Utilities > import win32serviceutil > import win32service > import win32event > # Twisted imports > from twisted.internet.protocol import Protocol, Factory > from twisted.internet import reactor > class QOTD(Protocol): > def connectionMade(self): > self.transport.write("An apple a day keeps the doctor away\r\n") > self.transport.loseConnection() > class WindowsService(win32serviceutil.ServiceFramework): > _svc_name_ = "TwistedWin32Service" > _svc_display_name_ = "Twisted Win32 Service" > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > win32event.SetEvent(self.hWaitStop) > def SvcDoRun(self): > import servicemanager > self.CheckForQuit() > factory = Factory() > factory.protocol = QOTD > reactor.listenTCP(8007, factory) > reactor.run(installSignalHandlers=0) > def CheckForQuit(self): > retval = win32event.WaitForSingleObject(self.hWaitStop, 10) > if not retval == win32event.WAIT_TIMEOUT: > # Received Quit from Win32 > reactor.stop() > reactor.callLater(1.0, self.CheckForQuit) > if __name__=='__main__': > win32serviceutil.HandleCommandLine(WindowsService) > > Here is the 3rd example. > > The imports are done in SvcDoRun. > There is no callfrom thread > It does not use the waitforobject > > import sys, os > import win32serviceutil, win32service > > class MyService(win32serviceutil.ServiceFramework): > """NT Service.""" > > _svc_name_ = "MyService" > _svc_display_name_ = "MyService server" > > def SvcDoRun(self): > import server > f = open(os.path.join(server.rootPath, "cyberhigh.log"), 'a') > from twisted.python.log import startLogging > from twisted.application.app import startApplication > from twisted.internet import reactor > startLogging(f) > startApplication(server.application, 0) > reactor.run() > > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > from twisted.internet import reactor > reactor.stop() > > if __name__ == '__main__': > win32serviceutil.HandleCommandLine(MyService) > > > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > http://mail.python.org/mailman/listinfo/python-win32 From johnaherne at rocs.co.uk Fri Oct 14 22:45:12 2011 From: johnaherne at rocs.co.uk (John Aherne) Date: Fri, 14 Oct 2011 21:45:12 +0100 Subject: [python-win32] windows service problem and twisted In-Reply-To: <4E982254.10803@gmail.com> References: <4E982254.10803@gmail.com> Message-ID: On Fri, Oct 14, 2011 at 12:51 PM, Mark Hammond wrote: > On 14/10/2011 7:47 PM, John Aherne wrote: > ... > > What I am trying to work out is should I import twisted.reactor etc >> inside the thread start in SvcDoRUn or import it globally as one of the >> examples does. >> > > Dunno - does the example work? If it does, then "yes" but if it doesn't, > then "maybe not" :) > > > And then should I be calling the reactor.fromthread in the SvcStop >> function. >> > > It has been a few years since I've used twisted, but I can't recall what > that does. > > > If I import reactor in SvcDoRun will the SvcStop be called in the same >> thread or not. >> > > Where you do the import doesn't impact this specific question; SvcStop will > be almost certainly be called on a different thread than the main thread > (ie, I'm pretty sure Windows itself always calls this on a different thread > - python/pywin32/twisted have no say in this). > > > One of the examples import reactor globally, starts the reactor in >> SvcDoRun - inside the thread - and in SvcStop, calls the >> reactorfromthread. This to me implies that SvcStop is in a different >> thread to SvcDoRun. But I could be completely wrong on this point. >> > > You are correct - it will be a different thread. But I think that the > "run" function will be called on the same thread as the module import, so > exactly when you import the twisted stuff probably doesn't matter - it > sounds like you are just looking for a way to stop the reactor from a > different thread (ie, from the SvcStop thread)? > > > >> As you can see I am a little bit confused about what is happening here. >> >> >> I have been looking for some info on running twisted as a Windows Service. >> >> I have found various examples in mailing-lists and blogs that vary in >> what seem to be important respects. >> >> I have included them below as 3 examples. >> >> The problem I have is working out which scheme or combination I should >> be adopting. >> I have tried out some of the options and they appear to work. But I need >> something better than seems to work. >> >> My gut reaction is that I should be putting all my imports into >> SvcDoRun, since they will be used in the thread. >> > > Nope - the "top level" imports and the "run" function are almost certainly > the same thread, and the "stop" function will be called on a thread created > by Windows - but thread.get_ident() will tell you for sure. > > Hope this helps - but if you still have problems, post the shortest > possible thing that doesn't work as you expect and I might be able to help > more... > > Mark > > >> But if I import the reactor in SvcDoRun, should I be >> using reactor.callfromthread(**reactor.stop). I think not >> >> I think the use of waitforobject is the right thing to do as well >> without fully understanding it at the moment. >> >> If anyone can throw some light on what to do I shall be very grateful. >> >> It could be that I should post this question to python-windows mailing >> list since it seems to me more pertinent to windows than twisted. >> >> Thanks for any info. >> >> John Aherne >> >> Here is 1st example. >> >> The reactor is imported globally not in SvcDoRun >> It uses the waitforobject to detect stopping the service >> The reactor.stop is calledfromthread >> >> >> [Twisted-Python] How to run Twisted as a service in Windows? >> >> Thomas Jacob jacob at internet24.de >> >> Wed Aug 9 10:49:30 EDT 2006 >> Previous message: [Twisted-Python] How to run Twisted as a service in >> Windows? >> Next message: [Twisted-Python] How to run Twisted as a service in Windows? >> Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] >> AFAIK, twistd doesn't provide direct support for Windows Services yet >> (Is this planned?). >> >> But you can easily wrap a reactor,run() yourself by doing something >> like the following using the Win32-Python packages >> >> import win32serviceutil >> import win32service >> import win32event >> >> from twisted.internet import reactor >> >> import sys >> >> >> class IMSAgentBase(win32serviceutil.**ServiceFramework): >> _svc_name_ = "myService" >> _svc_display_name_ = "My little Service" >> _svc_description_ = "My little Service" # Win2k or later >> _svc_deps_ = ["RpcSs"] # Start after the Network has come up... >> >> def __init__(self, args): >> win32serviceutil.**ServiceFramework.__init__(**self, args) >> self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) >> >> def SvcStop(self): >> self.ReportServiceStatus(**win32service.SERVICE_STOP_**PENDING) >> reactor.callFromThread(**reactor.stop) >> win32event.SetEvent(self.**hWaitStop) >> >> def SvcDoRun(self): >> # initialize your services here >> reactor.run() >> win32event.**WaitForSingleObject(self.** >> hWaitStop,win32event.INFINITE) >> >> def HandleCommandLine(cls): >> win32serviceutil.**HandleCommandLine(cls) >> >> >> Run the above as a script. >> >> >> Here is the 2nd example. >> >> The imports are global not in SvcDoRun >> >> And the reactor .stop is not called from thread. >> >> And the wait for stop event is in a timeout loop >> >> It uses waitforobject events >> >> It sets installsignalhandlers to 0 >> >> You can then test it out with the sample Echo client from the core docs. >> """qotdservice.py >> Sample Twisted Windows Service >> """ >> # Service Utilities >> import win32serviceutil >> import win32service >> import win32event >> # Twisted imports >> from twisted.internet.protocol import Protocol, Factory >> from twisted.internet import reactor >> class QOTD(Protocol): >> def connectionMade(self): >> self.transport.write("An apple a day keeps the doctor away\r\n") >> self.transport.loseConnection(**) >> class WindowsService(**win32serviceutil.**ServiceFramework): >> _svc_name_ = "TwistedWin32Service" >> _svc_display_name_ = "Twisted Win32 Service" >> def __init__(self, args): >> win32serviceutil.**ServiceFramework.__init__(**self, args) >> self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) >> def SvcStop(self): >> self.ReportServiceStatus(**win32service.SERVICE_STOP_**PENDING) >> win32event.SetEvent(self.**hWaitStop) >> def SvcDoRun(self): >> import servicemanager >> self.CheckForQuit() >> factory = Factory() >> factory.protocol = QOTD >> reactor.listenTCP(8007, factory) >> reactor.run(**installSignalHandlers=0) >> def CheckForQuit(self): >> retval = win32event.**WaitForSingleObject(self.**hWaitStop, 10) >> if not retval == win32event.WAIT_TIMEOUT: >> # Received Quit from Win32 >> reactor.stop() >> reactor.callLater(1.0, self.CheckForQuit) >> if __name__=='__main__': >> win32serviceutil.**HandleCommandLine(**WindowsService) >> >> Here is the 3rd example. >> >> The imports are done in SvcDoRun. >> There is no callfrom thread >> It does not use the waitforobject >> >> import sys, os >> import win32serviceutil, win32service >> >> class MyService(win32serviceutil.**ServiceFramework): >> """NT Service.""" >> >> _svc_name_ = "MyService" >> _svc_display_name_ = "MyService server" >> >> def SvcDoRun(self): >> import server >> f = open(os.path.join(server.**rootPath, "cyberhigh.log"), 'a') >> from twisted.python.log import startLogging >> from twisted.application.app import startApplication >> from twisted.internet import reactor >> startLogging(f) >> startApplication(server.**application, 0) >> reactor.run() >> >> def SvcStop(self): >> self.ReportServiceStatus(**win32service.SERVICE_STOP_**PENDING) >> from twisted.internet import reactor >> reactor.stop() >> >> if __name__ == '__main__': >> win32serviceutil.**HandleCommandLine(MyService) >> >> >> >> ______________________________**_________________ >> python-win32 mailing list >> python-win32 at python.org >> http://mail.python.org/**mailman/listinfo/python-win32 >> > > Mark Thanks for the response Yes you spotted what I wanted to do but didn't spell out. I want to stop the reactor from the thread in SvcStop. It helped clarify my thoughts. What I found was that I could stop the reactor whether I used callfromthread or not. It all worked regardless. What concerned me was that I wasn't sure that SvcStop was running in another thread. Now I know it is and because the reactor is not threadsafe, I should use callfromthread to be really sure and to avoid possible future problems. So thanks, but if I run into more problems I may have to come back with other questions. John Aherne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfman1313 at hotmail.com Sat Oct 15 03:24:49 2011 From: wolfman1313 at hotmail.com (dwayne owen) Date: Fri, 14 Oct 2011 20:24:49 -0500 Subject: [python-win32] pyhton card Message-ID: I have been trying to to run python card but it?s not in to my s start mine u can some one help -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfman1313 at hotmail.com Sat Oct 15 04:23:21 2011 From: wolfman1313 at hotmail.com (dwayne owen) Date: Fri, 14 Oct 2011 21:23:21 -0500 Subject: [python-win32] python card Message-ID: I have just download python card and I don?t know it is me but I am not get it in my start programs menu I have read the start ups and the read me but I can not get to start up want do I do and I do not see code Editor I 'am going by the book Beginning python Peter Norton,Alex Samuel,David Aitel and all them so if you can help that would be grate think you and god bless wolfmana1313 at hotmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at slimmersoft.com Sat Oct 15 19:21:46 2011 From: max at slimmersoft.com (Max Slimmer) Date: Sat, 15 Oct 2011 10:21:46 -0700 Subject: [python-win32] python card In-Reply-To: References: Message-ID: pythoncard is not an application it is a library that contains some tools to enable you to create gui applications if I recall by dragging components onto a canvas. I will never put anything into start menu. Go to http://pythoncard.sourceforge.net/windows_installation.html and follow all the steps including installing python wxpython and pythoncard, then do the step in Confirming Installation, "Open the folder called "minimal" in Python25\Lib\site-packages\PythonCard\samples. Find the icon labeled minimal.py and double-click it" this should popup a sample app you will also find tutorial etc on this site. max On Fri, Oct 14, 2011 at 7:23 PM, dwayne owen wrote: > I have just download python card and I don?t know it is me but I am not > get it in my start programs menu I have read the start ups and the read me > but I can not get to start up want do I do and I do not see code Editor I > 'am going by the book Beginning python Peter Norton,Alex Samuel,David Aitel > and all them so if you can help that would be grate > > > > > > > > > > > > > > > think you and god bless > > wolfmana1313 at hotmail.com > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > http://mail.python.org/mailman/listinfo/python-win32 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacobk at mailzone.co.za Tue Oct 18 16:13:01 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Tue, 18 Oct 2011 16:13:01 +0200 Subject: [python-win32] GUI interface for my small RPG applets Message-ID: Done using a layout by code module, called LBC, but also noted that, for example, you can add standard wxPython controls as children to things like the lbc.Dialog as well if you want/need to, but anyway. The front-end is here: http://www.blindza.co.za/uploads/mapData/mapDataLBC_dist/mapDataLBC_dist.zip and, the backend/generator applet is here: http://www.blindza.co.za/uploads/mapData/mapDataLBC_dist/mapDataGenLBC_dist.zip I also have the pyc (python compiled versions), but not sure they'll work on linux/mac machines as of yet, since haven't been able to test it as of yet. However, here's the python source: http://www.blindza.co.za/uploads/mapData/mapDataLBC_src/mapDataLBC_src.zip Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacobk at mailzone.co.za Wed Oct 19 07:07:46 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Wed, 19 Oct 2011 07:07:46 +0200 Subject: [python-win32] The opposite of a wxPython's SetFocus() method? Message-ID: Just wondering if therre's something similar to invoking a sort of blur effect to remove focus from a control before returning it to that control? This is partly that since with a screenreader already focused on a control, it won't necessarily render/mention updates to that control by default, but might if could take focus away from the control, and then return it after having made the changes to it's contents, etc., but without (preferably) having focused on another specific screen area inbetween, since that would then also most likely get rendered inbetween, if you know what I mean. Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' -------------- next part -------------- An HTML attachment was scrubbed... URL: From esj at harvee.org Sat Oct 22 09:34:57 2011 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 22 Oct 2011 03:34:57 -0400 Subject: [python-win32] need python+windows edit control help Message-ID: <4EA27221.8090501@harvee.org> I need some help from a win32/rich text edit control wizard. I'm looking for a mentoring/code template generation relationship. In a nutshell, I have RSI crippled hands which means writing code is a challenge and I'm totally unschooled in the ways of windowing systems. I'm working on techniques to make it possible to write code using speech recognition and I could use some help with the GUI aspect so I can focus on the speech user interface component. The core idea is pairing a speech user interface with an application via an accessibility adjunct program. This differs from the current model in that it moves the speech user interface outside of the application so that it is no longer bound by conventions of the application or the application's GUI structure. the reason for this change comes from a hunch that it would make it easier to create good speech user interfaces faster than the current in-situ UI techniques. the transition between application and speech UI starts when an utterance is detected and ends when the utterance ends. the transition consists of changing focus from the application to the paired speech UI. The speech UI component also has a GUI for accepting and presenting data. In most applications, the data is processed incrementally with intermediary results visible within the window. The incrementally processed data is usually hints as to what to say next. For example, if you are changing the directory and specify partial pathname, the window would contain options of what to say next. In my minds eye, I imagine that the window would contain a grid like a spreadsheet or table. Only one cell at a time would be active for data input and the active cell would receive all dictation input and commands. Any number of cells could be used for data input but only one would be active at a single time. How would this be used? For example, the Skype IM window is atrocious for disabled users. If one associated a two cell speech UI window with Skype, the user could dictate, edit, retrain, etc. within the speech UI program. On command, the speech UI program would return the text to Skype. One could also contain a small history so that like Skype, you could go back and edit a previously sent message. a second use case is found on my blog http://blog.esjworks.com which is the tool to create mangled codenames from speech. I think the grid model works better than individual text fields that I originally wrote because it allows me to make better presentation of a cache of previously generated symbols. Anyway, if anybody can help with the windowing side, I would really appreciate some assistance. --- eric From roberto.c.aguilar at gmail.com Mon Oct 24 20:56:51 2011 From: roberto.c.aguilar at gmail.com (Roberto Aguilar) Date: Mon, 24 Oct 2011 11:56:51 -0700 Subject: [python-win32] Error launching python.exe [The application failed to initialize properly (0x0150002)] Message-ID: Hello, I work on a Python application that runs on Windows. Lately we've been seeing a strange error pop up on a few installations (say 10 out of ~2000). When launching Python the following error pops up in a windows dialog: The application failed to initialize properly (0x0150002) Searching the internet, I don't see many posts about this error and none are very definitive. The closest, not-so-relevant post deals with compiler incompatibility [1]. There are a couple of gotchas: - Sometimes python starts working again. This seems to eliminate any compiler incompatibility. - These machines are not in a controlled environment; I don't have control over what is installed or removed, e.g. windows updates, install/uninstall 3rd party applications, etc. Has anyone else seen this problem? Any tips or pointers are most welcome. Thanks, -Roberto. [1] http://comments.gmane.org/gmane.comp.video.blender.devel/29365 From pacopyc at gmail.com Wed Oct 26 08:57:03 2011 From: pacopyc at gmail.com (pacopyc pacopyc) Date: Wed, 26 Oct 2011 08:57:03 +0200 Subject: [python-win32] retrieve microsoft office product key Message-ID: Hi, I'd like monitor microsoft office licences on my LAN (about 50 PC). Can I retrieve product key with python script? Thank you pacopyc -------------- next part -------------- An HTML attachment was scrubbed... URL: From reckoner at gmail.com Wed Oct 26 17:51:48 2011 From: reckoner at gmail.com (reckoner) Date: Wed, 26 Oct 2011 08:51:48 -0700 Subject: [python-win32] How to wait for context menu (i.e. right-click menu) pop-up? Message-ID: <4EA82C94.3070000@gmail.com> Hi, A script needs something on the context menu ( obtained either by right-click or by appskey ). The trouble is that sometimes the pop-up context menu takes an unpredictable time to load, so I need a way of detecting whether or not the context menu is ready for subsequent actions before the rest of the script can run. Any way to do detect the availability of this context menu? Thanks! From timr at probo.com Wed Oct 26 18:43:05 2011 From: timr at probo.com (Tim Roberts) Date: Wed, 26 Oct 2011 09:43:05 -0700 Subject: [python-win32] retrieve microsoft office product key In-Reply-To: References: Message-ID: <4EA83899.9040901@probo.com> pacopyc pacopyc wrote: > Hi, I'd like monitor microsoft office licences on my LAN (about 50 > PC). Can I retrieve product key with python script? The question is complicated, because Microsoft's licensing model is complicated. Do you have a volume license key that you're trying to monitor, or are these individual copies? There are a large number of scripts to do this kind of monitoring, so your best bet is going to be some deep web searching. Most of your results will be vbscript or PowerShell, so you'll have to do some translation, but anything they can do can be done in Python. Here is an example for Office 2010 volume licenses: http://blogs.technet.com/b/office2010/archive/2009/12/18/volume-activation-tips-and-tricks.aspx -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jacobk at mailzone.co.za Thu Oct 27 05:48:56 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Thu, 27 Oct 2011 05:48:56 +0200 Subject: [python-win32] Restart/re-run a thread Message-ID: Trying out/testing the use of multiple threading.Thread objects to play sounds using winsound.PlaySound function, and in order to be able to play multiple sounds at the same time/near enough to each other, I am trying out implementing a separate thread to call the function that handles this, but just wondering about the easiest way to then restart/rerun a thread, and/or if it's really possible/viable to in fact stop a thread while/if it's running..? Have it currently set to recreate a new thread each time I want it to in fact play a sound, and while this doesn't seem to thus far have made the python.exe task start to build up it's memory usage etc. in the task manager, I would just think that you could at the least, either stop a thread if it's currently running (threading.Thread.isAlive)() function) and/or then restart it, but it seems to want to then return an exception that the thread can't be restarted? Alternatively, I suppose I could also assign each thread to a class that then replays the winsound object, or something, but just wondering in general if there's an easier way to stop/restart a Thread object/item? Lastly, it otherwise seems quite happy/comfortable to run multiple threads/play multiple sounds at the same time/near enough to each other, which is nice. TIA Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' -------------- next part -------------- An HTML attachment was scrubbed... URL: From bxfree at gmail.com Thu Oct 27 08:52:25 2011 From: bxfree at gmail.com (Anton Kurbatov) Date: Thu, 27 Oct 2011 10:52:25 +0400 Subject: [python-win32] win32gui.GetCursorInfo: TypeError: function takes no arguments Message-ID: May you help me, pls... I am using win7 ultimate. Installed version of python 2.5.1.1. (ActivePython with pywin32) I get the following msg: >>> import win32gui >>> print win32gui.GetCursorInfo() Traceback (most recent call last): File "", line 1, in TypeError: function takes no arguments >>> This is a bug? -- Best regards, ?Kurbatov Anton? ? ? ? ? ? ? ? ? ? ? ? mailto:bxfree at gmail.com From pehr.meldert at smhi.se Thu Oct 27 12:00:54 2011 From: pehr.meldert at smhi.se (Meldert Pehr) Date: Thu, 27 Oct 2011 10:00:54 +0000 Subject: [python-win32] printing image in colour? Message-ID: <647290BB66CABE42ADAB0E5ACE54C89005A262@WINSERV302.ad.smhi.se> Hi! I'm testing Tims script from this site: http://timgolden.me.uk/python/win32_how_do_i/print.html to print a test image, and it works however, it is in greyscale Does anyone know how to print the test-image in colour? Brgds - Pehr Meldert -------------- next part -------------- An HTML attachment was scrubbed... URL: From imageguy1206 at gmail.com Thu Oct 27 15:47:21 2011 From: imageguy1206 at gmail.com (geoff) Date: Thu, 27 Oct 2011 08:47:21 -0500 Subject: [python-win32] Restart/re-run a thread In-Reply-To: References: Message-ID: The python docs are pretty clear that there is no way to external stop a thread and this was a design decision. Typically, I have used a threading.Event to control the actions of the worker threads from a loop in the main program. Setup each worker thread as a loop using the event.wait() method to block the loop. When you are ready for all of the threads to proceed, use the controller thread and event.set(). All of the worker threads will exit the blocking state of their loop and proceed with execution. Once finished, they return to the event.wait() mode. To stop the threads, I typically use another thread.Event object called "keepgoing" and test for that at the top of the worker threads processing loop. When the threads have finished processing and you want them to stop, you can set the keepgoing event to false. The example below is from memory, so be careful; keepgoing = threading.Event() keepgoing.set() # evaluates to True startprocess = threading.Event() startprocess.clear() # evaluates to False class worker(threading.Thread): def __init__(self, keepgoing, startprocess): while keepgoing: if startprocess: ... do someprocessing here else: startprocess.wait() #blocks the thread waiting for the event to be set. Note that if you need to pass objects into the worker thread, I would suggest placing in a collections.deque. One the startprocess is set, you can use deque.pop() to take the object out of the deque in a thread safe way. Hope this helps. BTW, I am not sure if this is for education purposes or for production, but debugging threads is REALLY HARD, so make sure this is something you really need to do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From btimby at gmail.com Thu Oct 27 16:31:17 2011 From: btimby at gmail.com (Ben Timby) Date: Thu, 27 Oct 2011 10:31:17 -0400 Subject: [python-win32] Restart/re-run a thread In-Reply-To: References: Message-ID: Jacob, What you are looking at is called a thread pool. The simple case you have now is that you start a thread whenever there is work to do (playing a sound). The thread does this work, then exits. A thread pool means you have a set number of threads idling and receiving work via a queue. When work appears, they perform it and then go back to idle. There are thread pool implementations for Python that you could simply plug into your application. from multiprocessing.pool import ThreadPool http://code.activestate.com/recipes/203871-a-generic-programming-thread-pool/ In either case, if you are looking to kill off a thread midway through the work (cut off the sound before it is done playing). Then you will need to use a flag to inform the thread that you wish for it to stop playing sound. This means you need a polling loop that will play a short sample of the track and then check the flag before playing the next sample. This way the thread can exit part of the way through the sound. A thread pool will not save memory. It saves the setup/teardown of threads. This is a relatively expensive process, and if an application starts hundreds of thousands of threads during it's lifetime, this adds up. Think about it, either way, you will need a number of concurrent threads that equals the number of sounds you wish to play concurrently. This means a thread pool will have X threads active (though idle) at all times. The simple case will have X threads active (and working) only while the sounds are being played. The only real advantage of the thread pool is that it avoids setup/teardown, so it could possibly save some latency when playing a new sound. This is because a new thread does not need to be initialized, it just has to wake up and start playing the sound. You have to decide if this latency is a problem and if so, go the thread pool route. Of course, Python threads are not native threads, so I think any advantage here probably washes out. My suggestion is to stick with the simple case. A simple sound player class can do the whole task for you, and your code will be much easier to follow and debug. Throwing a thread pool into the mix will complicate things. Simple case: class PlaySound(threading.Thread): def __init__(self, sound='foobar.wav'): self.sound = sound self.running = True self.sample = 0 threading.Thread.__init__(self): self.start() def playsample(self): soundlib.play(self.sound, startms=self.sample*100, lengthms=100) self.sample += 100 def run(self): while self.running: self.playsample() def stop(self): self.running = False s = PlaySound('explosion.wav') if user_exited: s.stop() The main key here is that instead of playing the whole sound file in one shot, you play only a small portion of it between polls. This way the thread can stop mid-sound. You need to use a sound library that will support breaking a sound into multiple parts in order to achieve this. Another option here is to ditch threads altogether and find a sound library that does async playback. Let it handle this mess for you. http://docs.python.org/library/winsound.html From jacobk at mailzone.co.za Thu Oct 27 16:47:47 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Thu, 27 Oct 2011 16:47:47 +0200 Subject: [python-win32] Restart/re-run a thread In-Reply-To: References: Message-ID: <272433C1D16B4F45A0F24CDAE4F51218@jakes> Thanks. What have also found that seems nice/usable enough is to sort of implement a class that inherits from threading.Thread, and then it runs the class's functionality in the threaded background, and you can define other functions and variables to check state if you want to - something like the following - off the top of my head: #---start of code--- import threading, time class myClass(threading.Thread): counter = -1 def __init__(self): self.counter = 0 threading.Thread.__init__(self) def getCount(self): return self.counter def run(self): while self.counter < 60: self.counter += 1 time.sleep(1) #---end of code--- The partial point is this one will be initiated, but when you then tell your instance of the class/object to start(), it sort of automatically tells itself to run(), and you can call the getCount() function to get the value of it's internal counter variable, etc. - simple example, but seems to work well enough, if you get my/the drift, and, what have pretty much found all over the 'net is that you get told not to try destroy anything manually/yourself, but anyway. Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' ----- Original Message ----- From: geoff To: Jacob Kruger Cc: python-win32 at python.org Sent: Thursday, October 27, 2011 3:47 PM Subject: Re: [python-win32] Restart/re-run a thread The python docs are pretty clear that there is no way to external stop a thread and this was a design decision. Typically, I have used a threading.Event to control the actions of the worker threads from a loop in the main program. Setup each worker thread as a loop using the event.wait() method to block the loop. When you are ready for all of the threads to proceed, use the controller thread and event.set(). All of the worker threads will exit the blocking state of their loop and proceed with execution. Once finished, they return to the event.wait() mode. To stop the threads, I typically use another thread.Event object called "keepgoing" and test for that at the top of the worker threads processing loop. When the threads have finished processing and you want them to stop, you can set the keepgoing event to false. The example below is from memory, so be careful; keepgoing = threading.Event() keepgoing.set() # evaluates to True startprocess = threading.Event() startprocess.clear() # evaluates to False class worker(threading.Thread): def __init__(self, keepgoing, startprocess): while keepgoing: if startprocess: ... do someprocessing here else: startprocess.wait() #blocks the thread waiting for the event to be set. Note that if you need to pass objects into the worker thread, I would suggest placing in a collections.deque. One the startprocess is set, you can use deque.pop() to take the object out of the deque in a thread safe way. Hope this helps. BTW, I am not sure if this is for education purposes or for production, but debugging threads is REALLY HARD, so make sure this is something you really need to do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacobk at mailzone.co.za Thu Oct 27 17:03:35 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Thu, 27 Oct 2011 17:03:35 +0200 Subject: [python-win32] Restart/re-run a thread In-Reply-To: References: Message-ID: Thanks. winsound.PlaySound("file.wav", winsound.SND_ASYNC) Does handle it asynchronously, but, yes, thanks for complete example. Am in any case still trying to find/get hold of a sound library of some sort that will do a bit more, like I want it to, and one called pyaudiere works fine on my windows7 32bit machine, but refuses to work on my windows7 64bit machine, same as another wrapper module called sound_lib - and main thing I would like, apart from just playing/stopping/pausing sounds is to be able to handle a little bit of 3D, like panning playback etc., but not end of the world thus far. Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' ----- Original Message ----- From: "Ben Timby" To: Sent: Thursday, October 27, 2011 4:31 PM Subject: Re: [python-win32] Restart/re-run a thread > Jacob, > > What you are looking at is called a thread pool. The simple case you > have now is that you start a thread whenever there is work to do > (playing a sound). The thread does this work, then exits. A thread > pool means you have a set number of threads idling and receiving work > via a queue. When work appears, they perform it and then go back to > idle. > > There are thread pool implementations for Python that you could simply > plug into your application. > > from multiprocessing.pool import ThreadPool > > http://code.activestate.com/recipes/203871-a-generic-programming-thread-pool/ > > In either case, if you are looking to kill off a thread midway through > the work (cut off the sound before it is done playing). Then you will > need to use a flag to inform the thread that you wish for it to stop > playing sound. This means you need a polling loop that will play a > short sample of the track and then check the flag before playing the > next sample. This way the thread can exit part of the way through the > sound. > > A thread pool will not save memory. It saves the setup/teardown of > threads. This is a relatively expensive process, and if an application > starts hundreds of thousands of threads during it's lifetime, this > adds up. Think about it, either way, you will need a number of > concurrent threads that equals the number of sounds you wish to play > concurrently. This means a thread pool will have X threads active > (though idle) at all times. The simple case will have X threads active > (and working) only while the sounds are being played. The only real > advantage of the thread pool is that it avoids setup/teardown, so it > could possibly save some latency when playing a new sound. This is > because a new thread does not need to be initialized, it just has to > wake up and start playing the sound. You have to decide if this > latency is a problem and if so, go the thread pool route. Of course, > Python threads are not native threads, so I think any advantage here > probably washes out. My suggestion is to stick with the simple case. > > A simple sound player class can do the whole task for you, and your > code will be much easier to follow and debug. Throwing a thread pool > into the mix will complicate things. > > Simple case: > > class PlaySound(threading.Thread): > def __init__(self, sound='foobar.wav'): > self.sound = sound > self.running = True > self.sample = 0 > threading.Thread.__init__(self): > self.start() > > def playsample(self): > soundlib.play(self.sound, startms=self.sample*100, lengthms=100) > self.sample += 100 > > def run(self): > while self.running: > self.playsample() > > def stop(self): > self.running = False > > s = PlaySound('explosion.wav') > if user_exited: > s.stop() > > The main key here is that instead of playing the whole sound file in > one shot, you play only a small portion of it between polls. This way > the thread can stop mid-sound. You need to use a sound library that > will support breaking a sound into multiple parts in order to achieve > this. > > Another option here is to ditch threads altogether and find a sound > library that does async playback. Let it handle this mess for you. > > http://docs.python.org/library/winsound.html > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > http://mail.python.org/mailman/listinfo/python-win32 From jacobk at mailzone.co.za Thu Oct 27 18:27:20 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Thu, 27 Oct 2011 18:27:20 +0200 Subject: [python-win32] Restart/re-run a thread In-Reply-To: References: Message-ID: <9B106325B1DC4C398CE410A41F56E681@jakes> Will check it out, but will also just say that a few of the game libraries I have looked at already are of no interest to me, since they produce inaccessible output/interfaces, but, will look into them a bit more for sound output...:) Have also gotten hold of another, sort of TTS module/wrapper that makes use of actual screen reader voices in meantime, and which works with python 2.7, which is what am using at the moment, but anyway: http://hg.qwitter-client.net/accessible_output/ Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' ----- Original Message ----- From: "Ben Timby" To: "Jacob Kruger" Sent: Thursday, October 27, 2011 5:34 PM Subject: Re: [python-win32] Restart/re-run a thread > Jacob, > > May be getting a bit off topic here :-). However, for 3D sound, look > for python game libraries. For cross-platform 3D sound, it looks like > you might want FMOD. There is pySonic, a python wrapper for FMOD. > > http://pysonic.sourceforge.net/ > > FMOD is non-free. However, it is gratis for non-commercial use. I am > sure there are other options as well, but I suggest looking for > libraries geared toward "games" since they will have the features you > apparently need. > > Good luck! From jacobk at mailzone.co.za Thu Oct 27 23:01:48 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Thu, 27 Oct 2011 23:01:48 +0200 Subject: [python-win32] Ok, reinstalled complete win32 set of packages/modules and now all sound/interface elements seem to be working on this windows7 64bit machine Message-ID: <8F5577A0EF264288A14C9D0CC54492CD@jakes> I installed in effectively the following order - dunno why before I seemed to need to install specifically the amr64bit installations, but anyway - what it now means is both pyaudiere and sound_lib sort of 3D sound packages will now work on this machine, under python27 32bit installation: Install packages: python-2.7.msi py2exe-0.6.9.win32-py2.7.exe pywin32-216.win32-py2.7.exe numpy-1.6.1-win32-superpack-python2.7.exe pyaudiere-0.2.win32-py2.7.msi I then installed the following packages by running their setup.py code with the install option: python setup.py install distribute-0.6.19 #http://packages.python.org/distribute/ platform_utils #http://hg.qwitter-client.net/platform_utils accessible_output #http://hg.qwitter-client.net/accessible_output sound_lib #http://hg.qwitter-client.net/sound_lib Both pyaudiere and sound_lib are sort of audio modules with some 3D support, and sound_lib seems to make use of the base24 component - you seem to just need to copy the base.dll file that's included in downloads from the following site into the relevant lib/site_packages.../sound_lib folder: http://www.un4seen.com/ Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacobk at mailzone.co.za Fri Oct 28 07:52:16 2011 From: jacobk at mailzone.co.za (Jacob Kruger) Date: Fri, 28 Oct 2011 07:52:16 +0200 Subject: [python-win32] Ok, reinstalled complete win32 set of packages/modules and now allsound/interface elements seem to be working on this windows764bit machine In-Reply-To: <8F5577A0EF264288A14C9D0CC54492CD@jakes> References: <8F5577A0EF264288A14C9D0CC54492CD@jakes> Message-ID: <5AD45F12D19A40E49A05DC6771C077E5@jakes> Oh yes, and another module is the wxPython keyboard_handler: http://hg.qwitter-client.net/keyboard_handler Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' ----- Original Message ----- From: Jacob Kruger To: python-win32 at python.org Sent: Thursday, October 27, 2011 11:01 PM Subject: [python-win32] Ok,reinstalled complete win32 set of packages/modules and now allsound/interface elements seem to be working on this windows764bit machine I installed in effectively the following order - dunno why before I seemed to need to install specifically the amr64bit installations, but anyway - what it now means is both pyaudiere and sound_lib sort of 3D sound packages will now work on this machine, under python27 32bit installation: Install packages: python-2.7.msi py2exe-0.6.9.win32-py2.7.exe pywin32-216.win32-py2.7.exe numpy-1.6.1-win32-superpack-python2.7.exe pyaudiere-0.2.win32-py2.7.msi I then installed the following packages by running their setup.py code with the install option: python setup.py install distribute-0.6.19 #http://packages.python.org/distribute/ platform_utils #http://hg.qwitter-client.net/platform_utils accessible_output #http://hg.qwitter-client.net/accessible_output sound_lib #http://hg.qwitter-client.net/sound_lib Both pyaudiere and sound_lib are sort of audio modules with some 3D support, and sound_lib seems to make use of the base24 component - you seem to just need to copy the base.dll file that's included in downloads from the following site into the relevant lib/site_packages.../sound_lib folder: http://www.un4seen.com/ Stay well Jacob Kruger Blind Biker Skype: BlindZA '...fate had broken his body, but not his spirit...' ------------------------------------------------------------------------------ _______________________________________________ python-win32 mailing list python-win32 at python.org http://mail.python.org/mailman/listinfo/python-win32 -------------- next part -------------- An HTML attachment was scrubbed... URL: From wws_ques at yahoo.com Sat Oct 29 03:25:03 2011 From: wws_ques at yahoo.com (love python) Date: Fri, 28 Oct 2011 18:25:03 -0700 (PDT) Subject: [python-win32] win32com in a 64bit laptop Message-ID: <32741987.post@talk.nabble.com> I just got a 64bit laptop and install python 2.7.2 (Windows AMD64 / Intel 64 / X86-64 binary) and other packages. When i run the previous file, I find to import win32com.client bc the program needs to read a word document as follows: app = win32com.client.gencache.EnsureDispatch('Word.Application') self.doc = app.Documents.Open(...) Can someone tell me how I should do here? Thanks. Bill -- View this message in context: http://old.nabble.com/win32com-in-a-64bit-laptop-tp32741987p32741987.html Sent from the Python - python-win32 mailing list archive at Nabble.com. From skippy.hammond at gmail.com Sat Oct 29 03:33:08 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sat, 29 Oct 2011 12:33:08 +1100 Subject: [python-win32] win32gui.GetCursorInfo: TypeError: function takes no arguments In-Reply-To: References: Message-ID: <4EAB57D4.70307@gmail.com> On 27/10/2011 5:52 PM, Anton Kurbatov wrote: > May you help me, pls... > > I am using win7 ultimate. Installed version of python 2.5.1.1. > (ActivePython with pywin32) > > I get the following msg: > >>>> import win32gui >>>> print win32gui.GetCursorInfo() > Traceback (most recent call last): > File "", line 1, in > TypeError: function takes no arguments >>>> > > This is a bug? Strange - it works for me: >>> import win32gui >>> win32gui.GetCursorInfo() (1, 65545L, (684, 703)) >>> Mark From skippy.hammond at gmail.com Sat Oct 29 03:36:51 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sat, 29 Oct 2011 12:36:51 +1100 Subject: [python-win32] win32com in a 64bit laptop In-Reply-To: <32741987.post@talk.nabble.com> References: <32741987.post@talk.nabble.com> Message-ID: <4EAB58B3.3090802@gmail.com> If your version of Word is 32bit (which it probably is), you should just stick with the 32bit version of Python - it works fine on a 64bit machine. HTH, Mark On 29/10/2011 12:25 PM, love python wrote: > > I just got a 64bit laptop and install python 2.7.2 (Windows AMD64 / Intel 64 > / X86-64 binary) and other packages. When i run the previous file, I find to > import win32com.client bc the program needs to read a word document as > follows: > > app = win32com.client.gencache.EnsureDispatch('Word.Application') > self.doc = app.Documents.Open(...) > > Can someone tell me how I should do here? Thanks. > Bill From wws_ques at yahoo.com Sat Oct 29 21:50:36 2011 From: wws_ques at yahoo.com (love python) Date: Sat, 29 Oct 2011 12:50:36 -0700 (PDT) Subject: [python-win32] win32com in a 64bit laptop In-Reply-To: <4EAB58B3.3090802@gmail.com> References: <32741987.post@talk.nabble.com> <4EAB58B3.3090802@gmail.com> Message-ID: <32745032.post@talk.nabble.com> Thanks for the reply. I removed the Softwares and reinstall them with 32bit again. But I have the following questions: 1. When installing xlutils1.4.1.win32, I got the following errors: couldn't create key for i) xlutils-py2.7; ii) python 2.7 xltuils-1.4.1 Then I got the error "Couldn't set key value" for "...\Removexlutils.exe" -u "...\xltuils-wininst.log" 2. Next, when installing win32com, i got the following error msg twice: The program can't start because python23.dll is missing from your computer... When I run my previous program, I got a runtime error as follows: Traceback (most recent call last): File "J:\MyProjects\Python\MySVD\src\SVDDecomposition.py", line 19, in from xlutils.copy import copy File "F:\Softwares\Working\Languages\Python27\lib\site-packages\xlutils\copy.py", line 7, in from xlutils.filter import process,XLRDReader,XLWTWriter File "F:\Softwares\Working\Languages\Python27\lib\site-packages\xlutils\filter.py", line 9, in import xlrd,xlwt ImportError: No module named xlwt How can I fix it? Thanks. Bill Mark Hammond-4 wrote: > > If your version of Word is 32bit (which it probably is), you should just > stick with the 32bit version of Python - it works fine on a 64bit machine. > > HTH, > > Mark > > -- View this message in context: http://old.nabble.com/win32com-in-a-64bit-laptop-tp32741987p32745032.html Sent from the Python - python-win32 mailing list archive at Nabble.com. From mc at mclaveau.com Sun Oct 30 13:48:49 2011 From: mc at mclaveau.com (Michel Claveau) Date: Sun, 30 Oct 2011 13:48:49 +0100 Subject: [python-win32] win32com in a 64bit laptop In-Reply-To: <32745032.post@talk.nabble.com> References: <32741987.post@talk.nabble.com> <4EAB58B3.3090802@gmail.com> <32745032.post@talk.nabble.com> Message-ID: <6F0748648F2C42F09CC3AD2D20DA9784@M14> Hi! > Python27 > The program can't start because python23.dll... Perhaps a bad version of pywin32... @-salutations -- Michel Claveau From wws_ques at yahoo.com Sun Oct 30 14:51:55 2011 From: wws_ques at yahoo.com (love python) Date: Sun, 30 Oct 2011 06:51:55 -0700 (PDT) Subject: [python-win32] win32com in a 64bit laptop In-Reply-To: <6F0748648F2C42F09CC3AD2D20DA9784@M14> References: <32741987.post@talk.nabble.com> <4EAB58B3.3090802@gmail.com> <32745032.post@talk.nabble.com> <6F0748648F2C42F09CC3AD2D20DA9784@M14> Message-ID: <32747181.post@talk.nabble.com> I got python from: www.python.org/download and choose ?Python 2.7.2 Windows Installer (Windows binary -- does not include source) It should be a good version too, right? What I did is to remove all the 64bit versions and reinstall these software systems for win32. Thanks in advance. Bill Michel Claveau wrote: > > Hi! > >> Python27 >> The program can't start because python23.dll... > > Perhaps a bad version of pywin32... > > @-salutations > -- > Michel Claveau > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > http://mail.python.org/mailman/listinfo/python-win32 > > -- View this message in context: http://old.nabble.com/win32com-in-a-64bit-laptop-tp32741987p32747181.html Sent from the Python - python-win32 mailing list archive at Nabble.com. From python at bdurham.com Mon Oct 31 21:01:45 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 31 Oct 2011 16:01:45 -0400 Subject: [python-win32] Detecting user (in)activity and changing process prioritization? Message-ID: <1320091305.8210.140660992869745@webmail.messagingengine.com> Is there a way to detect user (in)activity so that a program I have running in the background might use more system resources when a user isn't actively using their system and when user activity is detected, run in a more resource friendly mode? On a related note, is it possible to change the priority of a running process, or can the priority of a Windows process only be set when the process is launched? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Mon Oct 31 21:12:47 2011 From: timr at probo.com (Tim Roberts) Date: Mon, 31 Oct 2011 13:12:47 -0700 Subject: [python-win32] Detecting user (in)activity and changing process prioritization? In-Reply-To: <1320091305.8210.140660992869745@webmail.messagingengine.com> References: <1320091305.8210.140660992869745@webmail.messagingengine.com> Message-ID: <4EAF013F.4030802@probo.com> python at bdurham.com wrote: > Is there a way to detect user (in)activity so that a program I have > running in the background might use more system resources when a user > isn't actively using their system and when user activity is detected, > run in a more resource friendly mode? > > On a related note, is it possible to change the priority of a running > process, or can the priority of a Windows process only be set when the > process is launched? Changing the priority is exactly the way to do this. http://code.activestate.com/recipes/496767/ -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc.