Thursday, May 22, 2008

Play with Cheetah : the python based templating engine

Cheetah is a python powered  Templating engine and code generation tool (Though I never tried it’s code generation functionality). Its main application is in the Web Development scenario itself.

To start with Cheetah, we can download the latest release of cheetah from http://sourceforge.net/project/showfiles.php?group_id=28961.
Installation is done by the usual
python setup.py install

After this we are going to test the prime functionality of Cheetah, the Web Development scenario.

The simplest template (Greeting.tmpl)
###################################
Hello, $firstName.

Your order (#$order) has shipped:
###################################                                  

Compile it using Cheetah

cheetah compile Greeting.tmpl
Compiling Greeting.tmpl -> Greeting.py

Now we got a Greeting.py. So let’s  test that in python

>>> from Greeting import *
>>> t = Greeting()
>>> t.firstName= ‘Maxin’
>>> t.order = 23342
>>> print t
Hello, Maxin.

Your order (#23342) has shipped:

Hmm.. It works..
Best reference for cheetah is available at http://www.cheetahtemplate.org/docs/users_guide_html

Posted by maxinbjohn at 07:28:04 | Permalink | Comments (2)

Tuesday, May 20, 2008

System Tray application for Linux using Python and GTK

Creating an application which resides in the System tray adds charms to an otherwise simple application. Pleople tend to value accessibility and userfriendliness  than the quality of the program itself (pardon my friends, I am sure that you are not one of those chaps)

But, again it is fun to create a simple gui which demonstrates how to create an active System tray application using pygtk. My simple app goes like this.

#######################################################################################

#!/usr/bin/env python

import gtk

class StatusIcc:

    # activate callback
    def activate( self, widget, data=None):
    dialog = gtk.MessageDialog(
        parent         = None,
        flags          = gtk.DIALOG_DESTROY_WITH_PARENT,
        type           = gtk.MESSAGE_INFO,
        buttons        = gtk.BUTTONS_YES_NO,
        message_format = “Did you like this Activation example \n by Maxin B. John <maxinbjohn@gmail.com>?”)
    dialog.set_title(’Popup example’)
        dialog.connect(’response’, self.show_hide)
    dialog.show()
   
   # Show_Hide callback
    def  show_hide(self, widget,response_id, data= None):
           if response_id == gtk.RESPONSE_YES:
               widget.hide()
    else:
        widget.hide()
           

    # destroyer callback
    def  destroyer(self, widget,response_id, data= None):
        if response_id == gtk.RESPONSE_OK:
            gtk.main_quit()
    else:
        widget.hide()

    # popup callback
    def popup(self, button, widget, data=None):
        dialog = gtk.MessageDialog(
        parent         = None,
        flags          = gtk.DIALOG_DESTROY_WITH_PARENT,
        type           = gtk.MESSAGE_INFO,
        buttons        = gtk.BUTTONS_OK_CANCEL,
        message_format = “Do you want to close this Status Icon program?”)
    dialog.set_title(’Popup Window’)
        dialog.connect(’response’, self.destroyer)
    dialog.show()
     
       

    def __init__(self):
        # create a new Status Icon
        self.staticon = gtk.StatusIcon()
        self.staticon.set_from_stock(gtk.STOCK_ABOUT)
        self.staticon.set_blinking(True)
    self.staticon.connect(“activate”, self.activate)
        self.staticon.connect(“popup_menu”, self.popup)
        self.staticon.set_visible(True)

        # invoking the main()
        gtk.main()

if __name__ == “__main__”:
    statusicon = StatusIcc()
####################################################################################

Hmm , The code is pretty simple . It is using gtk.StatusIcon() for the System Tray app. The most important signal for the StatusIcon are “activate” and “poup_menu”. The callbacks for those singals are also self explanatory. So not much comments on the code. Now lets see my
app in action.

The Information (i) symbol in the system tray area is the running application. Right click and Left clicks will generate the “poup_menu” and “activate” signals respectively. 
Try the tray app for you next programming adventure :)

Posted by maxinbjohn at 05:48:19 | Permalink | Comments (1) »

Friday, May 16, 2008

Twitter through python

Twitter is a free social networking and micro blogging service that allows users to send “updates”  up to 140 characters long to the Twitter website, via SMS or instant messaging (google chat).
Updates are displayed on the user’s profile page and instantly delivered to other users who have signed up to receive them. The sender can restrict delivery to those in his or her circle of friends (delivery to everyone is the default). Users can receive updates via the Twitter website, instant messaging,SMS, RSS, email or through an application.

Now let’s have a look at python and integrate the Twitter with Python. Python-twitter module is a python wrapper around Twitter API which is available at http://code.google.com/p/python-twitter/. The twitter module depends on simplejson module which is available from http://pypi.python.org/packages/source/s/simplejson/simplejson-1.9.1.tar.gz. As it is a pure python implementation, installation is very easy and traditional.

Then download the python-twitter module from http://python-twitter.googlecode.com/files/python-twitter-0.5.tar.gz .
tar zxvf python-twitter-0.5.tar.gz
cd python-twitter
python setup.py build
python setup.py install
and we are done :)

