Thursday, July 23, 2009

Python WSGI simple example

# WSGI is the "Web Server Gateway Interface"
# It is a protocol for web servers.
# This example provides the easy_app function as the wsgi component
# When you run this example it will create a simple web server and you'll
# be able to browse to your wsgi web site at http://localhost:8000/
# To expand and improve this example take a gander at the wsgi site
# Python version >=2.5 should be able to run this example without
# additional libraries. Everything is included with python!


def easy_app(environ, start_response):
"""Easiest wsgi implementation ever!"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Python and WSGI Rules!\n']


from wsgiref.simple_server import make_server

httpd = make_server('', 8000, easy_app)

# reminder of where the website is being served
print("Browse to: http://localhost:8000/")

# run server for ever (you'll need to kill it to stop it)
httpd.serve_forever()

Thursday, July 16, 2009

Python - ping one or many addresses at once

# ping a range or a single ip address 
# This implementation creates a thread for each ip address 
# you wish to ping. 
# 
# this version utilizes the os' ping and 
# drives the ping through os.popen 
# 
# if you are looking for a pure python version you should try this 
# 
# if you are looking for a better way to drive 
# subprocesses then look here 

import os, time, sys
from threading import Thread
 
def usage():
    print """ 
    usage: ping_o_matic.py ip_or_ip_range 
 
    This script pings an ip address or a range of ip addresses and 
    returns the result of the ping. If a '*' character is not found 
    in the ipaddress then the script assumes that you are pinging a 
    single ip by ip or dns. 
    If a range of ip addresses is passed then only a class c network 
    can be pinged, nothing larger. 
    example: 
    ping_o_matic.py 192.168.1.1 # pings the ip address 192.168.1.1 
    ping_o_matic.py 192.168.1.* # pings entire class c subnet of 192.168.1.1-255 
    """ 
 
class pingy(Thread): # class inherits from thread 
    def __init__(self, ip):
        Thread.__init__(self) # calls super init 
        self.information = ("yet to run", "no response","Active")
        self.ip = ip
        self.status = 0 # corresponds to the information tuple -- 0 = "yet to run" 
    def run(self):
        pingexe = os.popen("ping -n 2 "+self.ip, "r")
        self.status = 1 #running but no response yet 
        while True:
            line = pingexe.readline()
            if not line: # if done pinging 
                break 
            if line.find(self.ip) and line.find("Reply") > -1: # they exist: 
                self.status = 2 # 2=Active 
    def getStatus(self):
        return self.information[self.status]
 
if __name__ == '__main__':
    # only accept one parameter -- the rest are ignored 
    try:
        ipaddr = sys.argv[1]
    except:
        usage()
        sys.exit()
 
    
 
    pinglist = []
    ip = ipaddr
    if ipaddr.find('*') == -1:
        current = pingy(ip)
        pinglist.append(current)
        current.start()
    else: # then its a range of IPs 
        lastDot = ipaddr.find('*')
        for host in range(0,255):
            ip = ipaddr[0:lastDot]+str(host)
            current = pingy(ip)
            pinglist.append(current)
            current.start()
    for pig in pinglist: # loop through all threads and collect and display status 
        pig.join()
        print pig.ip, ", ", pig.getStatus()
 
#output (for me): 
#python pingmanyatonce.py 10.0.0.1 
#10.0.0.1 ,  Active 
# 
# 
#python pingmanyatonce.py 10.0.0.* 
#10.0.0.0 ,  no response 
#10.0.0.1 ,  Active 
#10.0.0.2 ,  Active 
#10.0.0.3 ,  no response 
#10.0.0.4 ,  no response 
#10.0.0.5 ,  no response 
#10.0.0.6 ,  no response 
#10.0.0.7 ,  no response 
#... # and it keeps going for the entire subnet... 
 
 

# try out the full source

Wednesday, July 15, 2009

Python - compare two images

 
# PIL is a great python library for doing everything related to images 
 
# check out the other PIL and Image examples: 
#   Find and Label objects in Images l 
#   Find and outline the sun  
#   Replace or remove colors from an image  
#   Find the average RGB color for and image   
#   Determine an image's type (regardless of extension)  
 
 
# here is the zipped full source for this example  
from PIL import Image
import time
import sys
 
def compareTwoPics(picture_1, picture_2, step=20):
    step = int(step)
    if step < 1:
        step = 1
 
    percent_similar = 0.0
    percent_red = 0.0
    percent_green = 0.0
    percent_blue = 0.0
    percent_totalcolor = 0.0
 
 
    total_check_points = 0.0
    total_not_match = 0.0
    percent_similar = 0.0
 
    pic1_total_red = 0
    pic1_total_green = 0
    pic1_total_blue = 0
    pic1_total_color = 0
 
    pic2_total_red = 0
    pic2_total_green = 0
    pic2_total_blue = 0
    pic2_total_color = 0
 
    #print picture_1 
    #print picture_2 
 
    try:
        pic1 = Image.open(picture_1)
        pic2 = Image.open(picture_2)
    except:
        # tried to open an unsupported format!! 
        #print str(picture_1) + " is not a supported image format" 
        #print str(picture_2) + " is not a supported image format" 
        return -1.0, 0.0, 0.0, 0.0
 
    pic1_width = pic1.size[0]
    pic1_height = pic1.size[1]
 
    pic2_width = pic2.size[0]
    pic2_height = pic2.size[1]
 
 
    if pic1_width != pic2_width:
        print "\n widths must be the same \n" 
        sys.exit()
    if pic1_height != pic2_height:
        print "\n widths must be the same \n" 
        sys.exit()
 
 
    for x in range(0, pic1_width):
        for y in range(0, pic1_height):
 
            if x % step == 0:
                pic1_color = pic1.getpixel((x,y))
                pic2_color = pic2.getpixel((x,y))
 
                total_check_points += 3
 
                if pic1_color[0] != pic2_color[0]:
                    total_not_match += 1
                if pic1_color[1] != pic2_color[1]:
                    total_not_match += 1
                if pic1_color[2] != pic2_color[2]:
                    total_not_match += 1
 
                pic1_total_red += pic1_color[0]
                pic1_total_green += pic1_color[1]
                pic1_total_blue += pic1_color[2]
 
 
                pic2_total_red += pic2_color[0]
                pic2_total_green += pic2_color[1]
                pic2_total_blue += pic2_color[2]
 
                #print "     pic1 count: "+ str(pic1_total_red) 
                #print "     pic2 count: "+ str(pic2_total_red) 
 
 
 
    pic1_total_color = pic1_total_red + pic1_total_green + pic1_total_blue
    pic2_total_color = pic2_total_red + pic2_total_green + pic2_total_blue
 
 
    percent_similar = 1 - (total_not_match / total_check_points)
    percent_red = abs(float(pic2_total_red) / float(pic1_total_red))
    percent_green = abs(float(pic2_total_green) / float(pic1_total_green))
    percent_blue = abs(float(pic2_total_blue) / float(pic1_total_blue))
    percent_totalcolor = abs(float(pic2_total_color) / float(pic1_total_color))
 
    print '----' 
    print "total % comparible red:  " + str(percent_red)
    print "total % comparible green:" + str(percent_green)
    print "total % comparible blue: " + str(percent_blue)
    print "total % comparible:      " + str(percent_totalcolor)
    print "total pic1:              " + str(pic1_total_color)
    print "total pic2               " + str(pic2_total_color)
 
 
    return percent_similar, percent_totalcolor, pic1_total_color, pic2_total_color
 
 
 
if __name__ == '__main__':
    try:
        import psyco
        psyco.full()
    except ImportError:
        print "...installing psyco would provide additional performance" 
 
 
    thedetail = 20
    if len( sys.argv ) < 3:
        print "\n\n" 
        print "Usage: " + str(sys.argv[0]) + " <photo1.png> <photo2.png> [detail]" 
        print "" 
        print " - photo1.png and photo2.png are the photos you are comparing" 
        print " - detail is just a number.  The higher the number the faster" 
        print " and less detailed the comparison will be.  Default detail is 20" 
        print "" 
        print "example:" 
        print " # Highest quality comparison, slowest turn around" 
        print " " + str(sys.argv[0]) + " photo.png photo2.png 1" 
        print " " 
        print " # Low quality comparison, high turn around" 
        print " " + str(sys.argv[0]) + " photo.png photo2.png 100" 
        sys.exit()
    else:
        try:
            thedetail = sys.argv[3]
        except:
            thedetail = 20
 
        tt = time.time()
        print str(compareTwoPics(sys.argv[1], sys.argv[2], step=thedetail))
        print "execution seconds: " + str(time.time() - tt)
 
 

Friday, July 10, 2009

Python - an attempt at pyglet




Pyglet is a cross platform game developement api. Sort of like pygame. The screenshot shows the 'game' in action. I borrowed some code from the pyglet site. This is really just a first attempt at learning pyglet. Make sure to install pyglet before you try and run the example! Below is the main portion of the code, or the link to the full source:


# nice and simple first attempt at pyglet

from pyglet import window
from pyglet import clock
from pyglet import font
import pyglet
import random
import helper # (borrowed from example pygletspace program)
# it just loads images


class TheBounceWindow(window.Window):
def __init__(self, *args, **kwargs):
window.Window.__init__(self, *args, **kwargs)
self.set_mouse_visible(False)
self.init_sprites()
def init_sprites(self):
self.balls = []
self.ball_image = "ball.png" #helper.load_image("ball.png")
self.inactive_ball_image = "aball.png"
self.me_image = "me.png" # this is the player
self.me_ouch = "me.png" # player is hit image
self.me = Player( self.me_image, self.me_ouch, self.height, self.width)
def main_loop(self):
#fps indicator
ft = font.load('Arial', 28)
# text object to display the ft
fps_text = font.Text(ft, y=10)
# some stuff
clock.set_fps_limit(25)
while not self.has_exit:
self.dispatch_events()
self.clear()
self.update()
self.draw()
clock.tick()
fps_text.text = ("fps: %d") % (clock.get_fps())
fps_text.text += (" objects tracked: %s") %(str(len(self.balls)))
fps_text.draw()
self.flip()
#detect collisions
hits = self.me.collide_once(self.balls)
if hits != None:
#hits is the actual sprite that made contact
# should do something with it!
# do here
self.me.hits_i_can_take -= 1
self.me.playOuch()
#print "contact!"
def update(self):
for sprite in self.balls:
sprite.update()
self.me.update()
def draw(self):
for sprite in self.balls:
sprite.draw()
self.me.draw()

"""******************************************
Event Handlers
*********************************************"""
def on_mouse_motion(self, x, y, dx, dy):
self.me.setPoints(x,y)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
self.me.setPoints(x,y)
def on_mouse_press(self, x, y, button, modifiers):
#print "click: %s, %s" %(str(x), str(y))
#print "button pressed: %s" %(str(button))
self.me.setPoints(x,y)

if (button == 1):
b = Ball(self.ball_image, self.inactive_ball_image, self.height, self.width)
b.setPoints(x,y)
self.balls.append(b)

if (button == 2):
for count in xrange(0,5):
b = Ball(self.ball_image, self.inactive_ball_image, self.height, self.width)
b.setPoints(x,y)
self.balls.append(b)


if (button == 4):
for count in xrange(0,10):
b = Ball(self.ball_image, self.inactive_ball_image, self.height, self.width)
b.setPoints(x,y)
self.balls.append(b)




class Sprite(object):

def __get_left(self):
return self.x
left = property(__get_left)

def __get_right(self):
return self.x + self.image.width
right = property(__get_right)

def __get_top(self):
return self.y + self.image.height
top = property(__get_top)

def __get_bottom(self):
return self.y
bottom = property(__get_bottom)

def __init__(self, image_file, inactive_image_file=None, image_data=None, **kwargs):

#init standard variables
self.image_file = image_file
if (image_data is None):
self.image = helper.load_image(image_file)
else:
self.image = image_data

# inactive image
if (inactive_image_file is None):
# then we don't want one
# just use the regular image
self.inactive_image = self.image
else:
self.inactive_image = helper.load_image(inactive_image_file)
self.x = 10
self.y = 10
self.contact = False
self.active = False
self.dead = False
#Update the dict if they sent in any keywords
self.__dict__.update(kwargs)

def draw(self):
if self.active:
self.image.blit(self.x, self.y)
else:
self.inactive_image.blit(self.x, self.y)

def update(self):
pass

def intersect(self, sprite):
"""Do the two sprites intersect?
@param sprite - Sprite - The Sprite to test
"""
return not ((self.left > sprite.right)
or (self.right <>
or (self.top <>
or (self.bottom > sprite.top))

def collide(self, sprite_list):
"""Determing ther are collisions with this
sprite and the list of sprites
@param sprite_list - A list of sprites
@returns list - List of collisions"""

lst_return = []
for sprite in sprite_list:
if (self.intersect(sprite)):
lst_return.append(sprite)
return lst_return

def collide_once(self, sprite_list):
"""Determine if there is at least one
collision between this sprite and the list
@param sprite_list - A list of sprites
@returns - None - No Collision, or the first
sprite to collide
"""
for sprite in sprite_list:
if (self.intersect(sprite) and sprite.active == True):
sprite.active = False
self.active = False
return sprite
return None


class Ball(Sprite):
def __init__(self, image_data, inactive_image_data, top, right, **kwargs):
self.initial_x_direction = (int(random.random() *10) + 1) %2
self.initial_y_direction = (int(random.random() *10) + 1) %2
if self.initial_x_direction == 1:
self.initial_x_direction = -1
else:
self.initial_x_direction = 1
if self.initial_y_direction == 1:
self.initial_y_direction = -1
else:
self.initial_y_direction = 1
self.y_velocity = (int(random.random() * 10) + 1) * self.initial_x_direction
self.x_velocity = (int(random.random() * 10) + 1) * self.initial_y_direction
# preload sound:
self.sound = pyglet.resource.media('shot.wav', streaming=False)
self.hit_sides = False

#self.velocity = 1
self.screen_top = top
self.screen_right = right
Sprite.__init__(self, image_data,inactive_image_file=inactive_image_data, **kwargs)
def update(self):
#print "%s %s" %(self.top, self.bottom)
if self.top > self.screen_top or self.bottom <>
self.hit_sides = True
self.active = True
self.y_velocity *= -1
if self.right > self.screen_right or self.left <>
self.hit_sides = True
self.active= True
self.x_velocity *= -1
self.y += self.y_velocity
self.x += self.x_velocity
if self.hit_sides:
self.sound.play()
self.hit_sides = False
def setPoints(self, x, y):
self.x = x
self.y = y
class Player(Sprite):
def __init__(self, image_data, image_contact, top, right, **kwargs):

self.screen_top = top
self.screen_right = right
Sprite.__init__(self, image_data, **kwargs)
self.hits_i_can_take = 10
self.sound = pyglet.resource.media('ouch.wav', streaming=False)
self.font = font.load('Arial',28)
self.kill_text = font.Text(self.font, x=20, y=40)
def draw(self):
Sprite.draw(self)
self.kill_text.text = ("Lives : %d") %(self.hits_i_can_take)
self.kill_text.draw()
def playOuch(self):
self.sound.play()
def setPoints(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
bball = TheBounceWindow()
bball.main_loop()

Python remove vowels from a sentence

# create a tuple with vowels....yes I include y as a vowel
vowels = 'a', 'e', 'i', 'o', 'u', 'y'

# movie quote for our sentence
sentence = "My name is Werner Brandes, my voice is my password, verify me."


# iterate through the tuple of vowels
for vowel in vowels:
    # replace the vowel with nothing

    sentence = sentence.replace(vowel, '')

# display the vowel-less sentence!
print sentence

'M nm s Wrnr Brnds, m vc s m psswrd, vrf m.'


# additional string functions: http://docs.python.org/library/stdtypes.html

# manipulate vowels to create pig latin or double dutch


Wednesday, July 8, 2009

python dict

# a dictionary is created with curly braces {}
>>> d = {}
>>> type(d)


# add key,value pairs to the dict
>>> d['adam'] = 123422
>>> d['barry'] = 234223
>>> d['charlie'] = 999322
>>> d
{'barry': 234223, 'adam': 123422, 'charlie': 999322}


# test whether keys are in a dict
>>> 'steve' in d
False
>>> 'barry' in d
True


# iterate through a dict's keys
>>> for k in d.iterkeys():
... print k
...
barry
adam
charlie


# get a key's value from the dict
>>> d.get(k)
999322


# iterate through keys and print out key, value
>>> for k in d.iterkeys():
... print k, " = ", d.get(k)
...
barry = 234223
adam = 123422
charlie = 999322

Tuesday, July 7, 2009

python tuple

# A python tuple is enclosed in paranetheses ()
# tuples are immutable, which means once created they can't be
# added to or removed from like lists
>>> a = (1, 2, "three", 4)
>>> a
(1, 2, 'three', 4)

# the number of elements in a tuple
>>> len(a)
4

# take a slice of a tuple
>>> a[1:3]
(2, 'three')

The Python list and methods of the python list

# basic list usage and list methods 
 
# a list is created with the "[]" square brackets 
l = []
 
# add a single item into a list 
l.append("apple")
print l
#output: 
# apple 
 
# remove the last item appended 
l.pop()
#output: 
# apple 
 
print len(l)
#output: 
# 0 
 
# create and then iterate through a list 
l.append("apple")
l.append("pear")
l.append("peach")
l.append("apricot")
l.append("banana")
print l
#output: 
# ['apple', 'pear', 'peach', 'apricot', 'banana'] 
 
for fruit in l:
    print fruit
 
#output 
#    apple 
#    pear 
#    peach 
#    apricot 
#    banana 
 
# find the index of items in a list 
l.index("apricot")
#output: 3 
l.index("apple")
#output: 0 
 
# remove specific items from a list 
print l
#output: 
# ['apple', 'pear', 'peach', 'apricot', 'banana'] 
 
l.remove("peach")
print l
#output: 
# ['apple', 'pear', 'apricot', 'banana'] 
 
 
# More on lists:  http://docs.python.org/tutorial/datastructures.html