Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Capture and email a traceback in Python

   1  
   2  import traceback, smtplib, StringIO
   3  fp = StringIO.StringIO()
   4  traceback.print_exc(file=fp)
   5  message = fp.getvalue()
   6  server = smtplib.SMTP(FAILURE_SERVER)
   7  server.sendmail(
   8    FAILURE_FROM,
   9    FAILURE_TO,
  10    FAILURE_MESSAGE + '\n\n' + message,
  11  )
  12  server.quit()

Send email with attachment(s) in Python

Can't remember if I wrote this or found it on the Web or a combination, so I won't take credit per se -- I'm just posting it as reference.

   1  
   2  import smtplib
   3  import os
   4  from email.MIMEMultipart import MIMEMultipart
   5  from email.MIMEBase import MIMEBase
   6  from email.MIMEText import MIMEText
   7  from email.Utils import COMMASPACE, formatdate
   8  from email import Encoders
   9  
  10  def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
  11    assert type(send_to)==list
  12    assert type(files)==list
  13  
  14    msg = MIMEMultipart()
  15    msg['From'] = send_from
  16    msg['To'] = COMMASPACE.join(send_to)
  17    msg['Date'] = formatdate(localtime=True)
  18    msg['Subject'] = subject
  19  
  20    msg.attach( MIMEText(text) )
  21  
  22    for f in files:
  23      part = MIMEBase('application', "octet-stream")
  24      part.set_payload( open(file,"rb").read() )
  25      Encoders.encode_base64(part)
  26      part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
  27      msg.attach(part)
  28  
  29    smtp = smtplib.SMTP(server)
  30    smtp.sendmail(send_from, send_to, msg.as_string())
  31    smtp.close()

Script Word from Python

A quick and dirty class for working with Word via COM in Python. By far, not all of the power of Word is available here, but it's a good start for simple tasks.

   1  
   2  from win32com.client import constants, Dispatch
   3  
   4  import pythoncom
   5  
   6  wdStory = 6
   7  
   8  class WordDocument(object):
   9    """
  10    Some convenience methods for Word documents accessed
  11    through COM.
  12    """
  13    
  14    def __init__(self, visible=False):
  15      self.app = Dispatch("Word.Application")
  16      self.app.Visible = visible
  17    
  18    def new(self, filename=None):
  19      """
  20      Create a new Word document. If 'filename' specified,
  21      use the file as a template.
  22      """
  23      self.app.Documents.Add(filename)
  24    
  25    def open(self, filename):
  26      """
  27      Open an existing Word document for editing.
  28      """
  29      self.app.Documents.Open(filename)
  30    
  31    def save(self, filename=None):
  32      """
  33      Save the active document. If 'filename' is given,
  34      do a Save As.
  35      """
  36      if filename:
  37        self.app.ActiveDocument.SaveAs(filename)
  38      else:
  39        self.app.ActiveDocument.Save()
  40    
  41    def save_as(self, filename):
  42      return self.save(filename)
  43    
  44    def print_out(self):
  45      """
  46      Print the active document.
  47      """
  48      self.app.Application.PrintOut()
  49    
  50    def close(self):
  51      """
  52      Close the active document.
  53      """
  54      self.app.ActiveDocument.Close()
  55    
  56    def quit(self):
  57      """
  58      Quit Word.
  59      """
  60      return self.app.Quit()
  61    
  62    def find_and_replace(self, find_str, replace_str):
  63      """
  64      Find all occurances of 'find_str' and replace with 'replace_str'
  65      in the active document.
  66      """
  67      self.app.Selection.HomeKey(Unit=wdStory)
  68      find = self.app.Selection.Find
  69      find.Text = find_str
  70      while self.app.Selection.Find.Execute():
  71        self.app.Selection.TypeText(Text=replace_str)

Script Excel from Python

