Archive for the 'python' Category

28th Apr 2008

PocketPyGUI: an intuitive, pythonic wrapper of the native Windows Mobile GUI

In playing around with my Dell Axim X51v, I have discovered PythonCE (the python distribution for windows mobile), and, more recently PocketPyGUI — a reliable, complete and easy to use GUI library. I stress easy to use because this library takes all the Windows out of Windows programming ;), while still providing the slick integration with the rest of the Windows Mobile operating system. I’ve also whipped up a few apps (some more complete than others) while getting to know the library. You can find them here on sourceforge all bundled into one zip file.
Here are a few screenshots of the demo program:

Posted in axim, pocketpc, python, windows mobile | No Comments »

16th Feb 2008

Install Python module without root privileges

By default, python tries to install modules to the /usr/lib/pythonXX directory, which is write protected for any user other that root. Here’s how to get around that limitation:

In my case, I will be installing sqlite onto a web server, and so will be doing this all through cgi scripts. It shouldn’t be much different for other situations, though.

The short answer is:

run “python install.py –prefix=/home/username”

whenever you want to use the module, put this at the top of your file:

import sys
sys.path.append('/home/jabapyth/lib64/pythonX.X/site-packages')

For the long answer (how I did it),

Run this file:

#!/usr/bin/python
print "Content-type: text/html\n"

from urllib import urlopen as upen
import tarfile
import os

## the source archive URL
archive = "http://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/pysqlite-2.4.0.tar.gz"

## download the archive
open("pysqlite.tar.gz","w").write(upen(archive).read())

## extract it
tr = tarfile.open("pypy.tar.gz","r:gz")
for m in tr.getmembers():
    tr.extract(m)

## run the installer
import os
os.chdir("pysqlite-2.4.0")
## this is the relevant line for most people: pass --prefix=/home/username to the install file
res = os.popen("python setup.py install --prefix=/home/jabapyth").read()
print res

Run that file, and the module will be installed

again, you will need to put this at the top of any file into which you want to import this module:

import sys
sys.path.append('/home/username/lib64/python2.4/site-packages')

Posted in how-to, python, web | No Comments »

14th Feb 2008

VensterCE: Hello World, again

In this tutorial, we are actually going to make a window, although we will still just be saying “Hello, World”

The Code

from venster.ce import *

class MyWindow(CeMainWindow):
    _window_title = u"Hello World, again"

    @msg_handler(WM_CREATE)
    def OnCreate(self,event):
        self.sizer = BoxSizer(VERTICAL)
        text = StaticCenter(u"Hello World", parent=self)
        self.sizer.append(text)
        CeMainWindow.OnCreate(self,event)

def main():
    mainForm = MyWindow()
    mainForm.ShowWindow()
    application = Application()
    appliation.Run()

if __name__ == "__main__": main()

Step by Step

class MyWindow(CeMainWindow):
    _window_title = u"Hello World, again"

This is the class definition of the main window. It inherits from CeMainWindow, which was imported from venster.ce at the top. “_window_title” is a class variable, and representing the title of your window. Once again, be sure to use unicode (prepend the string literal with a “u” or convert with the unicode(str) function), or it will come out looking like garbage.

    @msg_handler(WM_CREATE)
    def OnCreate(self,event):
        self.sizer = BoxSizer(VERTICAL)
        text = StaticCenter(u"Hello World", parent=self)
        self.sizer.append(text)
        CeMainWindow.OnCreate(self,event)

the @msg_handler(WM_CREATE) is a decorator function, setting this function up as the message handler for the WM_CREATE function; the effect being that this function is called as soon as the window is created.
self.sizer (the name is important) is our main widget sizer — all widgets we create should be appended to it, or one of its children.
There are 4 classes of static text: Static, StaticLeft, StaticCenter, and StaticRight. They all take the same arguments.
Finally we call the parent class’ OnCreate to finish setting up the window.

def main():
    mainForm = MyWindow()
    mainForm.ShowWindow()
    application = Application()
    appliation.Run()

if __name__ == "__main__": main()

These lines of code will probably be at the end of all your programs; they “create” the window and start th eapplication running.

Posted in axim, how-to, pocketpc, python, windows mobile | No Comments »

24th Jan 2008

VensterCE: installation

To use the vensterce library you first need python, so (If you haven’t already) go ahead to the PythonCE Download Page and get either the installer or the CAB file (you choose :). Then you can fetch VensterCE zip archive from here. Inside that zip file you will find several things:

  • “venster”: this folder is the actual library. Copy it into your python library (Usually \Program Files\Python25\Lib\
  • “tutorial”: here is contained 5 “tutorial” files along with an html page describing them, although I’ve found this “tutorial” to be more of a quick-start for those already proficient with C++ win32 programming
  • the contents of the “shared” folder need to be copied into the \Windows directory on your device.
  • “pyceide”: this is an advanced python IDE, built in VensterCE. All you need to do is double-click on the “pyceide.pyw” file and it will run.

That should be all that’s necessary. From now on you can “import venster”.

Posted in how-to, pocketpc, python, windows mobile | No Comments »

22nd Jan 2008

VensterCE: Native Win32 Api for PythonCE

VensterCE is an open source wrapper of the native win32 controls on a windows mobile device (i believe its also available for regular windows…but its not as good as the win32api module). Its a cool project, but the tutorials provided give a good idea of what it can do, but don’t actually help you understand how to make your own. This can be a big challenge for those win32 noobs out there (hey, i was one too…about a month ago ;), so i decided to start a tutorial series to help out, and teach myself something in the process.

Posted in axim, pocketpc, python, windows mobile | No Comments »

10th Nov 2007

MandelBrot

I’ve been playing around with Mandelbrot fractals over the past couple of days, and ive come up with a pretty reasonable Generator (first written in python, and then in c for speed).
Source:

Setup:

  • Python: make sure you have python and pygame installed, then run “python mandelbrot.py”
  • C: (on linux) type “gcc mandelbrot.c -lm -lSDL -o mandelbrot”
    when that finishes, just run “mandelbrot”

Usage:

  • Click somewhere to zoom in.
  • right-click to increase the detail.
  • Ctrl-click to zoom out.
  • Ctrl-right-click to decrease the detail.

Compiled for Ubuntu Feisty Fawn
I took a bunch of screenshots of my program at various zooms (Flickr page)
Here are my favorite:






Posted in c, python | No Comments »

03rd Oct 2007

Pygame tutorial - the basics

The game

import pygame
from pygame.locals import *

screen = pygame.display.set_mode((100,100))
screen.fill((255,0,0))
pygame.display.flip()
raw_input()

Step by Step

import pygame
from pygame.locals import *

These are just the general pygame imports — found at the top of nearly every game

screen = pygame.display.set_mode((100,100))

This creates a pygame window (with width 100 and height 100) and returns a surface that points to the back buffer

screen.fill((255,0,0))

Fill the screen with red (rgb #ff0000)

pygame.display.flip()

Switch the buffers, showing your red window

raw_input()

This is merely to keep your python process from ending, thereby closing your window. Later, we will use while loops to keep your game going.

Important Note
pygame is automatically double buffered. This means that if you don’t call pygame.display.flip, the changes you have made to your screen’s surface will not be displayed.
Try omitting that line and see what happens.

Posted in pygame, python | No Comments »

11th Sep 2007

HTTP Auth

heres a script for easy http authentication. It can be particularly helpful for automating data backups and the like. Source Code


Posted in python, web | No Comments »

09th Sep 2007

Site Backup

I just finished a cPanel backup program BackMeUp. It is built in python, using PythonCard. I will be releasing the source code shortly.

Posted in python | No Comments »

09th Sep 2007

OpenGL

i finally took the jump into OpenGL, and its not as bad as i thought (althought it is far too C, if you know what i mean). The pyOlenGL module provides a full wrapper, although i would like a more pythonic layer on top of ogl, just to soften the blow. Anyway, here’s my first OpenGL program (its hoping to grow into a pong-type game)

from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *

def resize((width, height)):
    if height==0:
        height=1
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    #gluPerspective(45, 1.0*width/height, 0.1, 100.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def init():
    global quad

    glShadeModel(GL_SMOOTH)
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LEQUAL)
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
    quad=gluNewQuadric()

def draw(x,y):
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    y=600-y

    #square((x,y,0),(x+100,y,0),(x+100,y+100,0),(x,y+100,0),(255,100,0))
    #sqaure(x,y,100,100)
    cube(100,100,0,100,100,-100)

def square(v1,v2,v3,v4,color=(255,255,255)):
    def cx(x):return (1.0/300)*x-1.0
    glBegin(GL_QUADS)
    glColor3f(*[c*(1.0/255) for c in color])

    for point in [v1,v2,v3,v4]:
        glVertex3f(*[cx(o) for o in point])
    glEnd()

def sqaure(x,y,w,h,color=(255,255,255)):
    def cx(x):return (1.0/300)*x-1.0
    glBegin(GL_QUADS)
    glColor3f(*[c*(1.0/255) for c in color])

    glVertex2f(cx(x),cx(y))
    glVertex2f(cx(x)-cx(w),cx(y))
    glVertex2f(cx(x)-cx(w),cx(y)-cx(h))
    glVertex2f(cx(x),cx(y)-cx(h))

    glEnd()
xat=0
def cube(x,y,z,w,h,d,color=(255,255,255)):
    global xat
    xat+=0.1
    def cx(ax):return (1.0/300)*ax-1.0
    glRotatef(xat,1.0,1.0,0.0)
    glBegin(GL_QUADS)
    glColor3f(*[c*(1.0/255) for c in color])

    glVertex3f(cx(x),cx(y),cx(z))
    glVertex3f(cx(x)-cx(w),cx(y),cx(z))
    glVertex3f(cx(x)-cx(w),cx(y)-cx(h),cx(z))
    glVertex3f(cx(x),cx(y)-cx(h),cx(z))
    glEnd()
    glColor3f(*[c*(1.0/255)-0.5 for c in color])
    glBegin(GL_QUADS)
    glVertex3f(cx(x),cx(y),cx(z)+cx(d))
    glVertex3f(cx(x)-cx(w),cx(y),cx(z)+cx(d))
    glVertex3f(cx(x)-cx(w),cx(y)-cx(h),cx(z)+cx(d))
    glVertex3f(cx(x),cx(y)-cx(h),cx(z)+cx(d))

    glColor3f(*[c*(1.0/255)-0.1 for c in color])

   # glVertex3f(cx(x),cx(y),cx(z)+cx(d))
   # glVertex3f(cx(x)-cx(w),cx(y),cx(z)+cx(d))
   # glVertex3f(cx(x)-cx(w),cx(y),cx(z))
   # glVertex3f(cx(x),cx(y),cx(z))

    glEnd()

def main():
    x=y=0
    video_flags = OPENGL|DOUBLEBUF

    pygame.init()
    pygame.display.set_mode((600,600), video_flags)

    resize((600,600))
    init()

    frames = 0
    ticks = pygame.time.get_ticks()
    while 1:
        if pygame.event.get(QUIT):
            break
        for ev in pygame.event.get():
            if ev.type==MOUSEMOTION:
                x,y=ev.pos
            if ev.type==MOUSEBUTTONDOWN:
                mp=1
            if ev.type==MOUSEBUTTONUP:
                mp=0

        pygame.event.pump()
        draw(x,y)
        pygame.display.flip()
        frames = frames+1

    print “fps:  %d” % ((frames*1000)/(pygame.time.get_ticks()-ticks))
    pygame.display.quit()

if __name__ == ‘__main__’: main()

Posted in python | No Comments »