As I'm learning the PythonLanguage here are useful bits of code that I stumbled across that I might want to use later. Much of it is from the PythonTutor MailList.

See also: PythonLanguage, PythonTools, libxml2 examples

Accessing Environment Variables

# python
>>> import os
>>> os.environ['PATH']
'/bin:/sbin:/usr/bin:/usr/sbin'
>>> os.environ['HOSTNAME']
'ronin'

Extracting HTML with Regular Expressions

   1 >>> htmlSource = 'aaa <span> bbb </span> ccc'
   2 >>> import re
   3 >>> re.findall('<span>.*</span>', htmlSource)  # <== [A]
   4 ['<span> bbb </span>']
   5 >>> re.findall('<span>(.*)</span>', htmlSource)  # <== [B]
   6 [' bbb ']

Extracting HTML with HTMLParse

Note, this is untested.

   1 from HTMLParser import HTMLParser
   2 import sys
   3 
   4 class SpanExtractor(HTMLParser):
   5     show = False
   6     def handle_starttag(self, tag, attr):
   7         if tag == 'span':
   8             self.show = True
   9         if self.show:
  10             sys.stdout.write(self.get_starttag_text())
  11     def handle_endtag(self, tag):
  12         if self.show:
  13             sys.stdout.write(self.get_starttag_text())
  14         if tag == 'span':
  15             self.show = False
  16     def handle_data(self, data):
  17         if self.show:
  18             sys.stdout.write(data)
  19 
  20 >>> import SpanExtractor
  21 >>> html='''<html><body>
  22 bla bla bla
  23 <span>in the span
  24 in the span
  25 <b>in the span</b>
  26 in the span</SPAN>
  27 bla bla
  28 </body></html>'''
  29 
  30 >>> p = SpanExtractor.SpanExtractor()
  31 >>> p.feed(html)
  32 <span>in the span
  33 in the span
  34 <b>in the span<b>
  35 in the span<b>
  36 >>> p.close()

Using PIL (Python Imaging Library)

Here's some code for using the PythonImagingLibrary instead of convert. Note that most of this is lifted from their documentation here (but i've tested it to make sure it works):

http://www.pythonware.com/library/pil/handbook/introduction.htm

Resizing an Image

ronin(adam)$ python
Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
[GCC 3.3.3 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Image
>>> size = 128, 128
>>> file="/tmp/118.jpg"
>>> im = Image.open(file)
>>> im.thumbnail(size)
>>> im.save("/tmp/thumb.jpg", "JPEG")
>>> ^D

ronin(adam)$ imgsize 118.jpg thumb.jpg
118.jpg: WIDTH=640 HEIGHT=424
thumb.jpg: WIDTH=128 HEIGHT=84

Rotate an Image

>>> import Image
>>> im = Image.open("/tmp/thumb.jpg")
>>> out = im.rotate(90)
>>> out.save("/tmp/thumb2.jpg", "JPEG")

ronin(adam)$ imgsize thumb*
thumb.jpg: WIDTH=128 HEIGHT=84
thumb2.jpg: WIDTH=84 HEIGHT=128


CategoryProgramming

PythonCode (last edited 2005-03-16 19:06:20 by AdamShand)