Lotus notes script example

This is an example of how to access lotus email with python, please comment

from win32com.client import Dispatch
import smtplib

session = Dispatch(‘Lotus.Notessession’)
session.Initialize('xxxxx')
db = session.getDatabase("",'xxxxx\xxxxxx.nsf')
print db.Title

view = db.GetView('$Inbox')
print view.name
doc = view.GetFirstDocument
record = doc.GetItemValue('Body')
print doc.GetItemValue('Subject')
for line in record :
    print line
print '##########################################################'
loop=0
while loop<4:
    doc = view.GetNextDocument(doc)
    record = doc.GetItemValue('Body')
    print doc.GetItemValue('Subject')
    for line in record :
        print line
    print '##########################################################'
    loop=loop+1

A batch script to convert CAD files with CATIA V5

import os, sys
import win32com.client


def convert(file, format):

    print '  Converting with CATIA V5'
    dirname, filename = os.path.split(file)
    basename, ext = os.path.splitext(filename)
    fileout=os.path.join(dirname, basename + '.' + format)
    try:
        CATIA = win32com.client.Dispatch('CATIA.Application')
    except:
        print 'Error connecting to CATIA! Either CATIA V5 is not installed or' \
        'you didn`t have registered CATIA V5 as a COM application.'
        print 'You can do this with:'
        print '   >> c:\\...\\Dassault Systemes\\intel_a\\code\\bin\\CNEXT.exe /regserver'
        sys.exit()
    CATIA.DisplayFileAlerts = False
    Doc = CATIA.Documents.Open(os.path.abspath(file))
    try:
        Doc.ExportData(fileout, format)
    except:
        print 'Could not convert file %s.'%file
    finally:
        Doc.Close()
        CATIA.Quit()
    print 'done'
    return fileout

if __name__ == "__main__":
    if len(sys.argv)==1:
        print 'Usage: v5batcher.py [filename] [format]'
    else:
        convert(sys.argv[1], sys.argv[2])


A file open dialog with win32ui

import win32ui
o = win32ui.CreateFileDialog( 1, ".txt", "default.txt", 0, "Text Files (*.txt)|*.txt|All Files (*.*)|*.*|")
o.DoModal()
print o.GetPathName()

Compare/Diff two word files and create a result PDF

import win32com.client
import time

app = win32com.client.Dispatch('Word.Application')

# The original document:
doc = app.Documents.Open('c:\\temp\\firstversion.doc')
# The modified document:
ret = doc.Compare('c:\\temp\\newversion.doc')

app.ActiveDocument.SaveAs('diff.doc')
app.ActiveDocument.ExportAsFixedFormat('diff.pdf', 17, False, 0, 0, 1, 1, 7, True, True, 1, True, True, True)
app.ActiveDocument.Close()
doc.Close()
app.Quit()

Get all file property informations on Windows

# DumpStorage.py - Dumps some user defined properties
# of a COM Structured Storage file.

import pythoncom
from win32com import storagecon # constants related to storage functions.

# These come from ObjIdl.h
FMTID_UserDefinedProperties = "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"

PIDSI_TITLE               = 0x00000002
PIDSI_SUBJECT             = 0x00000003
PIDSI_AUTHOR              = 0x00000004
PIDSI_CREATE_DTM          = 0x0000000c

def PrintStats(filename) :

    if sys.platform == 'win32':
        if not pythoncom.StgIsStorageFile(filename) :
            print "The file is not a storage file!"
            return
        # Open the file.
        flags = storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE
        stg_= pythoncom.StgOpenStorage(filename, None, flags )

        # Now see if the storage object supports Property Information.
        try:
            pss = stg_.QueryInterface(pythoncom.IID_IPropertySetStorage)
        except pythoncom.com_error:
            print "No summary information is available"
            return
        # Open the user defined properties.
        ps = pss.Open(FMTID_UserDefinedProperties)
        props = PIDSI_TITLE, PIDSI_SUBJECT, PIDSI_AUTHOR, PIDSI_CREATE_DTM
        data = ps.ReadMultiple( props )
        # Unpack the result into the items.
        title, subject, author, created = data
        print "Title:", title
        print "Subject:", subject
        print "Author:", author
        print "Created:", created.Format()

if __name__=='__main__':
    import sys
    if len(sys.argv)<2:
        print "Please specify a file name"
    else:
        PrintStats(sys.argv[1])

Events in Microsoft Word and Excel

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()

Set archive bit on files in a directory

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)

Create Outlook tasks from Taskcoach task file

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()

Get all adressbook entries

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()