Sunday, September 30, 2012

Installing Python libraries in Mac OS X

Thanks to the post in http://ashearer.com/blog/2011/xcode/ 
was trying to install Python Imaging Library (PIL), failed. 
basically from the post linked:
'enter the following command line once and the effect will last across multiple builds or installations for the remainder of the terminal session.'

export ARCHFLAGS="-arch i386 -arch x86_64"


Saturday, September 29, 2012

python + socket + xml

made a silly error:
xmldom = xml.dom.minidom.parseString(xml)
xml is a string containing the xml doc.
but its name clashes with the xml.dom.minidom package
xmldom = xml.dom.minidom.parseString(xml_string)

xml processing:
elements = xmldom.getElementsByTagName("mytag")
print elements.length                  # return number of elements
element.getAttribute("myattr")


using multiple line for code. use "\"
eg.: print "this, " + "that, " \
                + "those"

Dictionary
mydictionary = {"mykey":"hehe"}
mydictionary["newkey"] = "hello"       # can be number too
for k, v in mydictionary.iteritems():
   print k + "= " + v
if  "key" in mydictionary:
   print "key exists in dictionary"


Socket client:
import socket
socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("127.0.0.1", 5000))   # address and port
data = socket.recv(4096)              # 4096 bytes buffer


binary data
data = bytearray(socket.recv(4096))
size = (data[3]<<24 | data[2]<<16 | data[1]<<8 | data[0] ) # to 32-bit or 4 byte integer


python imaging (PIL)

all thanks to the link: http://yufu.co/wordpress/?p=15

JPEG decoding from binary data using PIL. Documentation is lacking in official PIL site: http://www.pythonware.com/library/pil/handbook/image.htm

import Image
f = open("myimage.jpg", 'rb')
data = f.read()
im = Image.fromstring('RGB', (640,480), data, 'jpeg', 'RGB', '')