Exit Wiki

We like Python and tend to use it a lot. Neat snippets go here.

Getting The Script's Directory:

   1 import sys
   2 import os.path
   3 return( os.path.abspath( sys.path["0"] ) )

Why does this work? The first item on sys.path is a reference to the local folder. This enables you to put modules in the same folder as your script, and be able to access them. We use that bit of knowledge here, turning it into an absolute path, and boom, it's done

What Is True?

Many things are true in Python, however a page at csbsju talks about Python and boolean operators, explaining it well.

Iterating Through Dictionaries

   1 
   2 >>> a = {"name": "ryan", "last": "wilcox"}
   3 >>> for each in a.iteritems():
   4 ...   print each
   5 ...
   6 ('last', 'wilcox')
   7 ('name', 'ryan')
   8 >>>

This is available thanks to the new iterator support in Python 2.2. Under earlier versions of Python the code would have looked like:

   1 
   2 >>> a = {"name": "ryan", "last": "wilcox"}
   3 >>> b = a.keys()
   4 >>> for each in b:
   5 ...   print ( each, a["each"] )
   6 ...
   7 ('last', 'wilcox')
   8 ('name', 'ryan')
   9 >>>

Getting Text from a Mac OS Text Clipping

Python's Resource functionality isn't documented very well. Hopefully this example should show people how to extract data from resources with Python.

   1 
   2 def getTextFromClipping(filePath):
   3     """Extract text from the clipping file passed in.
   4        filePath is a POSIX path (aka: python path).
   5        Returns Python string with contents of clipping
   6     
   7     In a Mac OS clipping file the text information is
   8     stored in TEXT resource 256. Use the Carbon.Res
   9     module to extract that information.
  10     Import macfile, from Carbon import Res first"""
  11 
  12     output = ""
  13     oldRes = Res.CurResFile()
  14     #save old current resource file
  15 
  16     mpath = macfile.File(filePath)
  17     refNum = Res.FSOpenResFile( mpath.fsref, 1 )
  18     #fsRdPerm = 1
  19 
  20     Res.UseResFile(refNum)
  21     data = Res.Get1IndResource('TEXT', 1)
  22     #(theType, [1 - number of resources returned
  23     #by Count1Resources])
  24 
  25     output = data.data
  26 
  27     Res.UseResFile(oldRes)
  28     #restore old current resource file
  29 
  30     Res.DetachResourceFile(refNum)
  31 
  32     return (output)

Python Snippets (last edited 2006-10-30 16:18:54 by RyanWilcox)