Example for connect to Internet via Modem, ISDN, ADSL, …
import win32ras # Dialup with a RAS entry win32ras.Dial ( None, None, ("windows_ras_entry_name", "", "", "username", "password", ""), None ) # Hangup the connection win32ras.HangUp ()
Automation of Applications with Python for Windows – The Script Collection
Example for connect to Internet via Modem, ISDN, ADSL, …
import win32ras # Dialup with a RAS entry win32ras.Dial ( None, None, ("windows_ras_entry_name", "", "", "username", "password", ""), None ) # Hangup the connection win32ras.HangUp ()
import win32com.client wordapp = win32com.client.Dispatch("Word.Application") # Create new Word Object wordapp.Visible = 0 # Word Application should`t be visible worddoc = wordapp.Documents.Add() # Create new Document Object worddoc.PageSetup.Orientation = 1 # Make some Setup to the Document: worddoc.PageSetup.LeftMargin = 20 worddoc.PageSetup.TopMargin = 20 worddoc.PageSetup.BottomMargin = 20 worddoc.PageSetup.RightMargin = 20 worddoc.Content.Font.Size = 11 worddoc.Content.Paragraphs.TabStops.Add (100) worddoc.Content.Text = "Hello, I am a text!" worddoc.Content.MoveEnd worddoc.Close() # Close the Word Document (a save-Dialog pops up) wordapp.Quit() # Close the Word Application
This script is designed as a Windows 2000/NT Service and converts incoming Excel Workbooks in a directory to PDF. After installing this script with python scriptname.py install you will find a Service called “Excel2PDF” in the Service Control Manager (Services). To remove the Service do a python scriptname.py remove.
One Problem exists: The Service runs only when a user is logged in. If someone knows the problem please mail it via the contact webform.
To get the usage information start this script with the python interpreter as usually.
import win32serviceutil import win32service import win32event import win32gui import time import win32com.client import pythoncom import os class XLS2PDFService(win32serviceutil.ServiceFramework): _svc_name_ = "xls2pdf Service" _svc_display_name_ = "Excel2PDF" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) win32gui.MessageBox(0, "XLS2PDF Service has been stopped" , "XLS2PDF Status" , 0 ) def SvcDoRun(self): gscommand = 'c:\\gs\\gs8.15\\bin\\gswin32c.exe -sDEVICE=pdfwrite -r300 \ -dNOPAUSE -dBATCH -dSAFER -sPAPERSIZE=a4 \ -sOutputFile="'+path_to_watch+filename+'.pdf" "'+tmpfile+'"' path_to_watch = 'd:\\share\\' tmpdir = tempfile.mkdtemp() before = dict ([(f, None) for f in os.listdir (path_to_watch)]) win32gui.MessageBox(0, "XLS2PDF has been started" , "XLS2PDF Status" , 0 ) while 1 : time.sleep (0.1) after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] if added and added[0][-3:]=='xls': print os.tmpfile() filename = added[0] tmpfile = tmpdir + '\\'+filename+'.ps' if filename[-3:]=='xls': pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myExcel = win32com.client.DispatchEx('Excel.Application') Excel = myExcel.Workbooks.Open(path_to_watch + filename, 0, False, 2) Excel.PrintOut(1, 5000, 1, False, 'ServPDF', True, False, tmpfile) Excel.Saved = 1 Excel.Close() myExcel.Quit() del Excel del myExcel os.popen(gscommand) #os.remove(path_to_watch+filename) os.remove(tmpfile) pythoncom.CoUninitialize() before = after if __name__=='__main__': win32serviceutil.HandleCommandLine(XLS2PDFService)
#Lists information about all the printers connected to a print server. import win32com.client strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("Select * from Win32_Printer") for objItem in colItems: print "Attributes: ", objItem.Attributes print "Availability: ", objItem.Availability z = objItem.AvailableJobSheets if z is None: a = 1 else: for x in z: print "Available Job Sheets: ", x print "Average Pages Per Minute: ", objItem.AveragePagesPerMinute z = objItem.Capabilities if z is None: a = 1 else: for x in z: print "Capabilities: ", x z = objItem.CapabilityDescriptions if z is None: a = 1 else: for x in z: print "Capability Descriptions: ", x print "Caption: ", objItem.Caption z = objItem.CharSetsSupported if z is None: a = 1 else: for x in z: print "Char Sets Supported: ", x print "Comment: ", objItem.Comment print "Config Manager Error Code: ", objItem.ConfigManagerErrorCode print "Config Manager User Config: ", objItem.ConfigManagerUserConfig print "Creation Class Name: ", objItem.CreationClassName z = objItem.CurrentCapabilities if z is None: a = 1 else: for x in z: print "Current Capabilities: ", x print "Current Char Set: ", objItem.CurrentCharSet print "Current Language: ", objItem.CurrentLanguage print "Current Mime Type: ", objItem.CurrentMimeType print "Current Natural Language: ", objItem.CurrentNaturalLanguage print "Current Paper Type: ", objItem.CurrentPaperType print "Default: ", objItem.Default z = objItem.DefaultCapabilities if z is None: a = 1 else: for x in z: print "Default Capabilities: ", x print "Default Copies: ", objItem.DefaultCopies print "Default Language: ", objItem.DefaultLanguage print "Default Mime Type: ", objItem.DefaultMimeType print "Default Number Up: ", objItem.DefaultNumberUp print "Default Paper Type: ", objItem.DefaultPaperType print "Default Priority: ", objItem.DefaultPriority print "Description: ", objItem.Description print "Detected Error State: ", objItem.DetectedErrorState print "Device ID: ", objItem.DeviceID print "Direct: ", objItem.Direct print "Do Complete First: ", objItem.DoCompleteFirst print "Driver Name: ", objItem.DriverName print "Enable BIDI: ", objItem.EnableBIDI print "Enable Dev Query Print: ", objItem.EnableDevQueryPrint print "Error Cleared: ", objItem.ErrorCleared print "Error Description: ", objItem.ErrorDescription z = objItem.ErrorInformation if z is None: a = 1 else: for x in z: print "Error Information: ", x print "Extended Detected Error State: ", objItem.ExtendedDetectedErrorState print "Extended Printer Status: ", objItem.ExtendedPrinterStatus print "Hidden: ", objItem.Hidden print "Horizontal Resolution: ", objItem.HorizontalResolution print "Install Date: ", objItem.InstallDate print "Job Count Since Last Reset: ", objItem.JobCountSinceLastReset print "Keep Printed Jobs: ", objItem.KeepPrintedJobs z = objItem.LanguagesSupported if z is None: a = 1 else: for x in z: print "Languages Supported: ", x print "Last Error Code: ", objItem.LastErrorCode print "Local: ", objItem.Local print "Location: ", objItem.Location print "Marking Technology: ", objItem.MarkingTechnology print "Max Copies: ", objItem.MaxCopies print "Max Number Up: ", objItem.MaxNumberUp print "Max Size Supported: ", objItem.MaxSizeSupported z = objItem.MimeTypesSupported if z is None: a = 1 else: for x in z: print "Mime Types Supported: ", x print "Name: ", objItem.Name z = objItem.NaturalLanguagesSupported if z is None: a = 1 else: for x in z: print "Natural Languages Supported: ", x print "Network: ", objItem.Network z = objItem.PaperSizesSupported if z is None: a = 1 else: for x in z: print "Paper Sizes Supported: ", x z = objItem.PaperTypesAvailable if z is None: a = 1 else: for x in z: print "Paper Types Available: ", x print "Parameters: ", objItem.Parameters print "PNP Device ID: ", objItem.PNPDeviceID print "Port Name: ", objItem.PortName z = objItem.PowerManagementCapabilities if z is None: a = 1 else: for x in z: print "Power Management Capabilities: ", x print "Power Management Supported: ", objItem.PowerManagementSupported z = objItem.PrinterPaperNames if z is None: a = 1 else: for x in z: print "Printer Paper Names: ", x print "Printer State: ", objItem.PrinterState print "Printer Status: ", objItem.PrinterStatus print "Print Job Data Type: ", objItem.PrintJobDataType print "Print Processor: ", objItem.PrintProcessor print "Priority: ", objItem.Priority print "Published: ", objItem.Published print "Queued: ", objItem.Queued print "Raw Only: ", objItem.RawOnly print "Separator File: ", objItem.SeparatorFile print "Server Name: ", objItem.ServerName print "Shared: ", objItem.Shared print "Share Name: ", objItem.ShareName print "Spool Enabled: ", objItem.SpoolEnabled print "Start Time: ", objItem.StartTime print "Status: ", objItem.Status print "Status Info: ", objItem.StatusInfo print "System Creation Class Name: ", objItem.SystemCreationClassName print "System Name: ", objItem.SystemName print "Time Of Last Reset: ", objItem.TimeOfLastReset print "Until Time: ", objItem.UntilTime print "Vertical Resolution: ", objItem.VerticalResolution print "Work Offline: ", objItem.WorkOffline print "-------------------------------------------------------"
#Lists properties and capabilities for all the printers installed on a computer. import win32com.client strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("Select * from Win32_PrinterConfiguration") for objItem in colItems: print "Bits Per Pel: ", objItem.BitsPerPel print "Caption: ", objItem.Caption print "Collate: ", objItem.Collate print "Color: ", objItem.Color print "Copies: ", objItem.Copies print "Description: ", objItem.Description print "Device Name: ", objItem.DeviceName print "Display Flags: ", objItem.DisplayFlags print "Display Frequency: ", objItem.DisplayFrequency print "Dither Type: ", objItem.DitherType print "Driver Version: ", objItem.DriverVersion print "Duplex: ", objItem.Duplex print "Form Name: ", objItem.FormName print "Horizontal Resolution: ", objItem.HorizontalResolution print "ICM Intent: ", objItem.ICMIntent print "ICM Method: ", objItem.ICMMethod print "Log Pixels: ", objItem.LogPixels print "Media Type: ", objItem.MediaType print "Name: ", objItem.Name print "Orientation: ", objItem.Orientation print "Paper Length: ", objItem.PaperLength print "Paper Size: ", objItem.PaperSize print "Paper Width: ", objItem.PaperWidth print "Pels Height: ", objItem.PelsHeight print "Pels Width: ", objItem.PelsWidth print "Print Quality: ", objItem.PrintQuality print "Scale: ", objItem.Scale print "Setting ID: ", objItem.SettingID print "Specification Version: ", objItem.SpecificationVersion print "TT Option: ", objItem.TTOption print "Vertical Resolution: ", objItem.VerticalResolution print "X Resolution: ", objItem.XResolution print "Y Resolution: ", objItem.YResolution print "---------------------------------------------------"
#Returns information for each print job on a computer. import win32com.client strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("Select * from Win32_PrintJob") for objItem in colItems: print "Caption: ", objItem.Caption print "Data Type: ", objItem.DataType print "Description: ", objItem.Description print "Document: ", objItem.Document print "Driver Name: ", objItem.DriverName print "Elapsed Time: ", objItem.ElapsedTime print "Host Print Queue: ", objItem.HostPrintQueue print "Install Date: ", objItem.InstallDate print "Job Id: ", objItem.JobId print "Job Status: ", objItem.JobStatus print "Name: ", objItem.Name print "Notify: ", objItem.Notify print "Owner: ", objItem.Owner print "Pages Printed: ", objItem.PagesPrinted print "Parameters: ", objItem.Parameters print "Print Processor: ", objItem.PrintProcessor print "Priority: ", objItem.Priority print "Size: ", objItem.Size print "Start Time: ", objItem.StartTime print "Status: ", objItem.Status print "Status Mask: ", objItem.StatusMask print "Time Submitted: ", objItem.TimeSubmitted print "Total Pages: ", objItem.TotalPages print "Until Time: ", objItem.UntilTime
This Python module can be used to convert files from Microsoft
Office to Postscript. Remember: To print out Postscript files from Microsoft Office you need a virtual Postscript printer.
Alternatively you can download this tool from here too.
import win32com.client, time, pythoncom """ MSOffice2PS - Microsoft Office to Postscript Converter 1.1 Makes a Postscript file from Word-, Excel- or Powerpoint. Now with mutex support for Powerpoint. Because Powerpoint can only run as a single instance. Line 57 must have a unique GUID. You can create a new GUID via: i mport pythoncom print pythoncom.CreateGuid() usage: first: import msoffice2ps in the script, where it should be used then call the convert-function. import msoffice2ps msoffice2ps.word('wordfilename', 'psfilename', 'ps_printername') msoffice2ps.excel('excelfilename', 'psfilename', 'ps_printername') msoffice2ps.powerpoint('powerpointfilename', 'psfilename', 'ps_printername') Dipl.-Ing. Mustafa Goermezer -> http://www.goermezer.de """ 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() 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() def powerpoint(powerpointfile, psfile, printer): from win32event import CreateMutex from win32api import GetLastError from winerror import ERROR_ALREADY_EXISTS from sys import exit #the guid in the next line must be unique !!! handle = CreateMutex ( None, 1, '{8620EF5C-7ED7-4A46-834B-3C9220566F69}' ) if GetLastError ( ) == ERROR_ALREADY_EXISTS: print 'Powerpoint conversion already working' exit ( 1 ) 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()
# Inigo Surguy (inigosurguy at hotmail.com) # Sample code for speech recognition using the MS Speech API from win32com.client import constants import win32com.client import pythoncom """Sample code for using the Microsoft Speech SDK 5.1 via COM in Python. Requires that the SDK be installed (it's a free download from http://www.microsoft.com/speech and that MakePy has been used on it (in PythonWin, select Tools | COM MakePy Utility | Microsoft Speech Object Library 5.1). After running this, then saying "One", "Two", "Three" or "Four" should display "You said One" etc on the console. The recognition can be a bit shaky at first until you've trained it (via the Speech entry in the Windows Control Panel.""" class SpeechRecognition: """ Initialize the speech recognition with the passed in list of words """ def __init__(self, wordsToAdd): # For text-to-speech self.speaker = win32com.client.Dispatch("SAPI.SpVoice") # For speech recognition - first create a listener self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer") # Then a recognition context self.context = self.listener.CreateRecoContext() # which has an associated grammar self.grammar = self.context.CreateGrammar() # Do not allow free word recognition - only command and control # recognizing the words in the grammar only self.grammar.DictationSetState(0) # Create a new rule for the grammar, that is top level (so it begins # a recognition) and dynamic (ie we can change it at runtime) self.wordsRule = self.grammar.Rules.Add("wordsRule", constants.SRATopLevel + constants.SRADynamic, 0) # Clear the rule (not necessary first time, but if we're changing it # dynamically then it's useful) self.wordsRule.Clear() # And go through the list of words, adding each to the rule [ self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd ] # Set the wordsRule to be active self.grammar.Rules.Commit() self.grammar.CmdSetRuleState("wordsRule", 1) # Commit the changes to the grammar self.grammar.Rules.Commit() # And add an event handler that's called back when recognition occurs self.eventHandler = ContextEvents(self.context) # Announce we've started self.say("Started successfully") """Speak a word or phrase""" def say(self, phrase): self.speaker.Speak(phrase) """The callback class that handles the events raised by the speech object. See "Automation | SpSharedRecoContext (Events)" in the MS Speech SDK online help for documentation of the other events supported. """ class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")): """Called when a word/phrase is successfully recognized - ie it is found in a currently open grammar with a sufficiently high confidence""" def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): newResult = win32com.client.Dispatch(Result) print "You said: ",newResult.PhraseInfo.GetText() if __name__=='__main__': wordsToAdd = [ "One", "Two", "Three", "Four" ] speechReco = SpeechRecognition(wordsToAdd) while 1: pythoncom.PumpWaitingMessages()
I didn`t test this example. But it shows how to manipulate data in Lotus notes with Python/Pywin32:
import win32com.client
import win32com.client sess=win32com.client.Dispatch("Lotus.NotesSession") db=sess.GetDatabase("","log.nsf") print db.Title
I found this Windows Media Player example on a website:
You can automate Microsoft Media Player with win32com without
starting the GUI.This example opens and plays some media files:
# this program will play MP3, WMA, MID, WAV files via the WindowsMediaPlayer from win32com.client import Dispatch mp = Dispatch("WMPlayer.OCX") # use an mp3 file you have ... #tune = mp.newMedia("C:/Program Files/Common Files/HP/Memories Disc/2.0/audio/Swing.mp3") # or copy one to the working folder ... #tune = mp.newMedia("Bier1.mp3") # you can also play wma files, this cool sound came with XP ... tune = mp.newMedia("C:/WINDOWS/system32/oobe/images/title.wma") mp.currentPlaylist.appendItem(tune) mp.controls.play() # to stop playing use raw_input("Press Enter to stop playing") mp.controls.stop()