Automating Microsoft Powerpoint

One more example how to automate Microsoft Powerpoint and printout a
postscript file with a specified postscript printer (yes, more than one
printers can be installed on the system).

Multithreadding:

Unlike Word and Excel Powerpoint can not run in multiple instances.
If you want to use Powerpoint server based you must implement code to
handle the Powerpoint processes.

How to call the function:

You simply call the function with the name of the Word file, Postscript file and the printername which you want to use.:

e.g.:

make_ps.powerpoint(‘c:\test\powerpointfilename.ppt’, ‘c:\test\psfilename.ps’, ‘My Postscript Printername’)

The source code:

def powerpoint(powerpointfile, psfile, printer):
    pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
    myPowerpoint = win32com.client.DispatchEx('Powerpoint.Application')
    myPpt = myPowerpoint.Presentations.Open(powerpointfile, False, False, False)
    myPpt.PrintOptions.PrintInBackground = 0
    myPpt.PrintOptions.ActivePrinter = printer
    myPpt.Saved = 1
    myPpt.PrintOut(1, 5000, psfile, 0, False)
    myPpt.Close()
    #myPowerpoint.Quit()
    del myPpt
    #del myPowerpoint
    pythoncom.CoUninitialize()

Automating Microsoft Word

One small example how to automate Microsoft Word and printout a
postscript file with a specified postscript printer (yes, more than one
printers can be installed on the system).

Multithreadding:

Unlike
Powerpoint Microsoft Word can run in multiple instances – If a program
creates more Word processes you will see them in the task manager.

How to call the function:

You simply call the function with the name of the Word file, Postscript file and the printername which you want to use.:

eg.
make_ps.word(‘c:\test\wordfilename.doc’, ‘c:\test\psfilename.ps’, ‘My Postscript Printername’)

The source code:

import win32com.client, pythoncom, time

def word(wordfile, psfile, printer):
    pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
    myWord = win32com.client.DispatchEx('Word.Application')
    myWord.Application.ActivePrinter = printer
    myDoc = myWord.Documents.Open(wordfile, False, False, False)
    myDoc.Saved=1
    myWord.Application.NormalTemplate.Saved = 1
    myWord.PrintOut(True, False, 0, psfile)
    while myWord.BackgroundPrintingStatus > 0:
        time.sleep(0.1)
    myDoc.Close()
    myWord.Quit()
    del myDoc
    del myWord
    pythoncom.CoUninitialize()

Print all events from Windows Event Log

This example prints all events from event log:

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_NTLogEvent")
for objItem in colItems:
    print "Category: ", objItem.Category
    print "Category String: ", objItem.CategoryString
    print "Computer Name: ", objItem.ComputerName
    z = objItem.Data
    if z is None:
        a = 1
    else:
        for x in z:
            print "Data: ", x
    print "Event Code: ", objItem.EventCode
    print "Event Identifier: ", objItem.EventIdentifier
    print "Event Type: ", objItem.EventType
    z = objItem.InsertionStrings
    if z is None:
        a = 1
    else:
        for x in z:
            print "Insertion Strings: ", x
    print "Logfile: ", objItem.Logfile
    print "Message: ", objItem.Message
    print "Record Number: ", objItem.RecordNumber
    print "Source Name: ", objItem.SourceName
    print "Time Generated: ", objItem.TimeGenerated
    print "Time Written: ", objItem.TimeWritten
    print "Type: ", objItem.Type
    print "User: ", objItem.User 

Submitting values and clicking buttons in IE

Submits data to a website and / or clicks on a specific button using COM.

# Use the makepy utility for the "Microsoft Internet Controls (1.1)"
# object library to get early binding.
from win32com.client import Dispatch
from time import sleep

ie = Dispatch("InternetExplorer.Application")  #Create browser instance.
ie.Visible = 1      # Make it visible (0 = invisible)
ie.Navigate("http://www.google.com")
while ie.ReadyState != 4:    # Wait for browser to finish loading.
    sleep(1)

doc = ie.Document   # Get the document.
while doc.readyState != "complete": # Wait for document to finish
    sleep(1)
   
doc.f.q.value = "qwerty"    # form name is 'f'; search field name is 'q'
doc.f.submit()  # Submits form using default button (in this case, btnG)
# OR alternatively you can specify which button to click as follows...
# doc.f.btnI.click()    # click on button 'btnI'

# Note:  You can also reference the forms by the order in which they
# appear in the forms collection.  For example, you could use the
# following code as well which references the first form.
# doc.forms[0].q.value = 'qwerty'

Automating Microsoft Excel

One more example how to automate Microsoft Excel and printout a
postscript file with a specified postscript printer (yes more than one
printer can be installed on the system).

But unlike Word you can not check the background printing status in
Excel with the method "BackgroundPrintingStatus". This shouldn`t make
problems. I didn`t found an afvantage of this feature.

Multi-Threadding:

Unlike Powerpoint Excel works in more than one instances.

How to call the function:

You simply call the function with the name of the Word file, Postscript file and the printername which you want to use.:

The source code:

def excel(excelfile, psfile, printer):
    pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
    myExcel = win32com.client.DispatchEx('Excel.Application')
    myExcel.Application.AskToUpdateLinks = 0
    Excel = myExcel.Workbooks.Open(excelfile, 0, False, 2)
    Excel.Saved = 1
    Excel.PrintOut(1, 5000, 1, False, printer, True, False, psfile)
    Excel.Close()
    myExcel.Quit()
    del myExcel
    del Excel
    pythoncom.CoUninitialize()
excel('c:/test/excelfilename.xls', 'c:/test/psfilename.ps', 'My Postscript Printername')

Speak what I type

This script uses the Microsoft Speech SDK to speak what you type in
from the keyboard. To stop the script use STRG+Z. MS Speech Engine has
to be installed and makepy should be executed for the MS Speech Object
Library.

import sys
from win32com.client import constants
import win32com.client

speaker = win32com.client.Dispatch("SAPI.SpVoice")
print "Type word or phrase, then enter."
print "Ctrl+Z then enter to exit."
while 1:
   try:
      s = raw_input()
      speaker.Speak(s)
   except:
      if sys.exc_type is EOFError:
         sys.exit()

Shellexecute – Printing with the default application

This script prints the file in the first argument with the windows default application.

Example:

If you save the code in the file print.py:

print.py test.doc -> Opens Microsoft Word (if it is installed) and prints the file test.py to the default printer.

print.py mytextfile.txt -> Same. But prints with Notepad

from win32api import ShellExecute
from sys import argv

ShellExecute(0, "print", argv[1], None, "", 1)

Directory Watcher

You can use this script, if you want to watch for activity on a
directory. It shows you every write and delete of a file in a specified
directory.

import os, time
path_to_watch = "c:\temp"
before = dict ([(f, None) for f in os.listdir (path_to_watch)]) 
while 1: 
  time.sleep (10) 
  after = dict ([(f, None) for f in os.listdir (path_to_watch)]) 
  added = [f for f in after if not f in before] 
  removed = [f for f in before if not f in after] 
  if added: print "Added: ", ", .join (added) 
  if removed: print "Removed: ", ", ".join (removed) 
  before = after

Show all processes with IDs

This script shows all running processes with their process IDs. It uses the wmi-class from Tim Golden. Please put it into the directory where you run this script from.

import wmi 
c = wmi.WMI () 
for process in c.Win32_Process ():
    print process.ProcessId, process.Name