Now let’s write the simplest python script to post a message in twitter.

###############################################################
# The simplest python program to play with twitter using python-twitter
#  Google Code:   http://code.google.com/p/python-twitter/
#  Google Groups: http://groups.google.com/group/python-twitter
#  Python twitter API can be used to send and receive twitter messages
#
# Thanks to DeWitt Clinton <dewitt@google.com> for this wonderful module
#

import twitter

api = twitter.Api(username=”my_twitter_username”, password=”my_secret_password”, input_encoding=None)
status = api.PostUpdate(“example of the simplest twitter message program “)
print status.text

###########################################################

It is very simple. Now let’s run the code as
python simple_twitter.py
example of the simplest twitter message program

Now when I visit my twitter home (http://twitter.com/maxinbjohn), I can see that message and I think it is cool Cool

Posted by maxinbjohn at 06:34:45 | Permalink | No Comments »

Thursday, May 8, 2008

The simplest (python based) pre-commit hook in Subversion

Hooks in Subversion are scripts or executables that are triggered by an event in the subversion version control life cycle. The following are the hooks supported by Subversion.

In the hooks directory of a repository we can find these template files:
post-commit.tmpl      pre-unlock.tmpl
post-lock.tmpl          pre-commit.tmpl
start-commit.tmpl     post-revprop-change.tmpl
pre-lock.tmpl          post-unlock.tmpl     pre-revprop-change.tmpl

start-commit
Before the commit transaction starts
pre-commit After the commit transaction starts but before the transaction is commited
post-commit After the commit transaction completes
pre-revprop-change Before a revision property is changed Repository Path,
post-revprop-change: After a revision property is changed Repository Path
pre-lock:  Before the lock being acquired
post-lock:  
After the lock being acquired

To test how a hook works, let’s create a repository in our Gnu/Linux Box.

svnadmin create hello

Now we have a repository called hello and it will contain files like
conf dav db format hooks joke.py locks pre-commit README.txt
Modify the conf/svnserve.conf to include passwd file and add users to the passwd file along with their passwords.

Then run the server as svnserve -d -r hello
To checkout :
svn co svn://127.0.0.1

Then lets move to the real work. We need to stop anybody who is trying to commit to our repository just because we are doing some important work on the server or we just dont want anybody to help us :)

To do that, let’s create a file called pre-commit in hooks folder in the repository (hello). The content of the pre-commit should be :

#!/usr/bin/env python
# ====================================================================
# The simplest pre-commit hook which prevents all the commits to the repository
# This can be useful(?) when you are doing the backup of your subversion repo.
# This small script will prevent the commit and will give a simple message
# to the person who is commiting the changes.
#
# USAGE:
# copy this script as pre-commit in the hooks directory of the svn server
#
# ====================================================================

import sys

MESSAGE=”"”
Dear Sir,

As we are doing some important work in the server,all those who are submitting
the changes will have to wait for some time.

Sorry for the inconvenience caused.

Regards,

Administrator.
“”"
# Messages written to the stderr will be shown to the person who is commiting.
sys.stderr.write(MESSAGE)

# Need to exit with anything other than 0 to fail the commit
sys.exit(2)

Let’s change the mode of the pre-commit to executable (chmod +x pre-commit)

To test this setup, lets create a sandbox and then try to commit our changes to the server.
svn co svn://127.0.0.1
cd 127.0.0.1
mkdir test
svn add test
svn commit -m “adding the test directory”

Now we will see the pre-commit hook in action:

Adding test
svn: Commit failed (details follow):
svn: ‘pre-commit’ hook failed with error output:

Dear Sir,

As we are doing some important work in the server,all those who are submitting
the changes will have to wait for some time.

Sorry for the inconvenience caused.

Regards,

Administrator.


This is the most simplest hook that can be implemented in Python. More complex hooks can be implemented in python using the svn module. More useful hooks examples are available from http://subversion.tigris.org/tools_contrib.html#hook_scripts

Posted by maxinbjohn at 05:39:11 | Permalink | Comments (2)

Wednesday, April 30, 2008

Programming fun for children with Neko and Turtle in Windows

Python : A fun filled language for both beginners and experienced programmers. But some of us may not cared the fact that it is good for children also.. to start learning programming. As python is a heavily ported language (It runs in huge servers as well as on handheld gaming devices like gp2x too), it doesn’t matter where you are … you can be in Gnu/Linux (highly preferred and for the smart kids) or in Windows platform (only for the not so cool kids)

In Gnu/Linux, Python almost ‘pre loaded’. So you just need to care about the Tkinter module. In Windows , we need to install Python first to do something for for our kids. Just download Python 2.5.2 installer from http://www.python.org/ftp/python/2.5.2/python-2.5.2.msi and click to install it on your machine. Don’t forget to select the Tkinter during installation. Preferably you should modify the Environment Variable Path to include the Python : (C:Python25) will be the default path.

The default package that is present in the Python installation for Kids is Turtle. It is easy to play with Turtle in Python.
The kids can move the lines and draw things in the computer by typing very simple commands in the python interpreter. It is as easy as

import turtle
turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
This will give the kids an interesting way to see animation of what they are doing in real time and they will get an idea of what programs are suppossed to do.Its output looks like

The best way for the kid to learn programming is by playing with Neko (Cat in Japanese). Just like the Tom and Jerry Show, there is a rat in PyNeko which is an opponent for our Neko. If we program neko, he can jump to places and then eat that cat :) … Must be very funny for the kids….

To start doing something with Neko, we need to download neko.py and nekomaps.py from http://gnuvision.com/pyneko/. ” Adventures with Neko !” is a fun filled programming book by Mr. Pramode CE, a veteran Programmer/Teacher/Philosopher who lives in Thrissur. It is available at http://gnuvision.com/books/pybook/.

Now lets move on with Neko. Create a directory C:Python and download neko.py and nekomaps.py to that directory. Start cmd and cd to C:Python. Now we can start playing with Neko.

Neko can be invoked in Windows by

from neko import *
right() #moves the cat to 1 step right
left() # moves the cat to 1 step left
up() # moves it upwards
down() # moves it downwards..

It is really a funny experience. Read the Adventures with Neko for more fun filled adventures. A sneak peak of Neko :

Try it for your kid, it will be worth the effort, no matter what the OS you choose for it.

Posted by maxinbjohn at 05:26:52 | Permalink | Comments (2)

Wednesday, April 23, 2008

Play with Configuration files using Python

Today, the main purpose of most of the administrator GUI utilities is to modify the respective configuration files. The most reliable way to modify the configuration file  is to  use  editors like vi or emacs and modify it by hand.
Python provides a better and easy way to play with our configuration files… by using the configobj module. So we can create our own administrative utilities using python (either standalone apps or cgi applications)

http://sourceforge.net/projects/configobj

The configobj module is fully utf-8 encoding compatible. So it doesn’t matter whether your configuration is in English or say for example in Hindi.

Many projects like Bazaar, Turbogears etc are using this module for reading and modifying the configuration files.To modify a config file is as easy as…

from configobj import ConfigObj
config = ConfigObj()
config.filename = filename
#
config['keyword1'] = value1
config['keyword2'] = value2
config.write()

done….. :) , it is that easy….

Refer these links for further information…

http://www.voidspace.org.uk/python/configobj.html#introduction
http://www.linuxjournal.com/article/3616

My idea is to create some customised gui (in Tkinter for portability) for my favourite tools like subversion for administration (in the future , of course)

Posted by maxinbjohn at 10:03:01 | Permalink | No Comments »

Friday, April 11, 2008

Create and manipulate SQLite databases using Python

SQLite is a small,embedable relational database management System which is almost ACID compliant. It is 
heavily used in the Free/Open source world and by people like Apple. It is deployed in Firefox, Mac OS X, Skype, IPhone 
and Symbian phones. So when you use your Nokia phone (a symbian based phone), remember that you are a sqlite user. With a size less than 500k, it is one of the small but beautiful softwares which is platform independent.

Now let’s play with sqlite3 in Linux..

To create a sqlite database (here test.db), run the sqlite3 command in terminal.

sqlite3 test.db “create table t1(t1key INTEGER PRIMARY KEY, data TEXT, num double, timeEnter Date);”

now we have the test.db database in the present working directory.

To see the table details in a given database, execute this command.

sqlite3 test.db “.table”
t1

Now let’s populate the database..
sqlite3 test.db “insert into t1(data,num) values(’this is a sample data’,3);”

Ok, now let’s use python’s sqlite bindings to manipulate the database and the data in it..

>>> import sqlite
>>> con = sqlite.connect(’test.db’)
>>> cur = con.cursor()
>>> cur.execute(’insert into t1(data,num) values(“this is again a test”,1)’)
>>> cur.commit()
>>> cur.execute(’SELECT * from t1′)
>>> print cur.fetchall()
[(1, 'this is a sample data', 3.0, None), (2, 'this is again a test', 1.0, None)]

>> cur.execute(’select * from t1 where num=3′)
>>result=cur.fetchall()[0]
>>print result
(1, ‘this is a sample data’, 3.0, None)
>> print result[1]
this is a sample data

Well, if you think it is not enough to use sqlite in your project, refer this SQLite tutorial : http://souptonuts.sourceforge.net/readme_sqlite_tutorial.html

Posted by maxinbjohn at 05:45:50 | Permalink | No Comments »

Wednesday, March 19, 2008

Get Bluetooth RSSI values using Python

The Received Signal Strength Indicator (RSSI ) is a measurement of the power present in a received bluetooth signal. The end-user can observe the RSSI value when measuring the signal strength of received bluetooth signal.

Some interesting Projects like BlueProximity (http://www.gnomefiles.org/app.php/BlueProximity) uses RSSI value at it’s core. 
This software helps you add a little more security to your desktop by detecting your mobile phone(bluetooth enabled) , and keeping track of its distance. If you move away from your computer and the distance is above a certain level (no measurement in meters is possible) for a given time, it automatically locks your desktop.

But even in that project, they doen’t measure RSSI using Python. Instead, that project depends on the hcitool to measure RSSI . The developer of Blueproximity (Lars) posted the same issue in Ubuntu Forum (http://ubuntuforums.org/showthread.php?t=528701). That’s how I decided to spend some time for it Embarassed

My first investigation was what the Perl guys do to measure RSSI. I got the answer from http://perl.jonallen.info/pub/Main/BluetoothProximityDetection/xscreensaver.pl . 
  Yes, They depend on C to measure the RSSI using inline C code in Perl. So I decided to move in the same
direction.

As far as I know, Swig is the best method to integrate C with Python (http://linuxgazette.net/issue49/pramode.html).  So , I decided to move in that direction. I have modified the C code in hcitool by Maxim Krasnyansky <maxk@qualcomm.com> and Integrated it with Python.

enerating the swig wrapper for bluessid.c

swig -python -module bluessid bluessid.c

gcc -I /usr/include/python2.4 -c bluessid.c bluessid_wrap.c

ld -shared -o _bluessid.so bluessid.o bluessid_wrap.o -lbluetooth

This will create the _bluessid.so in the present working directory.
Invoke python

import bluessid
help(bluessid)

The completed source code of Pyrssi is available at  

http://pysportslive.googlecode.com/svn/trunk/pyrssi/

Warning: Due to the non availabity of Bluetooth module, I haven’t tested this code. It is in Beta stage . So please dont complain if it cause an explosion in your PC or fried your bluetooth adapter Innocent 

Posted by maxinbjohn at 05:57:41 | Permalink | No Comments »

Monday, March 3, 2008

You got a call.. with Python OSD and Sony Ericsson K300i

Consider the situation where you have put your mobile in silent mode and working on your PC. Most of the times,
you will not be able to attend the calls simply because you won’t care the buzzing of the mobile phone… 

This Python program will Show an On Screen Display telling ” You have a call” to divert our attention to the mobile phone. Only thing is that you should connect your Mobile with your PC using the USB cable 
provided with your mobile ..  or if you are a bit adventurous, try to connect your phone using bluetooth using the
bluetooth dongle.. ( /dev/rfcomm0 instead of /dev/ttyUSB0)..

For Bluetooth ….

###################
hcitool scan
Scanning …
11:22:33:44:55:66

Then modify the /etc/bluetooth/rfcomm.conf file
#
# RFCOMM configuration file.
#

rfcomm0 {
# Automatically bind the device at startup
bind no;

# Bluetooth address of the device
device 11:22:33:44:55:66;

# RFCOMM channel for the connection
channel 1;

# Description of the connection
comment “Example Bluetooth device”;
}

Then give this command

rfcomm bind /dev/rfcomm0 

after running the below given python program, release the device

rfcomm release /dev/rfcomm0
###################

Then try this python program

######################################################
# mobilecall.py #
# Python program which displays the information when #
# somebody calls your mobile (here my K300i) which is #
# plugged to my pc using the usb cable. #
# ################################################### #
# Technical Details: #
# The usb device is shown as ttyUSB0 in the Linux PC #
# The serial module can be used to read and write from#
# that device. PyOSD is used to diplay the information#
# on the screen. #
# If you want, you can use the pygame module to play #
# music in your PC to inform you about the call .. #
# or dbus module to mute other music players #
# #
# Technically , this is the meanest way(or simplest) #
# to achieve this using python #
######################################################

import serial
import time
import pyosd
#import pygame

def mobilecall():
try:
# /dev/rfcomm0 in the case you are using bluetooth connectivity :)
s= serial.Serial(’/dev/ttyUSB0′,9600)
# This will wait till some string is pushed from phone.
# Highest probable event is ‘RING’ indication from phone
# when somebody calls you.
data = s.readline()

# PyOSD initialization and other settings..
displayer = pyosd.osd()
displayer.set_colour(’red’)
displayer.set_pos(0)
displayer.set_timeout(10)
displayer.display(’You have a call . Please pick up your mobile’)

# Uncomment this if you want to play music on receiving a call
#pygame.mixer.init()
#indi_music = pygame.mixer.Sound(’/usr/share/sounds/KDE_Startup.wav’)
#pygame.mixer.Sound.play(indi_music)

 time.sleep(10)
except:
   print ‘Failed to open Port’

# Pythonic way to invoke the function
if __name__== ‘__main__’:
   mobilecall()

###############################################################

And here goes the output:

Posted by maxinbjohn at 10:57:59 | Permalink | Comments (1) »

Tuesday, February 26, 2008

Python and Cairo - There will be blood…

What will a huge Hollywood fan do after Daniel Day Lewis won Best actor award for “There will be Blood” beating legendary actor like George Cluny..? Well, he will definitely watch “There will be blood”. But as that film hasn’t yet released in India, I decided to do something which is no way related to that movie..  Learn to do something interesting with Cairo in Python…

As I was thrilled about the movie- “there will be blood”, I decided to create a simple GTK animation which shows the spreading of blood in the floor.. obviously insipired from the name of the movie :)

Python code

#########################################################################
#
#PyCairo Demo:- There will be blood ..
#By Maxin B. John
#An animation to show the capabilites of PyCairo
#
# About Cairo
# Cairo is a software library used to provide a vector graphics based,
# device-independent API for software developers. It is designed to provide
# primitives for 2-dimensional drawing across a number of different backends.
#Cairo is designed to use hardware acceleration when available.
# #########################################################################
#!/usr/bin/env python

import sys
import gobject
import pygtk
pygtk.require(’2.0′)
import gtk
from gtk import gdk
import cairo

if gtk.pygtk_version < (2,10,0):
print “PyGtk 2.10.0 or later required”
raise SystemExit

win = None

#The blood is a circle filled with red color whose radius grows with time :)

def expose(widget, event):
global radius
cr= widget.window.cairo_create()
cr.set_source_rgba(1.0, 0, 0, 0.7)
cr.arc(float(radius)/2, float(radius)/2, radius, 0, 2.0*3.14)
cr.fill()
cr.stroke()
return True

# this keeps the blood flowing…

def update_clock():
global win
global radius
radius = radius +1
win.queue_draw()
return True

# the ‘main’ function

def main(args):
global win
global radius
radius =0
win = gtk.Window()
win.set_app_paintable(True)
win.set_title(’PyCairo Demo’)
win.connect(’delete-event’, gtk.main_quit)
win.connect(’expose-event’, expose)
gobject.timeout_add(100, update_clock)

win.show_all()
gtk.main()
return True

# The pythonic way to start the animation
if __name__ == ‘__main__’:
     sys.exit(main(sys.argv))

And the output Cool

Don’t you feel the smell of blood…  ??? Undecided

Posted by maxinbjohn at 11:05:19 | Permalink | No Comments »