Examples for automating Windows applications via the Microsoft
Component Object Model (COM), Win32API, PythonCOM and other interesting
Python modules. Mainly developed with the Python Windows Extensions from Marc Hammond. If you want to post a script, article or news please use this link Post a Python script. Hint: For sytax highlighting place your code between the tags <pre> and </pre>
This section as RSS feed.
|
|
Microsoft Office
|
I think this must be an example from Marc Hammond. It shows how to connect to events in Microsoft Word and Excel:
# OfficeEvents - test/demonstrate events with Word and Excel.
from win32com.client import DispatchWithEvents, Dispatch
import msvcrt, pythoncom
import time, sys
import types
import threading
stopEvent = threading.Event()
def TestExcel():
class ExcelEvents:
def OnNewWorkbook(self, wb):
if type(wb) != types.InstanceType:
raise RuntimeError, "The transformer doesnt appear to have translated this for us!"
self.seen_events["OnNewWorkbook"] = None
def OnWindowActivate(self, wb, wn):
if type(wb) != types.InstanceType or type(wn) != types.InstanceType:
raise RuntimeError, "The transformer doesnt appear to have translated this for us!"
self.seen_events["OnWindowActivate"] = None
def OnWindowDeactivate(self, wb, wn):
self.seen_events["OnWindowDeactivate"] = None
def OnSheetDeactivate(self, sh):
self.seen_events["OnSheetDeactivate"] = None
def OnSheetBeforeDoubleClick(self, Sh, Target, Cancel):
if Target.Column % 2 == 0:
print "You can double-click there..."
else:
print "You can not double-click there..."
# This function is a void, so the result ends up in
# the only ByRef - Cancel.
return 1
class WorkbookEvents:
def OnActivate(self):
print "workbook OnActivate"
def OnBeforeRightClick(self, Target, Cancel):
print "It's a Worksheet Event"
e = DispatchWithEvents("Excel.Application", ExcelEvents)
e.seen_events = {}
e.Visible=1
book = e.Workbooks.Add()
book = DispatchWithEvents(book, WorkbookEvents)
print "Have book", book
# sheet = e.Worksheets(1)
# sheet = DispatchWithEvents(sheet, WorksheetEvents)
print "Double-click in a few of the Excel cells..."
print "Press any key when finished with Excel, or wait 10 seconds..."
if not _WaitForFinish(e, 10):
e.Quit()
if not _CheckSeenEvents(e, ["OnNewWorkbook", "OnWindowActivate"]):
sys.exit(1)
def TestWord():
class WordEvents:
def OnDocumentChange(self):
self.seen_events["OnDocumentChange"] = None
def OnWindowActivate(self, doc, wn):
self.seen_events["OnWindowActivate"] = None
def OnQuit(self):
self.seen_events["OnQuit"] = None
stopEvent.set()
w = DispatchWithEvents("Word.Application", WordEvents)
w.seen_events = {}
w.Visible = 1
w.Documents.Add()
print "Press any key when finished with Word, or wait 10 seconds..."
if not _WaitForFinish(w, 10):
w.Quit()
if not _CheckSeenEvents(w, ["OnDocumentChange", "OnWindowActivate"]):
sys.exit(1)
def _WaitForFinish(ob, timeout):
end = time.time() + timeout
while 1:
if msvcrt.kbhit():
msvcrt.getch()
break
pythoncom.PumpWaitingMessages()
stopEvent.wait(.2)
if stopEvent.isSet():
stopEvent.clear()
break
try:
if not ob.Visible:
# Gone invisible - we need to pretend we timed
# out, so the app is quit.
return 0
except pythoncom.com_error:
# Excel is busy (eg, editing the cell) - ignore
pass
if time.time() > end:
return 0
return 1
def _CheckSeenEvents(o, events):
rc = 1
for e in events:
if not o.seen_events.has_key(e):
print "ERROR: Expected event did not trigger", e
rc = 0
return rc
def test():
import sys
if "noword" not in sys.argv[1:]:
TestWord()
if "noexcel" not in sys.argv[1:]:
TestExcel()
print "Word and Excel event tests passed."
if __name__=='__main__':
test()
|
|
|
Microsoft Windows
|
import win32file
import win32con
import os
def togglefileattribute(filename, fileattribute, value):
"""Turn a specific file attribute on or off, leaving the other
attributes intact.
"""
bitvector = win32file.GetFileAttributes(filename)
if value:
bitvector |= fileattribute
else:
bitvector &= ~fileattribute
win32file.SetFileAttributes(filename, bitvector)
# Sample usage:
for file in os .listdir(r'C:\Temp\doc'):
file = os.path.join(r'C:\Temp\doc\%s'%file)
togglefileattribute(file, win32con.FILE_ATTRIBUTE_ARCHIVE, False)
|
|
|
Microsoft Office
|
This is a script which creates Outlook tasks from each task out of a Taskcoach XML-file. I saved my task to file named "My_Tasks.tsk". Please modify it for your needs.
from xml.dom import minidom
import win32com.client
from datetime import datetime
try:
oOutlookApp = win32com.client.gencache.EnsureDispatch("Outlook.Application")
except:
print "MSOutlook: unable to load Outlook"
# this should use more try/except blocks or nested blocks
#onMAPI = oOutlookApp.GetNamespace("MAPI")
#ofTasks = onMAPI.GetDefaultFolder(win32com.client.constants.olFolderTasks)
xml = r'My_Tasks.tsk'
xmldoc = minidom.parse(xml)
tcTasks = xmldoc.getElementsByTagName('task')
print 'Creating %s tasks'%len(tcTasks)
for tcTask in tcTasks:
print 'Saving %s [%s]' % (tcTask.getAttribute('subject'), tcTask.getAttribute('status'))
newtask = oOutlookApp.CreateItem(win32com.client.constants.olTaskItem)
if tcTask.getAttribute('expandedContexts') != 'Dummy': #Todo: Unsichere Ecke
newtask.Subject = tcTask.getAttribute('subject')
for note in tcTask.getElementsByTagName('note'):
newnote = oOutlookApp.CreateItem(win32com.client.constants.olNoteItem)
newnote.Body += note.getAttribute('subject') + ':\n'
for nodetext in note.getElementsByTagName('description'):
newnote.Body += nodetext.firstChild.data
newnote.Save()
#newtask.Links.Add(newnote)
for tasktext in tcTask.getElementsByTagName('description'):
newtask.Body += tasktext.firstChild.data
for attachment in tcTask.getElementsByTagName('attachment'):
newtask.Body += 'File attachment %s:\n%s\n' % (attachment.getAttribute('subject'), attachment.getAttribute('location'))
if tcTask.getAttribute('duedate') not in ['', None]:
newtask.DueDate = tcTask.getAttribute('duedate')
if tcTask.getAttribute('startdate') not in ['', None]:
newtask.StartDate = tcTask.getAttribute('startdate')
#elif tcTask.getAttribute('percentageComplete') in ['0', 0]:
#newtask.Status = 0
#newtask.PercentComplete = 0
if tcTask.getAttribute('percentageComplete') in ['100', 100]:
newtask.Status = 2
newtask.PercentComplete = 100
if tcTask.getAttribute('percentageComplete') not in ['', None, '100', 100]:
newtask.PercentComplete = int(tcTask.getAttribute('percentageComplete'))
newtask.Status = 5
newtask.Save()
|
|
|
Microsoft Office
|
import codecs, win32com.client
# This example dumps the items in the default address book
# needed for converting Unicode->Ansi (in local system codepage)
DecodeUnicodeString = lambda x: codecs.latin_1_encode(x)[0]
def DumpDefaultAddressBook():
# Create instance of Outlook
o = win32com.client.Dispatch("Outlook.Application")
mapi = o.GetNamespace("MAPI")
folder = mapi.GetDefaultFolder(win32com.client.constants.olFolderContacts)
print "The default address book contains",folder.Items.Count,"items"
# see Outlook object model for more available properties on ContactItem objects
attributes = [ 'FullName', 'Email1Address']
for i in range(1,folder.Items.Count+1):
print "~~~ Entry %d ~~~" % i
item = folder.Items[i]
for attribute in attributes:
print attribute, eval('item.%s' % attribute)
o = None
DumpDefaultAddressBook()
|
|
|
Microsoft Project
|
I found this very interesting Python script, which showes how to use Events in Microsoft Project with Python for Windows. Simply dispatch with an eventmanager class:
import win32com.client
import pythoncom
defaultNamedNotOptArg = pythoncom.Empty
class EventManager(object):
def OnProjectBeforeSave(self, pj=defaultNamedNotOptArg, SaveAsUi=defaultNamedNotOptArg, Cancel=defaultNamedNotOptArg):
print 'Project saved'
pass
def OnProjectBeforeClose(self, pj=defaultNamedNotOptArg, Cancel=defaultNamedNotOptArg):
print 'Project closed'
pass
def OnProjectTaskNew(self, pj=defaultNamedNotOptArg, ID=defaultNamedNotOptArg):
print 'Task created'
pass
def OnProjectBeforeTaskChange(self, tsk=defaultNamedNotOptArg, Field=defaultNamedNotOptArg, NewVal=defaultNamedNotOptArg, Cancel=defaultNamedNotOptArg):
print 'Field %s of Task %s changed to %s'%(Field, tsk, NewVal)
pass
def OnProjectBeforeTaskDelete(self, tsk=defaultNamedNotOptArg, Cancel=defaultNamedNotOptArg):
print 'Task %s deleted'%tsk
pass
app = win32com.client.DispatchWithEvents('MSProject.Application', EventManager)
doc = app.ActiveProject
app.Visible=1
|
|
|
<< Start < Prev 1 2 3 4 5 6 7 8 9 10 Next > End >>
|
| Results 6 - 10 of 95 |