Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

manatlan http://manatlan.online.fr

« Newer Snippets
Older Snippets »
Showing 11-20 of 22 total

converting some french chars with python

because translate and maketrans don't love utf-8 ;-(
    import string
    french=u"15 résultats trouvés".encode("utf_16")
    
    sfrom = u"àâäéèêëïîôöûùüç".encode("utf_16")
    sto   = u"aaaeeeeiioouuuc".encode("utf_16")
    print french.translate( string.maketrans(sfrom,sto) )

convert a PIL image to a GTK pixbuf

free adaptation of http://slugathon.python-hosting.com/changeset/205

import gtk
import Image

def image2pixbuf(im):  
    file1 = StringIO.StringIO()  
    im.save(file1, "ppm")  
    contents = file1.getvalue()  
    file1.close()  
    loader = gtk.gdk.PixbufLoader("pnm")  
    loader.write(contents, len(contents))  
    pixbuf = loader.get_pixbuf()  
    loader.close()  
    return pixbuf  

simplest httpserver with python

responding "hello" at http://localhost:8080
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200, 'OK')
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write( "hello" )

    @staticmethod
    def serve_forever(port):
        HTTPServer(('', port), MyServer).serve_forever()

if __name__ == "__main__":
    MyServer.serve_forever(8080)

python and sqllite : simplest example

import sqlite

con = sqlite.connect('mydatabase.db')
cur = con.cursor()
#~ cur.execute('CREATE TABLE foo (o_id INTEGER PRIMARY KEY, fruit VARCHAR(20), veges VARCHAR(30))')
#~ con.commit()
cur.execute('INSERT INTO foo (o_id, fruit, veges) VALUES(NULL, "apple", "broccoli")')
con.commit()
print cur.lastrowid

cur.execute('SELECT * FROM foo')
print cur.fetchall()

python unit tests with doctest

def mulby2(a):
    """
    >>> mulby2(5)
    10
    """
    return 2*a
    
    
import doctest
doctest.testmod()

python singleton and singleton borg

Singleton with same states
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

a=Borg()
a.toto = 12

b=Borg()
print b.toto
print id(a),id(b) # different ! but states are sames



real Singleton instance
class Singleton(object):
    def __new__(type):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type)
        return type._the_instance

a=Singleton()
a.toto = 12

b=Singleton()
print b.toto
print id(a),id(b) # the same !!




introspection with python

import inspect

def info():
    loc = inspect.currentframe(1).f_locals # its locals
    glob = inspect.currentframe(1).f_globals # its globals
    fct = inspect.currentframe(1).f_code.co_name #calling function

convert list of list/tuple to list of object named, python

my version of "named tuple"
class OList:
    """
        l=[("martin","jean"),("dupond","yves"),("klein","michel")]
        or
        l=[["martin","jean"],["dupond","yves"],["klein","michel"]]

        ll = OList("nom","prenom")(l)
        print ll[2].prenom,"==",ll[2][1],"==",l[2][1]
    """
    def __init__(self,*a):
        self.__n=list(a)
    def __call__(self,liste):
        class NList(list):
            def __init__(self,n,l):
                assert len(l)==len(n), "No match "+str(n)+" and "+str(l)
                list.__init__(self,l)
                for i in n:
                    setattr(self,i,l[ n.index(i) ])
                self.__noms = n
            def __repr__(self):
                m=" ".join(["""%s='%s'""" % (i,str(getattr(self,i))) for i in self.__noms])
                return "<objet %s>" % m
        return [ NList(self.__n, i) for i in liste ]

run a external command from python

with new subprocess module (py2.4)
from subprocess import Popen,PIPE

p = Popen(file, shell=True,stdout=PIPE,stderr=PIPE)
out = string.join(p.stdout.readlines() )
outerr = string.join(p.stderr.readlines() )


with old way :
import os
out= string.join(os.popen(file).readlines())


or
os.spawnvp(os.P_WAIT,"/usr/bin/mplayer",["","-ao","pcm",file])

# or 

os.spawnvp(os.P_NOWAIT,"/usr/bin/mplayer",["","-ao","pcm",file])

list files recursivly with python

import os
import stat

def walktree (top = ".", depthfirst = True):
    names = os.listdir(top)
    if not depthfirst:
        yield top, names
    for name in names:
        try:
            st = os.lstat(os.path.join(top, name))
        except os.error:
            continue
        if stat.S_ISDIR(st.st_mode):
            for (newtop, children) in walktree (os.path.join(top, name), depthfirst):
                yield newtop, children
    if depthfirst:
        yield top, names

for (basepath, children) in walktree("/home",False):
    for child in children:
        print os.path.join(basepath, child)
« Newer Snippets
Older Snippets »
Showing 11-20 of 22 total