A quick and dirty class for working with Excel via COM in Python. By far, not all of the power of Excel is available here, but it's a good start for simple tasks.

   1  
   2  from win32com.client import constants, Dispatch
   3  import pythoncom
   4  import os
   5  
   6  borderTop = 3
   7  borderBottom = 4
   8  borderLeft = 1
   9  borderRight = 2
  10  borderSolid = 1
  11  borderDashed = 2
  12  borderDotted = 3
  13  colorBlack = 1
  14  directionUp = -4162
  15  directionDown = -4121
  16  directionLeft = -4131
  17  directionRight = -4152
  18  
  19  class ExcelDocument(object):
  20    """
  21    Some convenience methods for Excel documents accessed
  22    through COM.
  23    """
  24    
  25    def __init__(self, visible=False):
  26      self.app = Dispatch("Excel.Application")
  27      self.app.Visible = visible
  28      self.sheet = 1
  29    
  30    def new(self, filename=None):
  31      """
  32      Create a new Excel workbook. If 'filename' specified,
  33      use the file as a template.
  34      """
  35      self.app.Workbooks.Add(filename)
  36    
  37    def open(self, filename):
  38      """
  39      Open an existing Excel workbook for editing.
  40      """
  41      self.app.Workbooks.Open(filename)
  42    
  43    def set_sheet(self, sheet):
  44      """
  45      Set the active worksheet.
  46      """
  47      self.sheet = sheet
  48    
  49    def get_range(self, range):
  50      """
  51      Get a range object for the specified range or single cell.
  52      """
  53      return self.app.ActiveWorkbook.Sheets(self.sheet).Range(range)
  54    
  55    def set_value(self, cell, value=''):
  56      """
  57      Set the value of 'cell' to 'value'.
  58      """
  59      self.get_range(cell).Value = value
  60    
  61    def get_value(self, cell):
  62      """
  63      Get the value of 'cell'.
  64      """
  65      value = self.get_range(cell).Value
  66      if isinstance(value, tuple):
  67        value = [v[0] for v in value]
  68      return value
  69    
  70    def set_border(self, range, side, line_style=borderSolid, color=colorBlack):
  71      """
  72      Set a border on the specified range of cells or single cell.
  73      'range' = range of cells or single cell
  74      'side' = one of borderTop, borderBottom, borderLeft, borderRight
  75      'line_style' = one of borderSolid, borderDashed, borderDotted, others?
  76      'color' = one of colorBlack, others?
  77      """
  78      range = self.get_range(range).Borders(side)
  79      range.LineStyle = line_style
  80      range.Color = color
  81    
  82    def sort(self, range, key_cell):
  83      """
  84      Sort the specified 'range' of the activeworksheet by the
  85      specified 'key_cell'.
  86      """
  87      range.Sort(Key1=self.get_range(key_cell), Order1=1, Header=0, OrderCustom=1, MatchCase=False, Orientation=1)
  88    
  89    def hide_row(self, row, hide=True):
  90      """
  91      Hide the specified 'row'.
  92      Specify hide=False to show the row.
  93      """
  94      self.get_range('a%s' % row).EntireRow.Hidden = hide
  95    
  96    def hide_column(self, column, hide=True):
  97      """
  98      Hide the specified 'column'.
  99      Specify hide=False to show the column.
 100      """
 101      self.get_range('%s1' % column).EntireColumn.Hidden = hide
 102    
 103    def delete_row(self, row, shift=directionUp):
 104      """
 105      Delete the entire 'row'.
 106      """
 107      self.get_range('a%s' % row).EntireRow.Delete(Shift=shift)
 108    
 109    def delete_column(self, column, shift=directionLeft):
 110      """
 111      Delete the entire 'column'.
 112      """
 113      self.get_range('%s1' % column).EntireColumn.Delete(Shift=shift)
 114      
 115    def fit_column(self, column):
 116      """
 117      Resize the specified 'column' to fit all its contents.
 118      """
 119      self.get_range('%s1' % column).EntireColumn.AutoFit()
 120    
 121    def save(self):
 122      """
 123      Save the active workbook.
 124      """
 125      self.app.ActiveWorkbook.Save()
 126    
 127    def save_as(self, filename, delete_existing=False):
 128      """
 129      Save the active workbook as a different filename.
 130      If 'delete_existing' is specified and the file already
 131      exists, it will be deleted before saving.
 132      """
 133      if delete_existing and os.path.exists(filename):
 134        os.remove(filename)
 135      self.app.ActiveWorkbook.SaveAs(filename)
 136    
 137    def print_out(self):
 138      """
 139      Print the active workbook.
 140      """
 141      self.app.Application.PrintOut()
 142    
 143    def close(self):
 144      """
 145      Close the active workbook.
 146      """
 147      self.app.ActiveWorkbook.Close()
 148    
 149    def quit(self):
 150      """
 151      Quit Excel.
 152      """
 153      return self.app.Quit()

Capitalize Proper Names

A function and a String-based class for properly capitalizing a proper name. I hope this isn't too big to be considered a "snippet". To see it in action, save the snippet to a .py file and run it from a terminal.

   1  
   2  # -*- coding: iso-8859-1 -*-
   3  
   4  # The code here is based loosely on John Cardinal's notes found at:
   5  # http://www.johncardinal.com/tmgutil/capitalizenames.htm
   6  
   7  # 2006-03-16
   8  # Thanks to David Kern <kernd@reasonspace.com> for fixing some bugs.
   9  
  10  suffixes = ["II", "(II)", "III", "(III)", "IV", "(IV)", "VI", "(VI)", "VII", "(VII)", "2nd", "(2nd)", "3rd", "(3rd)", "4th", "(4th)", "5th", "(5th)"]
  11  
  12  # The names listed here are included by permission from John Cardinal's TMG Utility.
  13  # http://www.johncardinal.com/tmgutil/index.htm
  14  # John Cardinal maintains the copyright for this list of names.
  15  surnames = ["ApShaw", "d'Albini", "d'Aubigney", "d'Aubigné", "d'Autry", "d'Entremont", "d'Hurst", "D'ovidio", "da Graça", "DaSilva", "DeAnda", "deAnnethe", "deAubigne", "deAubigny", "DeBardelaben", "DeBardeleben", "DeBaugh", "deBeauford", "DeBerry", "deBethune", "DeBetuile", "DeBoard", "DeBoer", "DeBohun", "DeBord", "DeBose", "DeBrouwer", "DeBroux", "DeBruhl", "deBruijn", "deBrus", "deBruse", "deBrusse", "DeBruyne", "DeBusk", "DeCamp", "deCastilla", "DeCello", "deClare", "DeClark", "DeClerck", "DeCoste", "deCote", "DeCoudres", "DeCoursey", "DeCredico", "deCuire", "DeCuyre", "DeDominicios", "DeDuyster", "DeDuytscher", "DeDuytser", "deFiennes", "DeFord", "DeForest", "DeFrance", "DeFriece", "DeGarmo", "deGraaff", "DeGraff", "DeGraffenreid", "DeGraw", "DeGrenier", "DeGroats", "DeGroft", "DeGrote", "DeHaan", "DeHaas", "DeHaddeclive", "deHannethe", "DeHatclyf", "DeHaven", "DeHeer", "DeJager", "DeJarnette", "DeJean", "DeJong", "deJonge", "deKemmeter", "deKirketon", "DeKroon", "deKype", "del-Rosario", "dela Chamotte", "DeLa Cuadra", "DeLa Force", "dela Fountaine", "dela Greña", "dela Place", "DeLa Ward", "DeLaci", "DeLacy", "DeLaet", "DeLalonde", "DelAmarre", "DeLancey", "DeLascy", "DelAshmutt", "DeLassy", "DeLattre", "DeLaughter", "DeLay", "deLessine", "DelGado", "DelGaudio", "DeLiberti", "DeLoache", "DeLoatch", "DeLoch", "DeLockwood", "DeLong", "DeLozier", "DeLuca", "DeLucenay", "deLucy", "DeMars", "DeMartino", "deMaule", "DeMello", "DeMinck", "DeMink", "DeMoree", "DeMoss", "DeMott", "DeMuynck", "deNiet", "DeNise", "DeNure", "DePalma", "DePasquale", "dePender", "dePercy", "DePoe", "DePriest", "DePu", "DePui", "DePuis", "DeReeper", "deRochette", "deRose", "DeRossett", "DeRover", "deRuggele", "deRuggle", "DeRuyter", "deSaint-Sauveur", "DeSantis", "desCuirs", "DeSentis", "DeShane", "DeSilva", "DesJardins", "DesMarest", "deSoleure", "DeSoto", "DeSpain", "DeStefano", "deSwaert", "deSwart", "DeVall", "DeVane", "DeVasher", "DeVasier", "DeVaughan", "DeVaughn", "DeVault", "DeVeau", "DeVeault", "deVilleneuve", "DeVilliers", "DeVinney", "DeVito", "deVogel", "DeVolder", "DeVolld", "DeVore", "deVos", "DeVries", "deVries", "DeWall", "DeWaller", "DeWalt", "deWashington", "deWerly", "deWessyngton", "DeWet", "deWinter", "DeWitt", "DeWolf", "DeWolfe", "DeWolff", "DeWoody", "DeYager", "DeYarmett", "DeYoung", "DiCicco", "DiCredico", "DiFillippi", "DiGiacomo", "DiMarco", "DiMeo", "DiMonte", "DiNonno", "DiPietro", "diPilato", "DiPrima", "DiSalvo", "du Bosc", "du Hurst", "DuFort", "DuMars", "DuPre", "DuPue", "DuPuy", "FitzUryan", "kummel", "LaBarge", "LaBarr", "LaBauve", "LaBean", "LaBelle", "LaBerteaux", "LaBine", "LaBonte", "LaBorde", "LaBounty", "LaBranche", "LaBrash", "LaCaille", "LaCasse", "LaChapelle", "LaClair", "LaComb", "LaCoste", "LaCount", "LaCour", "LaCroix", "LaFarlett", "LaFarlette", "LaFerry", "LaFlamme", "LaFollette", "LaForge", "LaFortune", "LaFoy", "LaFramboise", "LaFrance", "LaFuze", "LaGioia", "LaGrone", "LaLiberte", "LaLonde", "LaLone", "LaMaster", "LaMay", "LaMere", "LaMont", "LaMotte", "LaPeer", "LaPierre", "LaPlante", "LaPoint", "LaPointe", "LaPorte", "LaPrade", "LaRocca", "LaRochelle", "LaRose", "LaRue", "LaVallee", "LaVaque", "LaVeau", "LeBleu", "LeBoeuf", "LeBoiteaux", "LeBoyteulx", "LeCheminant", "LeClair", "LeClerc", "LeCompte", "LeCroy", "LeDuc", "LeFevbre", "LeFever", "LeFevre", "LeFlore", "LeGette", "LeGrand", "LeGrave", "LeGro", "LeGros", "LeJeune", "LeMaistre", "LeMaitre", "LeMaster", "LeMesurier", "LeMieux", "LeMoe", "LeMoigne", "LeMoine", "LeNeve", "LePage", "LeQuire", "LeQuyer", "LeRou", "LeRoy", "LeSuer", "LeSueur", "LeTardif", "LeVally", "LeVert", "LoMonaco", "Macabe", "Macaluso", "MacaTasney", "Macaulay", "Macchitelli", "Maccoone", "Maccurry", "Macdermattroe", "Macdiarmada", "Macelvaine", "Macey", "Macgraugh", "Machan", "Machann", "Machum", "Maciejewski", "Maciel", "Mackaben", "Mackall", "Mackartee", "Mackay", "Macken", "Mackert", "Mackey", "Mackie", "Mackin", "Mackins", "Macklin", "Macko", "Macksey", "Mackwilliams", "Maclean", "Maclinden", "Macomb", "Macomber", "Macon", "Macoombs", "Macraw", "Macumber", "Macurdy", "Macwilliams", "MaGuinness", "MakCubyn", "MakCumby", "Mcelvany", "Mcsherry", "Op den Dyck", "Op den Graeff", "regory", "Schweißguth", "StElmo", "StGelais", "StJacques", "te Boveldt", "VanAernam", "VanAken", "VanAlstine", "VanAmersfoort", "VanAntwerp", "VanArlem", "VanArnam", "VanArnem", "VanArnhem", "VanArnon", "VanArsdale", "VanArsdalen", "VanArsdol", "vanAssema", "vanAsten", "VanAuken", "VanAwman", "VanBaucom", "VanBebber", "VanBeber", "VanBenschoten", "VanBibber", "VanBilliard", "vanBlare", "vanBlaricom", "VanBuren", "VanBuskirk", "VanCamp", "VanCampen", "VanCleave", "VanCleef", "VanCleve", "VanCouwenhoven", "VanCovenhoven", "VanCowenhoven", "VanCuren", "VanDalsem", "VanDam", "VanDe Poel", "vanden Dijkgraaf", "vanden Kommer", "VanDer Aar", "vander Gouwe", "VanDer Honing", "VanDer Hooning", "vander Horst", "vander Kroft", "vander Krogt", "VanDer Meer", "vander Meulen", "vander Putte", "vander Schooren", "VanDer Veen", "VanDer Ven", "VanDer Wal", "VanDer Weide", "VanDer Willigen", "vander Wulp", "vander Zanden", "vander Zwan", "VanDer Zweep", "VanDeren", "VanDerlaan", "VanDerveer", "VanderWoude", "VanDeursen", "VanDeusen", "vanDijk", "VanDoren", "VanDorn", "VanDort", "VanDruff", "VanDryer", "VanDusen", "VanDuzee", "VanDuzen", "VanDuzer", "VanDyck", "VanDyke", "VanEman", "VanEmmen", "vanEmmerik", "VanEngen", "vanErp", "vanEssen", "VanFleet", "VanGalder", "VanGelder", "vanGerrevink", "VanGog", "vanGogh", "VanGorder", "VanGordon", "VanGroningen", "VanGuilder", "VanGundy", "VanHaaften", "VanHaute", "VanHees", "vanHeugten", "VanHise", "VanHoeck", "VanHoek", "VanHook", "vanHoorn", "VanHoornbeeck", "VanHoose", "VanHooser", "VanHorn", "VanHorne", "VanHouten", "VanHoye", "VanHuijstee", "VanHuss", "VanImmon", "VanKersschaever", "VanKeuren", "VanKleeck", "VanKoughnet", "VanKouwenhoven", "VanKuykendaal", "vanLeeuwen", "vanLent", "vanLet", "VanLeuven", "vanLingen", "VanLoozen", "VanLopik", "VanLuven", "vanMaasdijk", "VanMele", "VanMeter", "vanMoorsel", "VanMoorst", "VanMossevelde", "VanNaarden", "VanNamen", "VanNemon", "VanNess", "VanNest", "VanNimmen", "vanNobelen", "VanNorman", "VanNormon", "VanNostrunt", "VanNote", "VanOker", "vanOosten", "VanOrden", "VanOrder", "VanOrma", "VanOrman", "VanOrnum", "VanOstrander", "VanOvermeire", "VanPelt", "VanPool", "VanPoole", "VanPoorvliet", "VanPutten", "vanRee", "VanRhijn", "vanRijswijk", "VanRotmer", "VanSchaick", "vanSchelt", "VanSchoik", "VanSchoonhoven", "VanSciver", "VanScoy", "VanScoyoc", "vanSeters", "VanSickle", "VanSky", "VanSnellenberg", "vanStaveren", "VanStraten", "VanSuijdam", "VanTassel", "VanTassell", "VanTessel", "VanTexel", "VanTuyl", "VanValckenburgh", "vanValen", "VanValkenburg", "VanVelsor", "VanVelzor", "VanVlack", "VanVleck", "VanVleckeren", "VanWaard", "VanWart", "VanWassenhove", "VanWinkle", "VanWoggelum", "vanWordragen", "VanWormer", "VanZuidam", "VanZuijdam", "VonAdenbach", "vonAllmen", "vonBardeleben", "vonBerckefeldt", "VonBergen", "vonBreyman", "VonCannon", "vonFreymann", "vonHeimburg", "VonHuben", "vonKramer", "vonKruchenburg", "vonPostel", "VonRohr", "VonRohrbach", "VonSass", "VonSasse", "vonSchlotte", "VonSchneider", "VonSeldern", "VonSpringer", "VonVeyelmann", "VonZweidorff"]
  16  
  17  import re
  18  
  19  class Name(str):
  20    """A Class (based on the string type) that properly capitalizes a name."""
  21  
  22    def __new__(cls, value=''):
  23      original = value
  24      proper = Capitalize(value)
  25      obj = str.__new__(cls, proper)
  26      obj.original = original
  27      return obj
  28  
  29  def Capitalize(name):
  30    """Does the work of capitalizing a name (can be a full name)."""
  31    hyphen_indexes = []
  32    while name.find('-') > -1:
  33      index = name.find('-')
  34      hyphen_indexes.append(index)
  35      name = name[:index] + ' ' + name[index+1:]
  36    name = name.split()
  37    name = [w.capitalize() for w in name] # standard capitalization
  38    # "Mcx" should be "McX"
  39    index = 0
  40    for w in name:
  41      try: name[index] = mc.sub( "Mc"+w[2].upper(), w )
  42      except: pass
  43      index += 1
  44    # "Macx" should be "MacX"
  45    index = 0
  46    for w in name:
  47      try: name[index] = mac.sub( "Mac"+w[3].upper(), w )
  48      except: pass
  49      index += 1
  50    name = ' '.join( name )
  51    for index in hyphen_indexes:
  52      name = name[:index] + '-' + name[index+1:]
  53    # funky stuff (no capitalization)
  54    name = name.replace( " Dit ", " dit " )
  55    name = name.replace( " Van ", " van " )
  56    name = name.replace( " De ", " de " )
  57    # special surnames and suffixes
  58    name += ' '
  59    for surname in surnames + suffixes:
  60      pos = name.lower().find( surname.lower() )
  61      if pos > -1:
  62        # surname/suffix must be:
  63        # 1. at start of name or after a space
  64        #          -and-
  65        # 2. followed by the end of string or a space
  66        if (((pos == 0) or (pos > 0 and name[pos-1] == ' '))
  67          and ((len(name) == pos+len(surname))
  68          or (name[pos+len(surname)] == ' '))):
  69          name = name[:pos] + surname + name[pos+len(surname):]
  70    return name.strip()
  71      
  72  mc = re.compile( r"^Mc(\w)(?=\w)", re.I )
  73  mac = re.compile( r"^Mac(\w)(?=\w)", re.I )
  74  
  75  # when run from a terminal, this script runs a few quick tests
  76  if __name__ == "__main__":
  77    names = [
  78      "john smith", # normal capitalization
  79      "BOB MCELROY", # mc
  80      "josh macelvany", # mac
  81      "BILL VANWINKLE", # name from surnames list
  82      "joe van buren", # " van "
  83      "bob jones, iii", # suffix
  84      "mary johnson-smith", # hyphenated name
  85      "DAVID SULLIVAN", # IV in the middle
  86      "jason bumcorn", # MC in the middle
  87    ]
  88    for name in names:
  89      print '"%s" ==> "%s"' % ( name, Name(name) )
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS