From rjd254 at njms.rutgers.edu Wed Mar 1 01:35:04 2023 From: rjd254 at njms.rutgers.edu (Ryan Dikdan) Date: Wed, 1 Mar 2023 06:35:04 +0000 Subject: [python-win32] How to add citations to a word document Message-ID: Hello, I'm not sure how this mailing list works for support, but I'm trying to make a python script that formats downloaded citations and inserts them into word (avoiding all the hassle of external citation managers). I found pywin32 as the only way, but the documentation on doc.Bibliography.Sources.Add is scarce, so I was wondering if you all could help me. I have properly formatted xml of sources (since I could upload it to the source manager successfully, even though I think it's encoded in utf8 bom or sig or something). But whenever I put either the string of that content or the filename into the above Add() command in python it says the XML isn't formatted properly. I'd appreciate any help. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at manross.net Wed Mar 1 18:43:04 2023 From: steven at manross.net (Steven Manross) Date: Wed, 1 Mar 2023 23:43:04 +0000 Subject: [python-win32] How to add citations to a word document In-Reply-To: References: Message-ID: <0a10480d87144fffb66ae034fc3f4d41@manross.net> I'd probably start by creating a test Word document and adding a source manually in it from the Word GUI. Then, I would likely want to do something like this in python. # Sample python to list the bibliography entries import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") for source in doc.Bibliography.Sources: print("source: " + source.XML) # Now save the XML as a variable: myxml = source.XML wordapp.Quit() That should give you the properly formatted source XML that Word is looking for.... And you can then modify a known working version of the XML so you can add all your bibliographical information in Word. My test (using the above process) showed up like this: Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenHow To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1 # NOW use the Word GUI to Delete the source from the Bibliography info then save the document using the GUI And then you can use the code above to verify there are no more sources: And last but not least, re-add your source info programmatically: import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") myxml = 'Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenHow To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1' doc.Bibliography.Sources.Add(myxml) doc.Save() wordapp.Quit() I'm pretty sure that your Bibliography XML is likely not formatted the way Word wants it.. Microsoft likes their own formats on everything. If It matters, I tested this using Word 2019 but it should be backwards compatible all the way back to 2007. HTH and Enjoy P.S. This is not something that is limited to Python.. It can be done in just about any language that can access COM objects... VBScript, Perl, Python, etc and there are tons of references on using VB and or VBScript macros that I found (but not much on exactly what the source XML looked like) From: python-win32 On Behalf Of Ryan Dikdan Sent: Tuesday, February 28, 2023 11:35 PM To: python-win32 at python.org Subject: [python-win32] How to add citations to a word document Hello, I'm not sure how this mailing list works for support, but I'm trying to make a python script that formats downloaded citations and inserts them into word (avoiding all the hassle of external citation managers). I found pywin32 as the only way, but the documentation on doc.Bibliography.Sources.Add is scarce, so I was wondering if you all could help me. I have properly formatted xml of sources (since I could upload it to the source manager successfully, even though I think it's encoded in utf8 bom or sig or something). But whenever I put either the string of that content or the filename into the above Add() command in python it says the XML isn't formatted properly. I'd appreciate any help. Thanks! From cherrytwist at gmail.com Thu Mar 2 17:33:52 2023 From: cherrytwist at gmail.com (Clayton Macleod) Date: Thu, 2 Mar 2023 14:33:52 -0800 Subject: [python-win32] possible data corruption when deleting iTunes playlist items Message-ID: I've got a small script to create/maintain a randomized rolling 25-song playlist in iTunes which emulates some of the behaviour of an iTunes feature called Party Shuffle or iTunes DJ, which was removed from the iTunes app year ago. I've got its playback behaviour figured out and working except I seem to have come across a bug that seems to be causing data corruption somehow. The script was erroring out occasionally when trying to execute a playlist.AddTrack(song) command with error messages like this: Traceback (most recent call last): File "C:\iTunesDJ-project\iTunesDJ-current working version-debugging4.py", line 138, in playlist.AddTrack(song) File ">", line 2, in AddTrack pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, 'The track has been deleted.', None, 0, -1610350078), None) Error printing song.Name: I tried troubleshooting and added some print statements, and when it tried printing song.Name it gave a similar error: Traceback (most recent call last): File "C:\iTunesDJ-project\iTunesDJ-current working version-debugging.py", line 138, in print("song.Name:", song.Name) ^^^^^^^^^ File "C:\Users\Clay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\win32com\client\dynamic.py", line 628, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, 'The track has been deleted.', None, 0, -1610350078), None) I pared the script down so that the only things it was doing was connecting to iTunes to get the song library list and then doing a loop where it printed song.Name for random entries 1,000 times using "try" so it would continue if there was an error. This worked perfectly, so I was confused. I started adding commands back in one at a time until it finally started producing errors after a playlist.Tracks[0].Delete() command was executed. I can now reproduce the problem very easily. Only 1/20 trials ran without error once I reintroduced the delete command. 19/20 trials produced hundreds of errors in the 1,000 attempts in the loop. I don't know if you'd want ~150 lines of code included here or not, but the script can be downloaded from here if you'd like to see the whole thing. https://drive.google.com/file/d/1HMuZV7W1xDvYkkrbQ0O2wgJ782VLYqPa/view?usp=sharing -- Clayton Macleod If no one comes from the future to stop you from doing it, then how bad of a decision can it really be? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jn.ml.pyth.93 at letterboxes.org Fri Mar 3 06:42:04 2023 From: jn.ml.pyth.93 at letterboxes.org (Jeremy Nicoll) Date: Fri, 03 Mar 2023 11:42:04 +0000 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: On Thu, 2 Mar 2023, at 22:33, Clayton Macleod wrote: > I pared the script down so that the only things it was doing was connecting > to iTunes to get the song library list and then doing a loop where it > printed song.Name for random entries 1,000 times using "try" so it would > continue if there was an error. This worked perfectly, so I was confused. > I started adding commands back in one at a time until it finally started > producing errors after a playlist.Tracks[0].Delete() command was executed. I only have the sketchiest idea of what your code is doing, and know nothing about iTunes' internal data-structures but I wonder ... when you delete an item (from your playlist? - is that held only by your code or is it within iTunes??) whether that causes iTunes' lists of items to get rebuilt, so that pointers to them that you had are no longer valid? I don't know if that makes sense. If it's possible to extract a list of everything that iTunes knows about before a delete, and the same list afterwards, can you see if it changes more than you expected? I guess that might not help unless you can see, if eg data is held on a linked list, whether the whole list changes or if an element is merely unlinked but the other items are still where they used to be. > I can now reproduce the problem very easily. Only 1/20 trials ran without > error once I reintroduced the delete command. 19/20 trials produced > hundreds of errors in the 1,000 attempts in the loop. That suggests to me that either all items on an original list before the one you deleted might still be "in the same place" but maybe everything after it have moved. Or something. -- Jeremy Nicoll - my opinions are my own. From jn.ml.pyth.93 at letterboxes.org Fri Mar 3 12:17:49 2023 From: jn.ml.pyth.93 at letterboxes.org (Jeremy Nicoll) Date: Fri, 03 Mar 2023 17:17:49 +0000 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: Why did you not reply to the list where other people could see your reply? On Fri, 3 Mar 2023, at 16:46, Clayton Macleod wrote: > Well, the first thing I do is grab a list of the entire song library. Then > I create a playlist. The code says it uses an existing playlist unless it doesn't exist. Unless you're manually deleting it after each run, surely it will exist already. > The entries in this playlist are the only things that > get deleted, so the song list that I grabbed is still valid. What happens if you run the iTunes application while your script is running? If that's possible can you see your playlist's contents being changed? > But I'm not > keeping track of the playlist or its deletions in the script because I > don't think I need to since iTunes is holding a copy of it. Isn't the playlist that you're manipulating /the one that iTunes has/ ... ie not a copy of it? If your playlist is not iTunes playlist (of the specified name) how on earth does your one affect what iTunes is doing? > I'm only > referring again to items in the initial list that have not changed. But the > deletion call seems to cause my copy of that initial list to get corrupted > somehow as trying to print song.Name fails on hundreds of attempts out of a > loop of 1,000 attempts. This 1.000 attempts code ... it's not in the source code you posted, or is it? My python knowledge is rusty. And if your playlist only contains a max of 25 items, what is the significance of doing something 1000 times? -- Jeremy Nicoll - my opinions are my own. From cherrytwist at gmail.com Fri Mar 3 17:55:03 2023 From: cherrytwist at gmail.com (Clayton Macleod) Date: Fri, 3 Mar 2023 14:55:03 -0800 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: Sorry, forgot to hit reply all. Been many years since I've used mailing lists, and I'm surprised anyone still does. Heh. Anyway... Perhaps this isn't very clear. I've found a case where the pywin32 COM library is causing data corruption and I'm trying to make a bug report. I'm not having trouble figuring out how to write code in and use python. I found a bug. And wish to report that bug to the people that would be responsible for squashing bugs in the software they write/maintain. What it is, what is happening, as opposed to what should be happening. I opened an issue on git, where you normally report bugs in software that is hosted on git, but apparently they don't want bug reports in the bug reports section. Whatever sense that makes. The issue was closed without even considering anything in it, despite the fact that it is an actual bug. The idea behind my script is very simple, as is the script to carry out the idea. I have very simple code that should work as designed, but something in the pywin32 COM library is failing under a certain circumstance and causing data corruption in that case. Something which I have now figured out how to make happen on demand. Which is usually what you do when reporting bugs. Figure out if there are steps to reliably reproduce the problem. And if there are, list those steps so developers writing/maintaining that software can reproduce the error and try to figure out why it is happening. It doesn't really matter whether or not the playlist exists already. That doesn't have anything to do with the issue. The script alters the playlist in iTunes in real-time as iTunes is playing music so that it plays a continuous stream of music with the ratio of rated songs that I desire. If iTunes isn't running when the script starts the COM connection attempt fires up iTunes on its own. If it is already playing that playlist it doesn't interrupt playback. If it is playing music but isn't already playing that playlist it starts playing that playlist from the first track. iTunes has the music. iTunes is playing the music. I'm just making/updating the playlist in iTunes. I download the song library list from iTunes, and make randomized choices based on song ratings which is what the playlist is populated from. Everything works great until I make that delete call. After the delete call the script's data seems to be corrupted. If I never make the delete call the script's data remains intact. The significance of doing something 1,000 times is debugging with enough repetition to try to get a good idea of what is going on. I was trying to troubleshoot what was going on by following basic troubleshooting steps. Since I have thousands of songs in the library, and since it was failing with what seemed to be random entries in that list, I figured printing out the randomized song.Name entries 1,000 times would give me a good sample size to try to get some idea of how much of the data was being corrupted. I'm not going to print out one sample and get one error and say 100% of my data is corrupted. I'm going to print out 1000 and if I see 700 errors then there's a good chance 70% of the data was corrupted. As I already said, when I noticed there was a problem I pared the script down to the bare minimum to try to figure out what was going on. So the only things it was doing was downloading the song library list and then printing out the song.Name entries at random with the main loop modified just to print in order to troubleshoot things. debug_loop = 0 while debug_loop < 1000: #while len(playlist.Tracks) < 25: debug_loop += 1 #time.sleep(1) # Select a random rating group rating = random.choice(rating_weighting) # Select a random song from that rating group song = random.choice(grouped_songs[rating]) # Add the song to the playlist if it's not already there print("Topping up...", rating) if song not in playlist.Tracks: # print("song.Name:", song.Name) # playlist.AddTrack(song) try: print("song.Name:", song.Name) #playlist.AddTrack(song) except pywintypes.com_error as e: # I no longer care to see the errors because I can't do anything about them anyway. pass That successfully completed 100% of the time. It didn't matter how many times I tried it. It always printed all 1,000 attempts successfully. So when it was obvious that that was working correctly I just continued following basic troubleshooting steps. I added commands back in one at a time and tried running it again to see what the debug loop did after adding one more command back in. If it continues working then whatever command you just added back in probably wasn't involved in the problem. And then you continue adding and retrying. As I already said, this worked perfectly fine until I got to the point where I added the delete command back in. Immediately after adding the delete command back in the script's data would get corrupted and the failure rate of printing song.Name was very bad. It went from dozens of attempts before adding delete back all coming back with zero errors, to adding the delete command back in and getting 564/1000 errors, 575/1000 errors, 338/1000 errors, 131/1000 errors, 976/1000 errors, 906/1000 errors, 794/1000 errors during the test runs with the delete command present. I'm assuming that COM calls consist of the call itself and a response to the call. Perhaps something in the response to the "playlist.Tracks[0].Delete()" calls and how that's handled by the COM library when it receives the reply is what is responsible for corrupting the python script's own data. That's what seems to be going on to me. If the exact same code runs just fine if that command is avoided and then immediately fails horribly if that command is used I don't know what other conclusion to come to. On Fri, Mar 3, 2023 at 9:18?AM Jeremy Nicoll wrote: > Why did you not reply to the list where other people could see your reply? > > > On Fri, 3 Mar 2023, at 16:46, Clayton Macleod wrote: > > Well, the first thing I do is grab a list of the entire song library. > Then > > I create a playlist. > > The code says it uses an existing playlist unless it doesn't exist. Unless > you're manually deleting it after each run, surely it will exist already. > > > The entries in this playlist are the only things that > > get deleted, so the song list that I grabbed is still valid. > > What happens if you run the iTunes application while your script is > running? If that's possible can you see your playlist's contents being > changed? > > > But I'm not > > keeping track of the playlist or its deletions in the script because I > > don't think I need to since iTunes is holding a copy of it. > > Isn't the playlist that you're manipulating /the one that iTunes has/ ... > ie not a copy of it? > > If your playlist is not iTunes playlist (of the specified name) how on > earth does your one affect what iTunes is doing? > > > > I'm only > > referring again to items in the initial list that have not changed. But > the > > deletion call seems to cause my copy of that initial list to get > corrupted > > somehow as trying to print song.Name fails on hundreds of attempts out > of a > > loop of 1,000 attempts. > > This 1.000 attempts code ... it's not in the source code you posted, or is > it? > My python knowledge is rusty. And if your playlist only contains a max of > 25 items, what is the significance of doing something 1000 times? > > -- > Jeremy Nicoll - my opinions are my own. > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 > -- Clayton Macleod If no one comes from the future to stop you from doing it, then how bad of a decision can it really be? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Mon Mar 6 23:40:15 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 7 Mar 2023 15:40:15 +1100 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: <4e99a205-7d97-268d-d8e5-d36350e9b7fd@skippinet.com.au> On 4/03/2023 9:55 am, Clayton Macleod wrote: > Sorry, forgot to hit reply all.? Been many years since I've used mailing > lists, and I'm surprised anyone still does.? Heh.? Anyway... > > Perhaps this isn't very clear. I've found a case where the pywin32 COM > library is causing data corruption I'm sorry, but I don't think you did. Any bugs here are going to be inside the COM objects exposed by itunes - which doesn't sound particularly surprising given COM doesn't even exist on the platforms they own. It would be like saying that if you can provoke Word to create a corrupt document via COM that it would be a pywin32 bug - it would not - and stranger things have happened with many different COM interfaces over the years. Mark. From cherrytwist at gmail.com Tue Mar 7 00:03:02 2023 From: cherrytwist at gmail.com (Clayton Macleod) Date: Mon, 6 Mar 2023 21:03:02 -0800 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: <4e99a205-7d97-268d-d8e5-d36350e9b7fd@skippinet.com.au> References: <4e99a205-7d97-268d-d8e5-d36350e9b7fd@skippinet.com.au> Message-ID: <67226D27-5E6B-4212-8F19-89A010747B42@gmail.com> Perhaps I?m misunderstanding how those things work then. If I print song.Name that isn?t simply printing from the script?s own data? That?s what I thought to be happening. It is instead calling upon the iTunes app to get song.Name at print time? -- Clayton Macleod If no one comes from the future to stop you from doing it, then how bad of a decision can it really be? > On Mar 6, 2023, at 8:40 PM, Mark Hammond wrote: > > ?On 4/03/2023 9:55 am, Clayton Macleod wrote: >> Sorry, forgot to hit reply all. Been many years since I've used mailing lists, and I'm surprised anyone still does. Heh. Anyway... >> Perhaps this isn't very clear. I've found a case where the pywin32 COM library is causing data corruption > > I'm sorry, but I don't think you did. Any bugs here are going to be inside the COM objects exposed by itunes - which doesn't sound particularly surprising given COM doesn't even exist on the platforms they own. > > It would be like saying that if you can provoke Word to create a corrupt document via COM that it would be a pywin32 bug - it would not - and stranger things have happened with many different COM interfaces over the years. > > Mark. From mhammond at skippinet.com.au Tue Mar 7 00:09:06 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 7 Mar 2023 16:09:06 +1100 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: <67226D27-5E6B-4212-8F19-89A010747B42@gmail.com> References: <4e99a205-7d97-268d-d8e5-d36350e9b7fd@skippinet.com.au> <67226D27-5E6B-4212-8F19-89A010747B42@gmail.com> Message-ID: Your script is using itunes via COM - https://learn.microsoft.com/en-us/windows/win32/com. Many many apps expose APIs via COM, so almost all languages can use them in some way. When you reference song.Name, COM defines how Python asks itunes for a "name" property on a "songs" object. Mark On 7/03/2023 4:03 pm, Clayton Macleod wrote: > Perhaps I?m misunderstanding how those things work then. If I print song.Name that isn?t simply printing from the script?s own data? That?s what I thought to be happening. It is instead calling upon the iTunes app to get song.Name at print time? > > -- > Clayton Macleod > If no one comes from the future to stop you from doing it, then how bad of a decision can it really be? > >> On Mar 6, 2023, at 8:40 PM, Mark Hammond wrote: >> >> ?On 4/03/2023 9:55 am, Clayton Macleod wrote: >>> Sorry, forgot to hit reply all. Been many years since I've used mailing lists, and I'm surprised anyone still does. Heh. Anyway... >>> Perhaps this isn't very clear. I've found a case where the pywin32 COM library is causing data corruption >> I'm sorry, but I don't think you did. Any bugs here are going to be inside the COM objects exposed by itunes - which doesn't sound particularly surprising given COM doesn't even exist on the platforms they own. >> >> It would be like saying that if you can provoke Word to create a corrupt document via COM that it would be a pywin32 bug - it would not - and stranger things have happened with many different COM interfaces over the years. >> >> Mark. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cherrytwist at gmail.com Tue Mar 7 00:25:08 2023 From: cherrytwist at gmail.com (Clayton Macleod) Date: Mon, 6 Mar 2023 21:25:08 -0800 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: An HTML attachment was scrubbed... URL: From moi15moismokerlolilol at gmail.com Tue Mar 7 18:44:43 2023 From: moi15moismokerlolilol at gmail.com (Moi15 Moi) Date: Tue, 7 Mar 2023 18:44:43 -0500 Subject: [python-win32] EnumFontFamilies with EnumFontFamExProc Message-ID: Hi, I am trying to use EnumFontFamilies to get the elfFullName value of each font. Here is what I have tried: from typing import Optional import win32gui def enum_fonts(family_name: Optional[str]=None): hwnd = win32gui.GetDesktopWindow() dc = win32gui.GetWindowDC(hwnd) res = [] def callback(*args): print(args[0].elfFullName) res.append(args) return 1 win32gui.EnumFontFamilies(dc, family_name, callback) win32gui.ReleaseDC(hwnd, dc) return res for logfont in enum_fonts("Arial"): print(f"Font name: {logfont[0].lfFaceName}") print(f"Weight: {logfont[0].lfWeight}") print(f"Width: {logfont[0].lfWidth}") print(f"Height: {logfont[0].lfHeight}") print(f"Italic: {bool(logfont[0].lfItalic)}") print() But, it does give me the elfFullName value. How can I get it? >From what I understand, I need to use EnumFontFamExProc , but I have no idea how to do it. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From jn.ml.pyth.93 at letterboxes.org Wed Mar 8 08:33:13 2023 From: jn.ml.pyth.93 at letterboxes.org (Jeremy Nicoll) Date: Wed, 08 Mar 2023 13:33:13 +0000 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: On Fri, 3 Mar 2023, at 22:55, Clayton Macleod wrote: > It doesn't really matter whether or not the playlist exists already. That > doesn't have anything to do with the issue..... > > Everything works great until I make that delete call. That's not what you said at the start. Then, you said it (also) errors sometimes when you try to add a track. I wondered if those erroring adds/deletes were happening at the boundary where songs end/start playing. > As I already said, when I noticed there was a problem I pared the script > down to the bare minimum to try to figure out what was going on. So the > only things it was doing was downloading the song library list and then > printing out the song.Name entries at random with the main loop modified > just to print in order to troubleshoot things. > That successfully completed 100% of the time. Which is probably because the relationship between song entries and their names wasn't being changed by anything, But (maybe?) the places where you had failures to print names were when you tried to follow a pointer from a track to a song to a name; if the relationship between track & song is corrupted that won't work. Remembering that I don't use iTunes ... I wondered if the iTunes application (when you use it via its GUI) supports dynamic changes to a playlist when that playlist is being played? I also wondered just how often your add/deletes failed? Are you adding a track at the instant that your app notices that iTunes has just reached the end of one track and started the next, and presumably at that point removed the just-played track from the playlist? That is, maybe there's a timing problem. If your code just happens to try to alter the playlist at the same time as iTunes is doing so itself, maybe that doesn't work - so maybe (if you're doing your change when you think it's needed) you could wait 5 seconds and then try it. It also struck me that in the GUI application - even if as a user you may think you can make changes to playlists at any time - the GUI may inhibit user-made changes for a few fractions of a second if IT is about to make a change, but the COM interface might just be offering you the code that makes the change without the locking around it. So eg you might need to search the iTunes COM docs (I know there's some, I found them, but maybe not uptodate, and maybe not complete?) for any sign of "locks" or "serialisation" or "queuing" or "data integrity" controls to prevent the app and you simultaneously updating a data structure inside iTunes. [I don't know the right terminology for this, other than on the IBM mainframes I used to work with, sorry.] It's also possible that - say - it renumbers or completely rebuilds a playlist structure whenever it changes. I wondered if, if that's so, your code would get the rebuilt one each time. -- Jeremy Nicoll - my opinions are my own. From cherrytwist at gmail.com Wed Mar 8 17:28:03 2023 From: cherrytwist at gmail.com (Clayton Macleod) Date: Wed, 8 Mar 2023 14:28:03 -0800 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: On Wed, Mar 8, 2023 at 5:34?AM Jeremy Nicoll wrote: > Remembering that I don't use iTunes ... I wondered if the iTunes > application > (when you use it via its GUI) supports dynamic changes to a playlist when > that playlist is being played? > > Yes, you can alter live playlists at any time in the app itself. > I also wondered just how often your add/deletes failed? Are you adding a > track at the instant that your app notices that iTunes has just reached > the > end of one track and started the next, and presumably at that point > removed the just-played track from the playlist? > > That is, maybe there's a timing problem. If your code just happens to try > to > alter the playlist at the same time as iTunes is doing so itself, maybe > that > doesn't work - so maybe (if you're doing your change when you think it's > needed) you could wait 5 seconds and then try it. > > The old feature I'm trying to emulate was a 25-song rolling playlist in which the currently-playing song was actually song #6 in the playlist, providing enough songs have already played in order for it to get to song #6. It doesn't delete old songs until song #6 finishes playing. This means that once you actually reach song #6 you have a 5-song history in case you wanted to reference those or go back to any of them again for some reason. So you have a 5-song history, the currently-playing song, and 19 songs in queue at any given time. That's the behaviour my script is copying. So the songs that are being deleted from the playlist haven't been played in quite some time by the time it comes to actually delete it, and even with that, I've added a 1-second delay anyway. > It also struck me that in the GUI application - even if as a user you may > think > you can make changes to playlists at any time - the GUI may inhibit > user-made > changes for a few fractions of a second if IT is about to make a change, > but > the COM interface might just be offering you the code that makes the > change without the locking around it. > > So eg you might need to search the iTunes COM docs (I know there's some, > I found them, but maybe not uptodate, and maybe not complete?) for any > sign of "locks" or "serialisation" or "queuing" or "data integrity" > controls to > prevent the app and you simultaneously updating a data structure inside > iTunes. [I don't know the right terminology for this, other than on the > IBM > mainframes I used to work with, sorry.] It's also possible that - say - > it > renumbers or completely rebuilds a playlist structure whenever it changes. > I wondered if, if that's so, your code would get the rebuilt one each time. > > Well, if I'm there watching it as one song is about to end I can see that it deletes the song at the top of the list just fine, and adds a new song to the end of the list just fine, ignoring the fact that there are sometimes errors in the addition and it has to repeat addition attempts until it find one that works. It was my understanding that the song library was doing snagged and put into a local dicationary, and that this was where I was selecting my songs from. And also that the delete command only deletes the song from the current playlist, and only actually deletes the song from the filesystem in the case that you're current "playlist" isn't actually a playlist but rather the main library itself. So since I am deleting index 0 of the current playlist I don't think I should be getting any files deleted from the filesystem. I'm not attempting to delete the song itself by referencing the song entry it got from the library. I am attempting to delete my playlist's index 0 entry. I do have a backup of my library files just in case something like "Nah, bro, you're actually deleting files!" happened. I guess I should check to see if that's actually been happening. But the fact that I figured out where in the list failures were happening, and subsequent runs referencing the same file that errored actually succeeded in the later runs tells me I'm probably safe in that regard, or it would've failed on the same file again after it had actually been deleted. What strikes me as odd is how the references work fine as long as I haven't made a delete call, but after I make a delete call the references fail all over the place. It isn't just one reference that no longer works. It throws hundreds of random failures from each of the five groups in the 1000-test even though only one file has been through the delete call. I haven't timed it, but it takes something like 30-60 seconds to snag the library list from the app at startup. So I don't really want to have a master script to run a slave script that just makes one playlist update and exits, and loop that over and over. It'd be using up a lot of extra energy to make those 30-60-second calls every time a new song rolls over. Thanks for the reply, but this seems more like an iTunes problem than a python problem, so I guess it should just be left be. At least, there doesn't seem to be much point in cluttering up the python mailing list for something that now seems to be an app problem. Have a good one! -- Clayton Macleod If no one comes from the future to stop you from doing it, then how bad of a decision can it really be? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jn.ml.pyth.93 at letterboxes.org Thu Mar 9 15:13:23 2023 From: jn.ml.pyth.93 at letterboxes.org (Jeremy Nicoll) Date: Thu, 09 Mar 2023 20:13:23 +0000 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: <4f7e61bf-2f8d-48b9-908e-4449af331aae@app.fastmail.com> On Wed, 8 Mar 2023, at 22:28, Clayton Macleod wrote: > On Wed, Mar 8, 2023 at 5:34?AM Jeremy Nicoll > wrote: Please stop sending me private copies of your replies. I can easily read them on the mail list itself. >> I also wondered just how often your add/deletes failed? Are you adding a >> track at the instant that your app notices that iTunes has just reached >> the end of one track and started the next, and presumably at that point >> removed the just-played track from the playlist? > The old feature I'm trying to emulate was a 25-song ... So the songs that > are being deleted from the playlist haven't been played in quite some time > by the time it comes to actually delete it, and even with that, I've added a > 1-second delay anyway. ok >> It also struck me that in the GUI application - even if as a user you >> may think you can make changes to playlists at any time - the GUI >> may inhibit user-made changes for a few fractions of a second if IT >> is about to make a change, but the COM interface might just be >> offering you the code that makes the change without the locking >> around it. >> >> So eg you might need to search the iTunes COM docs (I know there's >> some ... for any sign of "locks" or "serialisation" or "queuing" or "data >> integrity" controls to prevent the app and you simultaneously updating >> a data structure inside iTunes. ... It's also possible that - say - it >> renumbers or completely rebuilds a playlist structure whenever it >> changes. I wondered if, if that's so, your code would get the rebuilt one >> each time. > Well, if I'm there watching it as one song is about to end I can see that > it deletes the song at the top of the list just fine ... That's interesting; I know I asked a while back if you could watch stuff changing in the GUI as your script ran, but in between times I read at https://www.joshkunz.com/iTunesControl/ that (it says this right at the top) "Note that calls to the iTunes COM interface will be suspended when a dialog is being displayed in iTunes." which made me think you wouldn't in fact be able to do that - that your script would be frozen. > and adds a new song to the end of the list just fine, ignoring the fact > that there are sometimes errors I read in one of the snippets of code that you posted that you were ignoring errors because you couldn't do anything about them, but I wonder if eg your script should at least be logging them, perhaps to see if there's a relationship between when adds fail vv when deletes do? > It was my understanding that the song library was doing snagged What? Errored? > and put into a local dicationary, and that this > was where I was selecting my songs from. > And also that the delete command > only deletes the song from the current playlist, and only actually deletes > the song from the filesystem Nobody - neither you nor I - has suggested anything has been deleted from the file system. > What strikes me as odd is how the references work fine as long as I haven't > made a delete call, but after I make a delete call the references fail all > over the place. It isn't just one reference that no longer works. It > throws hundreds of random failures from each of the five groups in the > 1000-test even though only one file has been through the delete call. No /file/ has been through a delete call, unless you're changing the story. I hope that was just a slip of the keyboard! -- Jeremy Nicoll - my opinions are my own. From jn.ml.pyth.93 at letterboxes.org Thu Mar 9 15:32:13 2023 From: jn.ml.pyth.93 at letterboxes.org (Jeremy Nicoll) Date: Thu, 09 Mar 2023 20:32:13 +0000 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: References: Message-ID: <4e6c42fb-56d2-485a-a840-9e160df1446b@app.fastmail.com> On Wed, 8 Mar 2023, at 22:28, Clayton Macleod wrote: > Yes, you can alter live playlists at any time in the app itself. Something else (maybe not a welcome suggestion on a Python list, though)... I just found this list of VBS scripts for interacting with iTunes: https://samsoft.org.uk/iTunes/scripts.asp Many look (from their descriptions) to be trivial, but one called InterleaveLists which merges items from two playlists looks interesting to me (and quite complicated too). If it works, it might tell you more about the inner workings of iTunes. Indeed, downloading all (or at least one of each sort when the description implies that groups of them are similar) & reading through them might help. I've also seen a suggestion that to get the uptodate iTunes SDK you probably need to register as an Apple developer. -- Jeremy Nicoll - my opinions are my own. From cherrytwist at gmail.com Thu Mar 9 16:57:21 2023 From: cherrytwist at gmail.com (Clayton Macleod) Date: Thu, 9 Mar 2023 13:57:21 -0800 Subject: [python-win32] possible data corruption when deleting iTunes playlist items In-Reply-To: <4e6c42fb-56d2-485a-a840-9e160df1446b@app.fastmail.com> References: <4e6c42fb-56d2-485a-a840-9e160df1446b@app.fastmail.com> Message-ID: Re: sending to your personal email, yet again another reason mailing lists are stupid. At least back in the day mailing lists were smart enough to only send me emails from the mailing list itself, so when you hit reply it only replied to the mailing list itself. This mailing list is sending me mail coming from your address as well as the mailing list address, so the first time I replied it only went to you personally, which you mentioned as you wondered why I didn't reply to the list. Well, I hit reply and replied, as that's how things always operated in the past. So I started hitting reply all instead, and that resulted in the reply going both to you and the list. This list should really be fixed so that messages it sends out only appear to come from the list server itself rather than also coming from personal email addresses. Then hitting reply and replying would actually work like it is supposed to. "Note that calls to the iTunes COM interface will be suspended when a dialog is being displayed in iTunes." As in, a pop-up dialog that appears on top of the main app window and blocks your view of the main window. Some dialog you have to interact with before you can once again interact with the main window. This has nothing to do with my scenario. Thanks for the list of VBS scripts. I'll take a gander. I was already going off info from the joshkunz website, as I found that before I started. I'll try to figure things out on my own from here, as it no longer seems to be a python issue. Thanks. Later. On Thu, Mar 9, 2023 at 12:32?PM Jeremy Nicoll wrote: > On Wed, 8 Mar 2023, at 22:28, Clayton Macleod wrote: > > > Yes, you can alter live playlists at any time in the app itself. > > > Something else (maybe not a welcome suggestion on a Python list, > though)... > > I just found this list of VBS scripts for interacting with iTunes: > > https://samsoft.org.uk/iTunes/scripts.asp > > Many look (from their descriptions) to be trivial, but one called > > InterleaveLists > > which merges items from two playlists looks interesting to me > (and quite complicated too). If it works, it might tell you more > about the inner workings of iTunes. > > Indeed, downloading all (or at least one of each sort when the > description implies that groups of them are similar) & reading > through them might help. > > I've also seen a suggestion that to get the uptodate iTunes SDK > you probably need to register as an Apple developer. > > -- > Jeremy Nicoll - my opinions are my own. > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 > -- Clayton Macleod If no one comes from the future to stop you from doing it, then how bad of a decision can it really be? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oudouxin at gmail.com Sun Mar 12 10:05:06 2023 From: oudouxin at gmail.com (Wuping Xin) Date: Sun, 12 Mar 2023 14:05:06 +0000 Subject: [python-win32] How to enable events for Python Active Scripting? Message-ID: I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "Python Programming On Win32, but it doesn't provide much information about Python Active Scripting COM events. Need help and much appreciate any advice. Wu -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Sun Mar 12 22:54:23 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 13 Mar 2023 13:54:23 +1100 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: References: Message-ID: It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: com\win32com\demos\connect.py com\win32com\server\connect.py com\win32com\client\connect.py If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. HTH, Mark On 13/03/2023 1:05 am, Wuping Xin wrote: > I have a host application that uses Python Active Scripting.? ?That host > application implements IConnectionPoint / IConnectionPointContainers > etc, and I am able to set COM event callbacks in C++. > > But I am having a hard time to figure out how to set COM event callback > with Python Active Scripting - I bought the book "/Python Programming On > Win32, but /it doesn't provide much information about//Python Active > Scripting COM events. > > Need help and much appreciate any advice. > > Wu > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 From adammabrunella399 at gmail.com Sun Mar 12 23:22:45 2023 From: adammabrunella399 at gmail.com (marketing seragam) Date: Mon, 13 Mar 2023 10:22:45 +0700 Subject: [python-win32] Penawaran seragam Message-ID: yth bpk ibu Di tempat, kami menerima pesanan kemeja, kaos oblong atau kaos krah untuk seragam kerja sesuai permintaan, untuk info lebih lengkap hubungi kami segera Marketing seragam dan promosi whatsapp 085920702991 email : opimina9 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 20180815_095421.jpg Type: image/jpeg Size: 3436306 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: prima 1.jpg Type: image/jpeg Size: 177803 bytes Desc: not available URL: From oudouxin at gmail.com Mon Mar 13 16:32:07 2023 From: oudouxin at gmail.com (Wuping Xin) Date: Mon, 13 Mar 2023 20:32:07 +0000 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: References: Message-ID: HI Mark, Thank you very much for the helpful information. I was trying to connect Event-handlers implemented inside Python Active Script to EventSink at the Host App side. But I cannot figure out how I'll take a look at the files you advised. Thank you again. Wu ------ Original Message ------ >From "Mark Hammond" To "Wuping Xin" ; python-win32 at python.org Date 3/12/2023 10:54:23 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? >It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: > >com\win32com\demos\connect.py >com\win32com\server\connect.py >com\win32com\client\connect.py > >If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. > >HTH, > >Mark > >On 13/03/2023 1:05 am, Wuping Xin wrote: >>I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. >> >>But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. >> >>Need help and much appreciate any advice. >> >>Wu >> >>_______________________________________________ >>python-win32 mailing list >>python-win32 at python.org >>https://mail.python.org/mailman/listinfo/python-win32 > From mhammond at skippinet.com.au Mon Mar 13 20:45:37 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 14 Mar 2023 11:45:37 +1100 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: References: Message-ID: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> [adding the list back in] I'm still not quite sure what you are trying to do. If you are trying to use Active Scripting, then things should "just work" in the same way they work for other Active Scripting languages. The IE demos show us handling events from IE. This all ties together with interfaces described in typelibs and using IConnectionPoint etc. In this world you don't implement Python classes which derive from EventSink or ScriptItem, you would define a function called "ObjectName_EventName"? - eg the "Image_OnClick()" you will find in mousetrack.htm. If you are just trying to use the IConnectionPoint etc without the Active Scripting framework, then your best bet is to check out win32com\demos\connect.py, and specifically how it uses "win32com.client.connect.SimpleConnection()" with the CLSID of an object implementing the interface which fires the events. I'm afraid it has been many years since I've worked on anything related to COM or events, so I really don't have great insights into the finer details. I've also no additional demos - everything relevant I have is in the repo. Cheers, Mark On 14/03/2023 10:41 am, Wuping Xin wrote: > Hi Mark, > > Thank you again for your suggestion. > > Here is my use case: > 1. C++ Host Application, which exposes a COM object model (with COM > events). > 2. Users are expected to write Python script to interact with the COM > object model. > > Following your advice, I read the following source files > - win32comext\axscript\client\framework.py > - win32comext\axscript\test\testHost.py > > But I am still somewhat unsure how to create event sinks at the Python > script side. > - Should I add a user-define Python class that inherits from EventSink > or ScriptItem? > > Do you think you might be able to provide more hints or it would be > great if there is an example to illustrate this? > > Much appreciated! > > Wuping Xin, PE, PhD > Chief Technology Officer | Caliper Corporation > ||||||||||||||||||||||||||||||||||||||||||||||||||||| > 1172 Beacon St, Ste 300 ? Newton MA 02461 USA > Mobile: 617-564-1676 ? Main: 617-527-4700 > > ------ Original Message ------ > From "Mark Hammond" > To "Wuping Xin";python-win32 at python.org > Date 3/12/2023 10:54:23 PM > Subject Re: [python-win32] How to enable events for Python Active > Scripting? > >> It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: >> >> com\win32com\demos\connect.py >> com\win32com\server\connect.py >> com\win32com\client\connect.py >> >> If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. >> >> HTH, >> >> Mark >> >> On 13/03/2023 1:05 am, Wuping Xin wrote: >>> I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. >>> >>> But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. >>> >>> Need help and much appreciate any advice. >>> >>> Wu >>> >>> _______________________________________________ >>> python-win32 mailing list >>> python-win32 at python.org >>> https://mail.python.org/mailman/listinfo/python-win32 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuping at caliper.com Mon Mar 13 22:12:46 2023 From: wuping at caliper.com (Wuping Xin) Date: Tue, 14 Mar 2023 02:12:46 +0000 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> References: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> Message-ID: Hi Mark, - "you would define a function called "ObjectName_EventName" Thank you again! This is valuable info. In the following pseudo-code, the Host COM Object implements TWO Events interfaces. How should I defined relevant event sink functions? For example, if the object instance is named "MyHostObject", should I just directly define the following event sink functions? MyHostObject.Do_A_Event() MyHostObject.Do_B_Event() MyHostObject.Do_C_Event() MyHostObject.Do_D_Event() interface _IMondayEvents { Do_A_Event; Do_B_event; } interface _ITuesdayEvents { Do_C_Event; Do_D_event; } coclass HostApplication { [default] interface IHostApplication; [source] interface _IMondayEvents; [source] interface _ITuesdayEvents; }; ------ Original Message ------ From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 8:45:37 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? WARNING EXTERNAL EMAIL [adding the list back in] I'm still not quite sure what you are trying to do. If you are trying to use Active Scripting, then things should "just work" in the same way they work for other Active Scripting languages. The IE demos show us handling events from IE. This all ties together with interfaces described in typelibs and using IConnectionPoint etc. In this world you don't implement Python classes which derive from EventSink or ScriptItem, you would define a function called "ObjectName_EventName" - eg the "Image_OnClick()" you will find in mousetrack.htm. If you are just trying to use the IConnectionPoint etc without the Active Scripting framework, then your best bet is to check out win32com\demos\connect.py, and specifically how it uses "win32com.client.connect.SimpleConnection()" with the CLSID of an object implementing the interface which fires the events. I'm afraid it has been many years since I've worked on anything related to COM or events, so I really don't have great insights into the finer details. I've also no additional demos - everything relevant I have is in the repo. Cheers, Mark On 14/03/2023 10:41 am, Wuping Xin wrote: Hi Mark, Thank you again for your suggestion. Here is my use case: 1. C++ Host Application, which exposes a COM object model (with COM events). 2. Users are expected to write Python script to interact with the COM object model. Following your advice, I read the following source files - win32comext\axscript\client\framework.py - win32comext\axscript\test\testHost.py But I am still somewhat unsure how to create event sinks at the Python script side. - Should I add a user-define Python class that inherits from EventSink or ScriptItem? Do you think you might be able to provide more hints or it would be great if there is an example to illustrate this? Much appreciated! Wuping Xin, PE, PhD Chief Technology Officer | Caliper Corporation ||||||||||||||||||||||||||||||||||||||||||||||||||||| 1172 Beacon St, Ste 300 ? Newton MA 02461 USA Mobile: 617-564-1676 ? Main: 617-527-4700 ------ Original Message ------ From "Mark Hammond" To "Wuping Xin" ; python-win32 at python.org Date 3/12/2023 10:54:23 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: com\win32com\demos\connect.py com\win32com\server\connect.py com\win32com\client\connect.py If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. HTH, Mark On 13/03/2023 1:05 am, Wuping Xin wrote: I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. Need help and much appreciate any advice. Wu _______________________________________________ python-win32 mailing list python-win32 at python.org https://mail.python.org/mailman/listinfo/python-win32 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Mon Mar 13 22:55:03 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 14 Mar 2023 13:55:03 +1100 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: References: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> Message-ID: IIRC, each of these objects is a "named item" - so whatever name you use when you call AddNamedItem() is the prefix and the suffix is the name of the function on the event interface. I'm really not sure how multiple event interfaces are supported, if at all. Cheers, Mark On 14/03/2023 1:12 pm, Wuping Xin wrote: > Hi Mark, > > - "you would define a function called "ObjectName_EventName" > > Thank you again! This is valuable info.? In the following > pseudo-code,? the Host COM Object implements TWO Events interfaces.? > How should I defined relevant event sink functions?? For example, if > the object instance is named "MyHostObject",? should I just directly > define the following event sink functions? > > MyHostObject.Do_A_Event() > MyHostObject.Do_B_Event() > MyHostObject.Do_C_Event() > MyHostObject.Do_D_Event() > > > interface _IMondayEvents > { > Do_A_Event; > Do_B_event; > } > > interface _ITuesdayEvents > { > ? ? ? ? Do_C_Event; > ? ? ? ? Do_D_event; > } > > ? ? coclass HostApplication > ? ? { > ? ? ? ? [default] interface IHostApplication; > ? ? ? ? [source] interface _IMondayEvents; > ? ? ? ? [source] interface _ITuesdayEvents; > ? ? }; > > > ------ Original Message ------ > From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 8:45:37 PM > Subject Re: [python-win32] How to enable events for Python Active > Scripting? > >> *WARNING EXTERNAL EMAIL * >> >> >> >> [adding the list back in] >> >> I'm still not quite sure what you are trying to do. If you are trying >> to use Active Scripting, then things should "just work" in the same >> way they work for other Active Scripting languages. The IE demos show >> us handling events from IE. This all ties together with interfaces >> described in typelibs and using IConnectionPoint etc. In this world >> you don't implement Python classes which derive from EventSink or >> ScriptItem, you would define a function called "ObjectName_EventName" >> - eg the "Image_OnClick()" you will find in mousetrack.htm. >> >> If you are just trying to use the IConnectionPoint etc without the >> Active Scripting framework, then your best bet is to check out >> win32com\demos\connect.py, and specifically how it uses >> "win32com.client.connect.SimpleConnection()" with the CLSID of an >> object implementing the interface which fires the events. >> >> I'm afraid it has been many years since I've worked on anything >> related to COM or events, so I really don't have great insights into >> the finer details. I've also no additional demos - everything >> relevant I have is in the repo. >> >> Cheers, >> >> Mark >> >> On 14/03/2023 10:41 am, Wuping Xin wrote: >>> Hi Mark, >>> >>> Thank you again for your suggestion. >>> >>> Here is my use case: >>> 1. C++ Host Application, which exposes a COM object model (with COM >>> events). >>> 2. Users are expected to write Python script to interact with the COM >>> object model. >>> >>> Following your advice, I read the following source files >>> - win32comext\axscript\client\framework.py >>> - win32comext\axscript\test\testHost.py >>> >>> But I am still somewhat unsure how to create event sinks at the Python >>> script side. >>> - Should I add a user-define Python class that inherits from EventSink >>> or ScriptItem? >>> >>> Do you think you might be able to provide more hints or it would be >>> great if there is an example to illustrate this? >>> >>> Much appreciated! >>> >>> Wuping Xin, PE, PhD >>> Chief Technology Officer | Caliper Corporation >>> ||||||||||||||||||||||||||||||||||||||||||||||||||||| >>> 1172 Beacon St, Ste 300 ? Newton MA 02461 USA >>> Mobile: 617-564-1676 ? Main: 617-527-4700 >>> >>> ------ Original Message ------ >>> From "Mark Hammond" >>> >>> To "Wuping Xin";python-win32 at python.org >>> Date 3/12/2023 10:54:23 PM >>> Subject Re: [python-win32] How to enable events for Python Active >>> Scripting? >>> >>>> It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: >>>> >>>> com\win32com\demos\connect.py >>>> com\win32com\server\connect.py >>>> com\win32com\client\connect.py >>>> >>>> If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. >>>> >>>> HTH, >>>> >>>> Mark >>>> >>>> On 13/03/2023 1:05 am, Wuping Xin wrote: >>>>> I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. >>>>> >>>>> But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. >>>>> >>>>> Need help and much appreciate any advice. >>>>> >>>>> Wu >>>>> >>>>> _______________________________________________ >>>>> python-win32 mailing list >>>>> python-win32 at python.org >>>>> https://mail.python.org/mailman/listinfo/python-win32 >>> > >> >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Tue Mar 14 00:47:27 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 14 Mar 2023 15:47:27 +1100 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: References: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> Message-ID: <7cc2794e-1834-ee05-593c-9b1d54b1eb5b@skippinet.com.au> Feel free to put a PR up! Cheers, Mark On 14/03/2023 3:10 pm, Wuping Xin wrote: > Thank you again Mark. > > In framework.py, Line 223 - Line 235, I see that it only searches for > [source, default] interface on the coclass.? That means,? multiple > event interface is NOT supported for now. > > I think I'll have to use "win32com.client.connect.SimpleConnection()" > to manually create the Source/EventSink connection. > > Wuping > > > ------ Original Message ------ > From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 10:55:03 PM > Subject Re: [python-win32] How to enable events for Python Active > Scripting? > >> *WARNING EXTERNAL EMAIL * >> >> >> >> IIRC, each of these objects is a "named item" - so whatever name you >> use when you call AddNamedItem() is the prefix and the suffix is the >> name of the function on the event interface. I'm really not sure how >> multiple event interfaces are supported, if at all. >> >> Cheers, >> >> Mark >> >> >> >> On 14/03/2023 1:12 pm, Wuping Xin wrote: >>> Hi Mark, >>> >>> - "you would define a function called "ObjectName_EventName" >>> >>> Thank you again! This is valuable info.? In the following >>> pseudo-code,? the Host COM Object implements TWO Events interfaces.? >>> How should I defined relevant event sink functions?? For example, if >>> the object instance is named "MyHostObject", should I just directly >>> define the following event sink functions? >>> >>> MyHostObject.Do_A_Event() >>> MyHostObject.Do_B_Event() >>> MyHostObject.Do_C_Event() >>> MyHostObject.Do_D_Event() >>> >>> >>> interface _IMondayEvents >>> { >>> ? ? Do_A_Event; >>> ? ? Do_B_event; >>> } >>> >>> interface _ITuesdayEvents >>> { >>> ? ? ? ? Do_C_Event; >>> ? ? ? ? Do_D_event; >>> } >>> >>> ? ? coclass HostApplication >>> ? ? { >>> ? ? ? ? [default] interface IHostApplication; >>> ? ? ? ? [source] interface _IMondayEvents; >>> ? ? ? ? [source] interface _ITuesdayEvents; >>> ? ? }; >>> >>> >>> ------ Original Message ------ >>> From "Mark Hammond" >>> To "Wuping Xin" >>> Cc "Python-win32 at python.org" >>> Date 3/13/2023 8:45:37 PM >>> Subject Re: [python-win32] How to enable events for Python Active >>> Scripting? >>> >>>> *WARNING EXTERNAL EMAIL * >>>> >>>> >>>> >>>> [adding the list back in] >>>> >>>> I'm still not quite sure what you are trying to do. If you are >>>> trying to use Active Scripting, then things should "just work" in >>>> the same way they work for other Active Scripting languages. The IE >>>> demos show us handling events from IE. This all ties together with >>>> interfaces described in typelibs and using IConnectionPoint etc. In >>>> this world you don't implement Python classes which derive from >>>> EventSink or ScriptItem, you would define a function called >>>> "ObjectName_EventName"? - eg the "Image_OnClick()" you will find in >>>> mousetrack.htm. >>>> >>>> If you are just trying to use the IConnectionPoint etc without the >>>> Active Scripting framework, then your best bet is to check out >>>> win32com\demos\connect.py, and specifically how it uses >>>> "win32com.client.connect.SimpleConnection()" with the CLSID of an >>>> object implementing the interface which fires the events. >>>> >>>> I'm afraid it has been many years since I've worked on anything >>>> related to COM or events, so I really don't have great insights >>>> into the finer details. I've also no additional demos - everything >>>> relevant I have is in the repo. >>>> >>>> Cheers, >>>> >>>> Mark >>>> >>>> On 14/03/2023 10:41 am, Wuping Xin wrote: >>>>> Hi Mark, >>>>> >>>>> Thank you again for your suggestion. >>>>> >>>>> Here is my use case: >>>>> 1. C++ Host Application, which exposes a COM object model (with COM >>>>> events). >>>>> 2. Users are expected to write Python script to interact with the COM >>>>> object model. >>>>> >>>>> Following your advice, I read the following source files >>>>> - win32comext\axscript\client\framework.py >>>>> - win32comext\axscript\test\testHost.py >>>>> >>>>> But I am still somewhat unsure how to create event sinks at the Python >>>>> script side. >>>>> - Should I add a user-define Python class that inherits from EventSink >>>>> or ScriptItem? >>>>> >>>>> Do you think you might be able to provide more hints or it would be >>>>> great if there is an example to illustrate this? >>>>> >>>>> Much appreciated! >>>>> >>>>> Wuping Xin, PE, PhD >>>>> Chief Technology Officer | Caliper Corporation >>>>> ||||||||||||||||||||||||||||||||||||||||||||||||||||| >>>>> 1172 Beacon St, Ste 300 ? Newton MA 02461 USA >>>>> Mobile: 617-564-1676 ? Main: 617-527-4700 >>>>> >>>>> ------ Original Message ------ >>>>> From "Mark Hammond" >>>>> >>>>> To "Wuping Xin";python-win32 at python.org >>>>> Date 3/12/2023 10:54:23 PM >>>>> Subject Re: [python-win32] How to enable events for Python Active >>>>> Scripting? >>>>> >>>>>> It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: >>>>>> >>>>>> com\win32com\demos\connect.py >>>>>> com\win32com\server\connect.py >>>>>> com\win32com\client\connect.py >>>>>> >>>>>> If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. >>>>>> >>>>>> HTH, >>>>>> >>>>>> Mark >>>>>> >>>>>> On 13/03/2023 1:05 am, Wuping Xin wrote: >>>>>>> I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. >>>>>>> >>>>>>> But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. >>>>>>> >>>>>>> Need help and much appreciate any advice. >>>>>>> >>>>>>> Wu >>>>>>> >>>>>>> _______________________________________________ >>>>>>> python-win32 mailing list >>>>>>> python-win32 at python.org >>>>>>> https://mail.python.org/mailman/listinfo/python-win32 >>>>> > >>>> >>>> >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuping at caliper.com Tue Mar 14 00:10:37 2023 From: wuping at caliper.com (Wuping Xin) Date: Tue, 14 Mar 2023 04:10:37 +0000 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: References: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> Message-ID: Thank you again Mark. In framework.py, Line 223 - Line 235, I see that it only searches for [source, default] interface on the coclass. That means, multiple event interface is NOT supported for now. I think I'll have to use "win32com.client.connect.SimpleConnection()" to manually create the Source/EventSink connection. Wuping ------ Original Message ------ From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 10:55:03 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? WARNING EXTERNAL EMAIL IIRC, each of these objects is a "named item" - so whatever name you use when you call AddNamedItem() is the prefix and the suffix is the name of the function on the event interface. I'm really not sure how multiple event interfaces are supported, if at all. Cheers, Mark On 14/03/2023 1:12 pm, Wuping Xin wrote: Hi Mark, - "you would define a function called "ObjectName_EventName" Thank you again! This is valuable info. In the following pseudo-code, the Host COM Object implements TWO Events interfaces. How should I defined relevant event sink functions? For example, if the object instance is named "MyHostObject", should I just directly define the following event sink functions? MyHostObject.Do_A_Event() MyHostObject.Do_B_Event() MyHostObject.Do_C_Event() MyHostObject.Do_D_Event() interface _IMondayEvents { Do_A_Event; Do_B_event; } interface _ITuesdayEvents { Do_C_Event; Do_D_event; } coclass HostApplication { [default] interface IHostApplication; [source] interface _IMondayEvents; [source] interface _ITuesdayEvents; }; ------ Original Message ------ From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 8:45:37 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? WARNING EXTERNAL EMAIL [adding the list back in] I'm still not quite sure what you are trying to do. If you are trying to use Active Scripting, then things should "just work" in the same way they work for other Active Scripting languages. The IE demos show us handling events from IE. This all ties together with interfaces described in typelibs and using IConnectionPoint etc. In this world you don't implement Python classes which derive from EventSink or ScriptItem, you would define a function called "ObjectName_EventName" - eg the "Image_OnClick()" you will find in mousetrack.htm. If you are just trying to use the IConnectionPoint etc without the Active Scripting framework, then your best bet is to check out win32com\demos\connect.py, and specifically how it uses "win32com.client.connect.SimpleConnection()" with the CLSID of an object implementing the interface which fires the events. I'm afraid it has been many years since I've worked on anything related to COM or events, so I really don't have great insights into the finer details. I've also no additional demos - everything relevant I have is in the repo. Cheers, Mark On 14/03/2023 10:41 am, Wuping Xin wrote: Hi Mark, Thank you again for your suggestion. Here is my use case: 1. C++ Host Application, which exposes a COM object model (with COM events). 2. Users are expected to write Python script to interact with the COM object model. Following your advice, I read the following source files - win32comext\axscript\client\framework.py - win32comext\axscript\test\testHost.py But I am still somewhat unsure how to create event sinks at the Python script side. - Should I add a user-define Python class that inherits from EventSink or ScriptItem? Do you think you might be able to provide more hints or it would be great if there is an example to illustrate this? Much appreciated! Wuping Xin, PE, PhD Chief Technology Officer | Caliper Corporation ||||||||||||||||||||||||||||||||||||||||||||||||||||| 1172 Beacon St, Ste 300 ? Newton MA 02461 USA Mobile: 617-564-1676 ? Main: 617-527-4700 ------ Original Message ------ From "Mark Hammond" To "Wuping Xin" ; python-win32 at python.org Date 3/12/2023 10:54:23 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: com\win32com\demos\connect.py com\win32com\server\connect.py com\win32com\client\connect.py If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. HTH, Mark On 13/03/2023 1:05 am, Wuping Xin wrote: I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. Need help and much appreciate any advice. Wu _______________________________________________ python-win32 mailing list python-win32 at python.org https://mail.python.org/mailman/listinfo/python-win32 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rjd254 at njms.rutgers.edu Fri Mar 17 01:11:34 2023 From: rjd254 at njms.rutgers.edu (Ryan Dikdan) Date: Fri, 17 Mar 2023 05:11:34 +0000 Subject: [python-win32] How to add citations to a word document In-Reply-To: <0a10480d87144fffb66ae034fc3f4d41@manross.net> References: <0a10480d87144fffb66ae034fc3f4d41@manross.net> Message-ID: Thank you!! I've made a lot of progress. I've been able to reformat citations, but I've hit another roadbump that chat gpt can't help me with anymore. I successfully have a script that can take a citation file and load it into word and automatically place a citation, but if I want to put a citation on top of an existing citation Field, it says that the field is protected. I can't find a way to unprotect it, either through the selection or the document itself. Here's my code: `word = win32.GetActiveObject("Word.Application") doc = word.ActiveDocument doc.Bibliography.Sources.Add(xml_string) cursor_pos = word.Selection.Range.Start fields = doc.Fields current_field = None for field in fields: if cursor_pos >= field.Result.Start and cursor_pos <= field.Result.End: current_field = field break if current_field is not None: if current_field.Type == win32.constants.wdFieldCitation: current_code = current_field.Code.Text # \\m is just used to show that there are multiple sources in this one citation. current_field.Code.Text = current_code + f'\\m {tag}' else: # \\l 1033 just says means that it's in english current_field = doc.Range(cursor_pos, cursor_pos).Fields.Add(doc.Range(cursor_pos, cursor_pos), win32.constants.wdFieldCitation, Text=f" {tag} \\l 1033", PreserveFormatting=True) current_field.Update()` But this gives the error pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'You are not allowed to edit this selection because it is protected.', 'wdmain11.chm', 25604, -2146822164), None)? when the cursor is inside of another field. Any other way to edit or unprotect the field would be appreciated. I was thinking of deleting and remaking the field, but this duplicates the references I think. Yours truly, Ryan Dikdan ________________________________ From: Steven Manross Sent: Wednesday, March 1, 2023 6:43 PM To: Ryan Dikdan ; python-win32 at python.org Subject: RE: How to add citations to a word document I'd probably start by creating a test Word document and adding a source manually in it from the Word GUI. Then, I would likely want to do something like this in python. # Sample python to list the bibliography entries import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") for source in doc.Bibliography.Sources: print("source: " + source.XML) # Now save the XML as a variable: myxml = source.XML wordapp.Quit() That should give you the properly formatted source XML that Word is looking for.... And you can then modify a known working version of the XML so you can add all your bibliographical information in Word. My test (using the above process) showed up like this: Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenHow To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1 # NOW use the Word GUI to Delete the source from the Bibliography info then save the document using the GUI And then you can use the code above to verify there are no more sources: And last but not least, re-add your source info programmatically: import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") myxml = 'Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenHow To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1' doc.Bibliography.Sources.Add(myxml) doc.Save() wordapp.Quit() I'm pretty sure that your Bibliography XML is likely not formatted the way Word wants it.. Microsoft likes their own formats on everything. If It matters, I tested this using Word 2019 but it should be backwards compatible all the way back to 2007. HTH and Enjoy P.S. This is not something that is limited to Python.. It can be done in just about any language that can access COM objects... VBScript, Perl, Python, etc and there are tons of references on using VB and or VBScript macros that I found (but not much on exactly what the source XML looked like) From: python-win32 On Behalf Of Ryan Dikdan Sent: Tuesday, February 28, 2023 11:35 PM To: python-win32 at python.org Subject: [python-win32] How to add citations to a word document Hello, I'm not sure how this mailing list works for support, but I'm trying to make a python script that formats downloaded citations and inserts them into word (avoiding all the hassle of external citation managers). I found pywin32 as the only way, but the documentation on doc.Bibliography.Sources.Add is scarce, so I was wondering if you all could help me. I have properly formatted xml of sources (since I could upload it to the source manager successfully, even though I think it's encoded in utf8 bom or sig or something). But whenever I put either the string of that content or the filename into the above Add() command in python it says the XML isn't formatted properly. I'd appreciate any help. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at manross.net Fri Mar 17 02:04:41 2023 From: steven at manross.net (Steven Manross) Date: Fri, 17 Mar 2023 06:04:41 +0000 Subject: [python-win32] How to add citations to a word document In-Reply-To: References: <0a10480d87144fffb66ae034fc3f4d41@manross.net> Message-ID: A quick google of your error led me to this, although I am not 100% sure it will solve your issue? however, it is worth trying at a minimum. https://stackoverflow.com/questions/17594211/you-are-not-allowed-to-edit-this-selection-because-it-is-protected-but-only-s They suggest changing the View and explain that Microsoft blocks certain thing in Reading Layout. This linked website also has some comments about changing security settings of the document in the Trust Center which may also be of some help, but I did not validate or test their suggestions. Good luck, as I did not have this problem (likely because I started from a blank document). Steven From: Ryan Dikdan Sent: Thursday, March 16, 2023 10:12 PM To: Steven Manross ; python-win32 at python.org Subject: Re: How to add citations to a word document Thank you!! I've made a lot of progress. I've been able to reformat citations, but I've hit another roadbump that chat gpt can't help me with anymore. I successfully have a script that can take a citation file and load it into word and automatically place a citation, but if I want to put a citation on top of an existing citation Field, it says that the field is protected. I can't find a way to unprotect it, either through the selection or the document itself. Here's my code: `word = win32.GetActiveObject("Word.Application") doc = word.ActiveDocument doc.Bibliography.Sources.Add(xml_string) cursor_pos = word.Selection.Range.Start fields = doc.Fields current_field = None for field in fields: if cursor_pos >= field.Result.Start and cursor_pos <= field.Result.End: current_field = field break if current_field is not None: if current_field.Type == win32.constants.wdFieldCitation: current_code = current_field.Code.Text # \\m is just used to show that there are multiple sources in this one citation. current_field.Code.Text = current_code + f'\\m {tag}' else: # \\l 1033 just says means that it's in english current_field = doc.Range(cursor_pos, cursor_pos).Fields.Add(doc.Range(cursor_pos, cursor_pos), win32.constants.wdFieldCitation, Text=f" {tag} \\l 1033", PreserveFormatting=True) current_field.Update()` But this gives the error pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'You are not allowed to edit this selection because it is protected.', 'wdmain11.chm', 25604, -2146822164), None)? when the cursor is inside of another field. Any other way to edit or unprotect the field would be appreciated. I was thinking of deleting and remaking the field, but this duplicates the references I think. Yours truly, Ryan Dikdan ________________________________ From: Steven Manross > Sent: Wednesday, March 1, 2023 6:43 PM To: Ryan Dikdan >; python-win32 at python.org > Subject: RE: How to add citations to a word document I'd probably start by creating a test Word document and adding a source manually in it from the Word GUI. Then, I would likely want to do something like this in python. # Sample python to list the bibliography entries import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") for source in doc.Bibliography.Sources: print("source: " + source.XML) # Now save the XML as a variable: myxml = source.XML wordapp.Quit() That should give you the properly formatted source XML that Word is looking for.... And you can then modify a known working version of the XML so you can add all your bibliographical information in Word. My test (using the above process) showed up like this: Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossSteven>How To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1 # NOW use the Word GUI to Delete the source from the Bibliography info then save the document using the GUI And then you can use the code above to verify there are no more sources: And last but not least, re-add your source info programmatically: import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") myxml = 'Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossSteven>How To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1' doc.Bibliography.Sources.Add(myxml) doc.Save() wordapp.Quit() I'm pretty sure that your Bibliography XML is likely not formatted the way Word wants it.. Microsoft likes their own formats on everything. If It matters, I tested this using Word 2019 but it should be backwards compatible all the way back to 2007. HTH and Enjoy P.S. This is not something that is limited to Python.. It can be done in just about any language that can access COM objects... VBScript, Perl, Python, etc and there are tons of references on using VB and or VBScript macros that I found (but not much on exactly what the source XML looked like) From: python-win32 > On Behalf Of Ryan Dikdan Sent: Tuesday, February 28, 2023 11:35 PM To: python-win32 at python.org Subject: [python-win32] How to add citations to a word document Hello, I'm not sure how this mailing list works for support, but I'm trying to make a python script that formats downloaded citations and inserts them into word (avoiding all the hassle of external citation managers). I found pywin32 as the only way, but the documentation on doc.Bibliography.Sources.Add is scarce, so I was wondering if you all could help me. I have properly formatted xml of sources (since I could upload it to the source manager successfully, even though I think it's encoded in utf8 bom or sig or something). But whenever I put either the string of that content or the filename into the above Add() command in python it says the XML isn't formatted properly. I'd appreciate any help. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuping at caliper.com Fri Mar 17 10:11:38 2023 From: wuping at caliper.com (Wuping Xin) Date: Fri, 17 Mar 2023 14:11:38 +0000 Subject: [python-win32] How to enable events for Python Active Scripting? In-Reply-To: <7cc2794e-1834-ee05-593c-9b1d54b1eb5b@skippinet.com.au> References: <1528ce55-1bd4-7966-d46f-3c3ffc3db47a@skippinet.com.au> <7cc2794e-1834-ee05-593c-9b1d54b1eb5b@skippinet.com.au> Message-ID: I am still struggling with PyActiveScripting COM events. Is there a way to "step into" the framework code while running the C++ host? I found PyDump - how can I make use of it? Thank you Wuping ------ Original Message ------ From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/14/2023 12:47:27 AM Subject Re: [python-win32] How to enable events for Python Active Scripting? WARNING EXTERNAL EMAIL Feel free to put a PR up! Cheers, Mark On 14/03/2023 3:10 pm, Wuping Xin wrote: Thank you again Mark. In framework.py, Line 223 - Line 235, I see that it only searches for [source, default] interface on the coclass. That means, multiple event interface is NOT supported for now. I think I'll have to use "win32com.client.connect.SimpleConnection()" to manually create the Source/EventSink connection. Wuping ------ Original Message ------ From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 10:55:03 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? WARNING EXTERNAL EMAIL IIRC, each of these objects is a "named item" - so whatever name you use when you call AddNamedItem() is the prefix and the suffix is the name of the function on the event interface. I'm really not sure how multiple event interfaces are supported, if at all. Cheers, Mark On 14/03/2023 1:12 pm, Wuping Xin wrote: Hi Mark, - "you would define a function called "ObjectName_EventName" Thank you again! This is valuable info. In the following pseudo-code, the Host COM Object implements TWO Events interfaces. How should I defined relevant event sink functions? For example, if the object instance is named "MyHostObject", should I just directly define the following event sink functions? MyHostObject.Do_A_Event() MyHostObject.Do_B_Event() MyHostObject.Do_C_Event() MyHostObject.Do_D_Event() interface _IMondayEvents { Do_A_Event; Do_B_event; } interface _ITuesdayEvents { Do_C_Event; Do_D_event; } coclass HostApplication { [default] interface IHostApplication; [source] interface _IMondayEvents; [source] interface _ITuesdayEvents; }; ------ Original Message ------ From "Mark Hammond" > To "Wuping Xin" > Cc "Python-win32 at python.org" > Date 3/13/2023 8:45:37 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? WARNING EXTERNAL EMAIL [adding the list back in] I'm still not quite sure what you are trying to do. If you are trying to use Active Scripting, then things should "just work" in the same way they work for other Active Scripting languages. The IE demos show us handling events from IE. This all ties together with interfaces described in typelibs and using IConnectionPoint etc. In this world you don't implement Python classes which derive from EventSink or ScriptItem, you would define a function called "ObjectName_EventName" - eg the "Image_OnClick()" you will find in mousetrack.htm. If you are just trying to use the IConnectionPoint etc without the Active Scripting framework, then your best bet is to check out win32com\demos\connect.py, and specifically how it uses "win32com.client.connect.SimpleConnection()" with the CLSID of an object implementing the interface which fires the events. I'm afraid it has been many years since I've worked on anything related to COM or events, so I really don't have great insights into the finer details. I've also no additional demos - everything relevant I have is in the repo. Cheers, Mark On 14/03/2023 10:41 am, Wuping Xin wrote: Hi Mark, Thank you again for your suggestion. Here is my use case: 1. C++ Host Application, which exposes a COM object model (with COM events). 2. Users are expected to write Python script to interact with the COM object model. Following your advice, I read the following source files - win32comext\axscript\client\framework.py - win32comext\axscript\test\testHost.py But I am still somewhat unsure how to create event sinks at the Python script side. - Should I add a user-define Python class that inherits from EventSink or ScriptItem? Do you think you might be able to provide more hints or it would be great if there is an example to illustrate this? Much appreciated! Wuping Xin, PE, PhD Chief Technology Officer | Caliper Corporation ||||||||||||||||||||||||||||||||||||||||||||||||||||| 1172 Beacon St, Ste 300 ? Newton MA 02461 USA Mobile: 617-564-1676 ? Main: 617-527-4700 ------ Original Message ------ From "Mark Hammond" To "Wuping Xin" ; python-win32 at python.org Date 3/12/2023 10:54:23 PM Subject Re: [python-win32] How to enable events for Python Active Scripting? It's difficult to know what exactly you mean, but if it is how to use IConnectionPoint etc from Python in general, then you should check out the following files in the distribution: com\win32com\demos\connect.py com\win32com\server\connect.py com\win32com\client\connect.py If it is about the use of these interfaces specifically with ActiveScripting, then you should find win32comext\axscript\test\testHost.py useful. win32comext\axscript\client\framework.py is where the implementation of Active Scripting's event handling is implemented - eg, see the functions Connect, CreateConnections, ConnectEventHandlers etc in that file. HTH, Mark On 13/03/2023 1:05 am, Wuping Xin wrote: I have a host application that uses Python Active Scripting. That host application implements IConnectionPoint / IConnectionPointContainers etc, and I am able to set COM event callbacks in C++. But I am having a hard time to figure out how to set COM event callback with Python Active Scripting - I bought the book "/Python Programming On Win32, but /it doesn't provide much information about//Python Active Scripting COM events. Need help and much appreciate any advice. Wu _______________________________________________ python-win32 mailing list python-win32 at python.org https://mail.python.org/mailman/listinfo/python-win32 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rjd254 at njms.rutgers.edu Sun Mar 19 00:30:31 2023 From: rjd254 at njms.rutgers.edu (Ryan Dikdan) Date: Sun, 19 Mar 2023 04:30:31 +0000 Subject: [python-win32] How to add citations to a word document In-Reply-To: References: <0a10480d87144fffb66ae034fc3f4d41@manross.net> Message-ID: It doesn't seem to be a Reading Layout or View setting. I followed all the instructions on the linked website and still have the same problem on multiple computers. Perhaps there was a change that happened with Office 365 as I'm running Microsoft 365 Apps for Enterprise Version 2302 Build 16.0.16130.20298 from my school that prevents the editing of fields that the cursor is in for some reason? But if you've run the code that I just sent (which edits fields which have the cursor inside of them) and it works, it means that there's probably something changed in the office version. I wish there was an easy way to find out the different options I can run on field objects, etc. that are allowed instead of guessing and checking with dir. I may try to make a work around that just deletes the field and then makes a new citation field which is a combination of the two instead, messy, but it'll work hopefully. Yours truly, Ryan Dikdan ________________________________ From: Steven Manross Sent: Friday, March 17, 2023 2:04 AM To: Ryan Dikdan ; python-win32 at python.org Subject: RE: How to add citations to a word document A quick google of your error led me to this, although I am not 100% sure it will solve your issue? however, it is worth trying at a minimum. https://stackoverflow.com/questions/17594211/you-are-not-allowed-to-edit-this-selection-because-it-is-protected-but-only-s They suggest changing the View and explain that Microsoft blocks certain thing in Reading Layout. This linked website also has some comments about changing security settings of the document in the Trust Center which may also be of some help, but I did not validate or test their suggestions. Good luck, as I did not have this problem (likely because I started from a blank document). Steven From: Ryan Dikdan Sent: Thursday, March 16, 2023 10:12 PM To: Steven Manross ; python-win32 at python.org Subject: Re: How to add citations to a word document Thank you!! I've made a lot of progress. I've been able to reformat citations, but I've hit another roadbump that chat gpt can't help me with anymore. I successfully have a script that can take a citation file and load it into word and automatically place a citation, but if I want to put a citation on top of an existing citation Field, it says that the field is protected. I can't find a way to unprotect it, either through the selection or the document itself. Here's my code: `word = win32.GetActiveObject("Word.Application") doc = word.ActiveDocument doc.Bibliography.Sources.Add(xml_string) cursor_pos = word.Selection.Range.Start fields = doc.Fields current_field = None for field in fields: if cursor_pos >= field.Result.Start and cursor_pos <= field.Result.End: current_field = field break if current_field is not None: if current_field.Type == win32.constants.wdFieldCitation: current_code = current_field.Code.Text # \\m is just used to show that there are multiple sources in this one citation. current_field.Code.Text = current_code + f'\\m {tag}' else: # \\l 1033 just says means that it's in english current_field = doc.Range(cursor_pos, cursor_pos).Fields.Add(doc.Range(cursor_pos, cursor_pos), win32.constants.wdFieldCitation, Text=f" {tag} \\l 1033", PreserveFormatting=True) current_field.Update()` But this gives the error pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'You are not allowed to edit this selection because it is protected.', 'wdmain11.chm', 25604, -2146822164), None)? when the cursor is inside of another field. Any other way to edit or unprotect the field would be appreciated. I was thinking of deleting and remaking the field, but this duplicates the references I think. Yours truly, Ryan Dikdan ________________________________ From: Steven Manross > Sent: Wednesday, March 1, 2023 6:43 PM To: Ryan Dikdan >; python-win32 at python.org > Subject: RE: How to add citations to a word document I'd probably start by creating a test Word document and adding a source manually in it from the Word GUI. Then, I would likely want to do something like this in python. # Sample python to list the bibliography entries import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") for source in doc.Bibliography.Sources: print("source: " + source.XML) # Now save the XML as a variable: myxml = source.XML wordapp.Quit() That should give you the properly formatted source XML that Word is looking for.... And you can then modify a known working version of the XML so you can add all your bibliographical information in Word. My test (using the above process) showed up like this: Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossSteven>How To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1 # NOW use the Word GUI to Delete the source from the Bibliography info then save the document using the GUI And then you can use the code above to verify there are no more sources: And last but not least, re-add your source info programmatically: import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") wordapp.Visible = True doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx") myxml = 'Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossSteven>How To Add A Bibliography Entry2023Nowhere, AZ< /b:City>Some Really Good Publisher1' doc.Bibliography.Sources.Add(myxml) doc.Save() wordapp.Quit() I'm pretty sure that your Bibliography XML is likely not formatted the way Word wants it.. Microsoft likes their own formats on everything. If It matters, I tested this using Word 2019 but it should be backwards compatible all the way back to 2007. HTH and Enjoy P.S. This is not something that is limited to Python.. It can be done in just about any language that can access COM objects... VBScript, Perl, Python, etc and there are tons of references on using VB and or VBScript macros that I found (but not much on exactly what the source XML looked like) From: python-win32 > On Behalf Of Ryan Dikdan Sent: Tuesday, February 28, 2023 11:35 PM To: python-win32 at python.org Subject: [python-win32] How to add citations to a word document Hello, I'm not sure how this mailing list works for support, but I'm trying to make a python script that formats downloaded citations and inserts them into word (avoiding all the hassle of external citation managers). I found pywin32 as the only way, but the documentation on doc.Bibliography.Sources.Add is scarce, so I was wondering if you all could help me. I have properly formatted xml of sources (since I could upload it to the source manager successfully, even though I think it's encoded in utf8 bom or sig or something). But whenever I put either the string of that content or the filename into the above Add() command in python it says the XML isn't formatted properly. I'd appreciate any help. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Sat Mar 25 20:19:22 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 26 Mar 2023 11:19:22 +1100 Subject: [python-win32] [ANN] pywin32 build 306 released Message-ID: Hi all, I'm happy to announce the release of pywin32 build 306. There are relatively few changes in this release: * Support for Python 3.6 was dropped, support for later versions was improved. * Add GetSystemPowerStatus (#2010, @CristiFati) * Add CascadeWindows (#1999, @CristiFati) * Add win32gui.ResetDC * Fix leak in win32pdh.GetFormattedCounterArray * Fix IIS on later python versions (#2025) * Fix for service registration code updated in build 305 (#1985) Downloads are available at: https://github.com/mhammond/pywin32/releases/tag/b306 and via pypi. For initial support (eg, to ask questions about the release etc), please contact this mailing-list (python-win32 at python.org). If you want to report a bug, please do so at https://github.com/mhammond/pywin32/issues As always, thanks to everyone who contributed to this release, both in terms of code and reporting bugs - there were a number of new contributors which is great to see, Cheers, Mark. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy.farmer1206 at proton.me Fri Mar 24 16:25:54 2023 From: jeremy.farmer1206 at proton.me (jeremy.farmer1206) Date: Fri, 24 Mar 2023 20:25:54 +0000 Subject: [python-win32] Pywin32 Windows Service not responding Message-ID: Hi, I am looking for some assistance with utilizing pywin32 in order to create a Windows Service. I've tried to create as bare-bones of an application as I could inheriting from win32serviceutil.ServiceFramework import traceback import win32serviceutil import win32service import win32event import servicemanager import socket import time import os import sys class MyService(win32serviceutil.ServiceFramework): _svc_name_ = 'MyPythonService' _svc_display_name_ = 'My Python Service' _svc_description_ = 'This is a sample Python Wind def __init__(self, args): win32serviceutil.ServiceFramework.__init__(se self.hWaitStop = win32event.CreateEvent(None, socket.setdefaulttimeout(60) self.is_alive = True def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE win32event.SetEvent(self.hWaitStop) self.is_alive = False def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE self.ReportServiceStatus(win32service.SERVICE # win32event.WaitForSingleObject(self.hWaitSt try: servicemanager.LogMsg(servicemanager.EVEN PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() except Exception as ex: servicemanager.LogErrorMsg("Exception in eback.format_exc())) raise def main(self): while self.is_alive: with open('test.txt', 'a') as f: f.write('Service loop...') time.sleep(2) if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(MyService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(MyService) I've installed it via opening an admin command prompt and running python main.py install It installs successfully but if I attempt to run it, I get [image.png] Or >>python main.py start > Starting service MyPythonService > Error starting service: The service did not respond to the start or control request in a timely fashion. debugging seems to work, or at least does not give any errors > python main.py debug > Debugging service MyPythonService - press Ctrl+C to stop.Info 0x40001002 - The MyPythonService service has started. I believe my pywin32 is fully up to date > python -m pip install --upgrade pywin32 > Requirement already satisfied: pywin32 in c:\users\jerem\appdata\local\programs\python\python311\lib\site-packages (305) Misc > python --version > Python 3.11.2 [image.png] Any assistance is very much appreciated! Sent with [Proton Mail](https://proton.me/) secure email. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image.png Type: image/png Size: 7142 bytes Desc: not available URL: From steven at manross.net Sat Mar 25 20:49:31 2023 From: steven at manross.net (Steven Manross) Date: Sun, 26 Mar 2023 00:49:31 +0000 Subject: [python-win32] Pywin32 Windows Service not responding In-Reply-To: References: Message-ID: <6dc2915a06ed46a39f6a3638edad80da@manross.net> Something seems to be stripping your code at about 40-50 characters and it seems like we are missing the right half of your code. Example: _svc_description_ = 'This is a sample Python Wind Steven From: python-win32 On Behalf Of jeremy.farmer1206 via python-win32 Sent: Friday, March 24, 2023 1:26 PM To: python-win32 at python.org Subject: [python-win32] Pywin32 Windows Service not responding Hi, I am looking for some assistance with utilizing pywin32 in order to create a Windows Service. I've tried to create as bare-bones of an application as I could inheriting from win32serviceutil.ServiceFramework import traceback import win32serviceutil import win32service import win32event import servicemanager import socket import time import os import sys class MyService(win32serviceutil.ServiceFramework): _svc_name_ = 'MyPythonService' _svc_display_name_ = 'My Python Service' _svc_description_ = 'This is a sample Python Wind def __init__(self, args): win32serviceutil.ServiceFramework.__init__(se self.hWaitStop = win32event.CreateEvent(None, socket.setdefaulttimeout(60) self.is_alive = True def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE win32event.SetEvent(self.hWaitStop) self.is_alive = False def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE self.ReportServiceStatus(win32service.SERVICE # win32event.WaitForSingleObject(self.hWaitSt try: servicemanager.LogMsg(servicemanager.EVEN PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() except Exception as ex: servicemanager.LogErrorMsg("Exception in eback.format_exc())) raise def main(self): while self.is_alive: with open('test.txt', 'a') as f: f.write('Service loop...') time.sleep(2) if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(MyService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(MyService) I've installed it via opening an admin command prompt and running python main.py install It installs successfully but if I attempt to run it, I get [cid:image001.png at 01D95F42.26DA6EF0] Or >python main.py start Starting service MyPythonService Error starting service: The service did not respond to the start or control request in a timely fashion. debugging seems to work, or at least does not give any errors python main.py debug Debugging service MyPythonService - press Ctrl+C to stop. Info 0x40001002 - The MyPythonService service has started. I believe my pywin32 is fully up to date python -m pip install --upgrade pywin32 Requirement already satisfied: pywin32 in c:\users\jerem\appdata\local\programs\python\python311\lib\site-packages (305) Misc python --version Python 3.11.2 [cid:834fd2a at proton.me] Any assistance is very much appreciated! Sent with Proton Mail secure email. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.png Type: image/png Size: 7142 bytes Desc: image001.png URL: From skippy.hammond at gmail.com Sat Mar 25 23:29:51 2023 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sun, 26 Mar 2023 14:29:51 +1100 Subject: [python-win32] Pywin32 Windows Service not responding In-Reply-To: References: Message-ID: <2512115a-fbc6-0bb3-ead1-b59a97da3fa1@gmail.com> The last pywin32 release was before 3.11 was officially released, so maybe try either 3.10 or pywin32-306 Mark On 25/03/2023 7:25 am, jeremy.farmer1206 via python-win32 wrote: > Hi, I am looking for some assistance with utilizing pywin32 in order to > create a Windows Service. > > I've tried to create as bare-bones of an application as I could > inheriting from win32serviceutil.ServiceFramework > > import traceback > import win32serviceutil > import win32service > import win32event > import servicemanager > import socket > import time > import os > import sys > class MyService(win32serviceutil.ServiceFramework): > ? ? _svc_name_ = 'MyPythonService' > ? ? _svc_display_name_ = 'My Python Service' > ? ? _svc_description_ = 'This is a sample Python Wind > ? ? def __init__(self, args): > ? ? ? ? win32serviceutil.ServiceFramework.__init__(se > ? ? ? ? self.hWaitStop = win32event.CreateEvent(None, > ? ? ? ? socket.setdefaulttimeout(60) > ? ? ? ? self.is_alive = True > ? ? def SvcStop(self): > ? ? ? ? self.ReportServiceStatus(win32service.SERVICE > ? ? ? ? win32event.SetEvent(self.hWaitStop) > ? ? ? ? self.is_alive = False > ? ? def SvcDoRun(self): > ? ? ? ? self.ReportServiceStatus(win32service.SERVICE > ? ? ? ? self.ReportServiceStatus(win32service.SERVICE > ? ? ? ? # win32event.WaitForSingleObject(self.hWaitSt > ? ? ? ? try: > ? ? ? ? ? ? servicemanager.LogMsg(servicemanager.EVEN > PYS_SERVICE_STARTED, (self._svc_name_, '')) > ? ? ? ? ? ? self.main() > ? ? ? ? except Exception as ex: > ? ? ? ? ? ? servicemanager.LogErrorMsg("Exception in > eback.format_exc())) > ? ? ? ? ? ? raise > ? ? def main(self): > ? ? ? ? while self.is_alive: > ? ? ? ? ? ? with open('test.txt', 'a') as f: > ? ? ? ? ? ? ? ? f.write('Service loop...') > ? ? ? ? ? ? ? ? time.sleep(2) > if __name__ == '__main__': > ? ? if len(sys.argv) == 1: > ? ? ? ? servicemanager.Initialize() > ? ? ? ? servicemanager.PrepareToHostSingle(MyService) > ? ? ? ? servicemanager.StartServiceCtrlDispatcher() > ? ? else: > ? ? ? ? win32serviceutil.HandleCommandLine(MyService) > > > I've installed it via opening an admin command prompt and running > > python main.py install > > It installs successfully but if I attempt to run it, I get > > image.png > > Or > > >python main.py start > Starting service MyPythonService > Error starting service: The service did not respond to the start or > control request in a timely fashion. > > > debugging seems to work, or at least does not give any errors > > python main.py debug > Debugging service MyPythonService - press Ctrl+C to stop. > Info 0x40001002 - The MyPythonService service has started. > > > I believe my pywin32 is fully up to date > > python -m pip install --upgrade pywin32 > Requirement already satisfied: pywin32 in > c:\users\jerem\appdata\local\programs\python\python311\lib\site-packages (305) > > > Misc > > python --version > Python 3.11.2 > > > image.png > > Any assistance is very much appreciated! > Sent with Proton Mail secure email. > > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > https://mail.python.org/mailman/listinfo/python-win32 From philipcarr83 at gmail.com Tue Mar 28 14:38:58 2023 From: philipcarr83 at gmail.com (Philip Carr) Date: Tue, 28 Mar 2023 20:38:58 +0200 Subject: [python-win32] pythoncom.Pumpwaitingmessages() overloaded Message-ID: Hi Im looking for help on pythoncom.PumpWaitingMessages(). I?m using it to connect to a Windows application that has a com object to stream stock prices. It works fine most of the time but when the rate of new events/messages gets too high ( unscientifically about 50 a second i think it can handle) it grinds to a halt and basically stops processing new events/messages and doesn't catch up even if the rate of new events/messages slows down. . I'm using in my thread: while True: pythoncom.PumpWaitingMessages() There's a few stackexchange questions with vague answers, I'd really appreciate if someone could elaborate on some of these? https://stackoverflow.com/questions/28352419/python-win32com-pumpwaitingmessages-processing https://stackoverflow.com/questions/30691875/python-pythoncom-pumpmessages Replacing the loop with just pythoncom.PumpMessages() also works, but I have no idea if this is more or less robust? I've seen plenty of examples with some time.sleep in the while True loop, but that definitely doesnt work for my purposes. Happy to share more code if it is needed for context, but the application itself needs a paid subscription so it wouldn't be testable. Thanks for your help Phil -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Tue Mar 28 17:38:26 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 29 Mar 2023 08:38:26 +1100 Subject: [python-win32] pythoncom.Pumpwaitingmessages() overloaded In-Reply-To: References: Message-ID: On 29/03/2023 5:38 am, Philip Carr wrote: > Hi > > Im looking for help on pythoncom.PumpWaitingMessages(). I?m using it to > connect to a Windows application that has a com object to stream stock > prices. > > It works fine most of the time but when the rate of new events/messages > gets too high ( unscientifically about 50 a second i think it can > handle) it grinds to a halt and basically stops processing new > events/messages and doesn't catch up even if the rate of new > events/messages slows down. . I can't explain why it doesn't recover, but you would certainly expect this to be quite slow given Python is executing an infinite loop. > Replacing the loop with just?pythoncom.PumpMessages() also works, but I > have no idea if this is more or less robust? That should be more robust and performant in your scenario. The only time you should use PumpWaitingMessages is when that infinite loop isn't what you want. HTH, Mark From mhammond at skippinet.com.au Thu Mar 30 06:13:05 2023 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 30 Mar 2023 21:13:05 +1100 Subject: [python-win32] Recommendations for releasing pywin32 without a local windows device? Message-ID: <18176505-b403-cb3f-79ac-8a04c12604a4@skippinet.com.au> Hey all, ? I'm in the process of moving countries for a couple of years and for the first time in - um - forever - will find myself without a physical Windows machine. It seems unlikely I'll actually need one other than for pywin32 builds and testing. My primary device will end up as an M2 macbook pro supplied by work. Options I see are: * Lean into CI for releases - this is problematic because obscure html-help and mapi/exchange sdks are needed, and manually testing stuff still happens - but this might make sense for the longer term health of the project. * VM on the macbook - but by all accounts, anything other than ARM doesn't really work well on the M chips, and as above re the SDKs etc, I'm not sure an ARM build environment will work in practice without losing functionality for x86 builds. * Buy an x86-64 laptop - $1k probably gets me something good enough if I'm patient waiting for things to build. * A hosted VPS. The latter seems a bit easier and less things to carry around, but might actually be more expensive over ~2 years and more of a PITA than a local device. I've also no experience at all with this kind of environment. Wondering what experience/anecdotes/thoughts y'all have for this? Thanks, Mark. -------------- next part -------------- An HTML attachment was scrubbed... URL: From graham.bloice at trihedral.com Thu Mar 30 06:19:24 2023 From: graham.bloice at trihedral.com (Graham Bloice) Date: Thu, 30 Mar 2023 10:19:24 +0000 Subject: [python-win32] Recommendations for releasing pywin32 without a local windows device? In-Reply-To: <18176505-b403-cb3f-79ac-8a04c12604a4@skippinet.com.au> References: <18176505-b403-cb3f-79ac-8a04c12604a4@skippinet.com.au> Message-ID: Moving to a CI system would be good for the project long-term. Windows VM(s) should suffice short-term, I would have thought with the project profile that the cloud giants would be amenable to covering the costs. ________________________________ From: python-win32 on behalf of Mark Hammond Sent: 30 March 2023 11:13 To: python-win32 at python.org Subject: [python-win32] Recommendations for releasing pywin32 without a local windows device? Hey all, I'm in the process of moving countries for a couple of years and for the first time in - um - forever - will find myself without a physical Windows machine. It seems unlikely I'll actually need one other than for pywin32 builds and testing. My primary device will end up as an M2 macbook pro supplied by work. Options I see are: * Lean into CI for releases - this is problematic because obscure html-help and mapi/exchange sdks are needed, and manually testing stuff still happens - but this might make sense for the longer term health of the project. * VM on the macbook - but by all accounts, anything other than ARM doesn't really work well on the M chips, and as above re the SDKs etc, I'm not sure an ARM build environment will work in practice without losing functionality for x86 builds. * Buy an x86-64 laptop - $1k probably gets me something good enough if I'm patient waiting for things to build. * A hosted VPS. The latter seems a bit easier and less things to carry around, but might actually be more expensive over ~2 years and more of a PITA than a local device. I've also no experience at all with this kind of environment. Wondering what experience/anecdotes/thoughts y'all have for this? Thanks, Mark. -------------- next part -------------- An HTML attachment was scrubbed... URL: