Differences between revisions 4 and 5
Revision 4 as of 2009-11-20 22:29:36
Size: 18900
Editor: 63
Revision 5 as of 2009-11-20 22:30:45
Size: 18890
Editor: 63
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:

#how to write text to a file (not safe)
open('foo.txt', 'w').write('hello')

#how to loop a certain number (e.g. 10) of times
for x in range(10): 
    print x

#how to concatenate a number and a string
x = 1 
print str(x) + " is a string" 
print "%s is a string" % x

#how to test if a string contains another string
my_string = "abcdef"
if "abc" in my_string:
    has_abc = True

#check if an item is in a list or dictionary or tuple or set
my_list = [1, 2, 3, 4, 5]
if 1 in my_list:
    has_one = True

my_dict = {"a":1, "b": 2, "c": 3}
if "a" in my_dict:
   has_a = True

# Lambda (anonymous functions)
add = lambda x, y: x + y
print add(3,4) # prints "7"

# Reduce
from functools import reduce
def factorial(x):
  return reduce(lambda accum, x: accum * x, range(1, x+1), 1)

# Non-destructive sort on key
people = [ ... list of people objects ... ]
people_by_age = sorted(people, key=lambda person: person.age)

# Ternary expression (i.e. "BOOLEAN ? IF_TRUE : IF_FALSE")
print "a" if x == 1 else "b"
# Python 2.6 only!
# 2.5 or earlier: print (x == 1) and "a" or "b"

# Printing stuff nicely.
from pprint import pprint
pprint('Complex thing')

# generators/iteration
def generate_stuff ():
  yield "x"
  yield "y"
  yield "z"
for item in generate_stuff ():
  print item

#how to test if a string begins or ends with another string
my_string = "abcdef"
if my_string.startswith("abc"):
    starts_with_abc = True    
if my string.endswith("def")
    ends_with_def = True

#how to catch exceptions
grades = ['A', 'A-', 'B', 'C'] 
except ValueError, inst: 
    #print out error info
    print inst.args 

# Catching multiple exceptions in Python.
    "do something"
except (ExceptionOne, ExceptionTwo):
    # Note: The parens are important.
    "handle the exception"

# Convert a file url to a file path in a shell script
deurledfile=`python -c 'import sys, urlparse, urllib; print urllib.unquote(urlparse.urlparse(sys.argv[1]).path)' $1`

# change/update value in a file with "="
  fin = file('file1', 'r')
  fout = file( + '.new', 'w')
  for line in fin:
        fields = line.split('=') # Separate variable from value
        if "keyname" == fields[0].strip():
            line = "%s='%s'\n" % (fields[0], "newvalue")
except (OSError, IOError), e:
   print("can't update the file")

# how to make money in open source
1. get developers
2. bzr commit
4. profit

# how to generate pretty charts
import cairoplot
chartTitle = "Simulated model of Wine development" # Appears at the top of the chart produced at the end
chartData = {"Working Apps" : [], "Happy Users" : []}
for x in xrange(100):
    chartData["Working Apps"].append(float(x))
    chartData["Happy Users"].append(float(x))
 x_labels = [ "Project start", "25% bugs solved", "50% bugs solved", "75% bugs solved", "All bugs solved" ]
y_labels = [ "0%", "25%", "50%", "75%", "100%" ]
cairoplot.dot_line_plot( "wine-model-results", chartData, 600, 600, x_labels = x_labels, 
    y_labels = y_labels, axis = True, grid = True,
    x_title = chartTitle, y_title = "Percentage", series_legend=True )

#how to play a sound
import gst
player = gst.element_factory_make("playbin", "player")
player.set_property("uri", "file:///usr/share/sounds/ubuntu/stereo/bell.ogg")
import pygame

import pynotify

n = pynotify.Notification("message name", "message", "icon")

# more notify-osd stuff

# get the output of a command
import subprocess

date = subprocess.Popen(['date', '+%c'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = date.communicate()
print 'exit code', date.returncode

#open a link in a web browser
import webbrowser

url = ''

#get the text for an html page from the web
import urllib
f = urllib.urlopen(day_url)
html =

 #create a stock cancel button and pack it into the vbox 
  cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
  cancel_button.connect("clicked", on_cancel_clicked) 

# Parse XML file
import xml.dom
    dom = xml.dom.minidom.parseString(xml_content)
except ExpatError, e:
    print >> sys.stderr, 'Invalid XML:', e

for p_node in dom.getElementsByTagName('p'):
    print 'class of paragraph', p.attributes['class']
    for child in p_node.childNodes:
        print 'XML child node:', child

# search a file for a pattern and do something with every match
import re
for m in re.finditer('bug (\d+) blabla', text):
    print 'bug number': m.match(1)

# download an URL and process it line by line
import urllib
for line in'http://foo'):
   print line

# grep all versioned files in a Bazaar tree
# Best command ever
bzr ls -VR --kind=file --null | xargs -0 grep -In <REGEX>
git grep <REGEX>

Creating a Gtk+ TreeView:

# Instantiate the tree store and specify the data types
store = gtk.TreeStore(str, gtk.gdk.Pixbuf, int, bool)

# Create a TreeViewColumn
col = gtk.TreeViewColumn("File")
# Create a column cell to display text
col_cell_text = gtk.CellRendererText()
# Create a column cell to display an image
col_cell_img = gtk.CellRendererPixbuf()
# Add the cells to the column
col.pack_start(col_cell_img, False)
col.pack_start(col_cell_text, True)
# Bind the text cell to column 0 of the tree's model
col.add_attribute(col_cell_text, "text", 0)
# Bind the image cell to column 1 of the tree's model
col.add_attribute(col_cell_img, "pixbuf", 1)

col2 = gtk.TreeViewColumn("Size")
col2_cell_text = gtk.CellRendererText()
col2.add_attribute(col2_cell_text, "text", 2)

# Create the TreeView and set our data store as the model
tree = gtk.TreeView(store)
# Append the columns to the TreeView

#make a new ListStore when columns are calculated at runtim
col_count = 100
self.list_store = gtk.ListStore( 
                        *[gobject.TYPE_STRING for i in range(col_count)])

#Put data into desktop CouchDB:

from desktopcouch.records.server import CouchDatabase
from desktopcouch.records.record import Record as CouchRecord

db = CouchDatabase("dbname", create=True)
record = CouchRecord({"a": 1, "b": 2}, record_type="http://recordtypeurl", record_id=XXX)

# Call a desktop CouchDB view:

view = """function(doc) { if (doc) emit(doc._id, doc); }"""
if not self.messages.view_exists("myview", "myapp"):
    self.messages.add_view("myview", view, None, "myapp")
result = self.messages.execute_view("myview", "myapp")

#Creating a new Tomboy note
def create_tomboy_note(text):
  bus = dbus.SessionBus()
  obj = bus.get_object("org.gnome.Tomboy", "/org/gnome/Tomboy/RemoteControl")
  tomboy = dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")
  n = tomboy.CreateNote()
  tomboy.SetNoteContents(n, text)

#Set Pidgin status
def set_pidgin_status_text(message):
  bus = dbus.SessionBus()
  obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
  purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
  current = purple.PurpleSavedstatusGetType(purple.PurpleSavedstatusGetCurrent())
  status = purple.PurpleSavedstatusNew("", current)
  purple.PurpleSavedstatusSetMessage(status, message)

#How to embed a WebKit renderer in an application:
import gtk, webkit

window = gtk.Window()
window.connect("destroy", gtk.main_quit)
web = webkit.WebView()"")


# Put an icon in a Gtk+ text entry
GtkWidget *entry = gtk_entry_new();
    GTK_ENTRY(entry),           // specify which entry widget
    GTK_ENTRY_ICON_SECONDARY,   // put the icon at the end
    GTK_STOCK_ABOUT);           // make it display the "about" icon

# Display a progress bar in a Gtk+ entry
GtkWidget *entry = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(entry), "This is a test");
gtk_entry_set_progress_fraction(GTK_ENTRY(entry), 0.5);

#Get Gtk+ theme colors
def get_theme_colors(w):
  d = {}
  for i in ["base", "text", "fg", "bg"]:
    d[i] = Color.from_gtk_color(
      getattr(w.get_style(), i)[gtk.STATE_NORMAL].to_string())

    d["%s_selected" % i] = Color.from_gtk_color(
      getattr(w.get_style(), i)[gtk.STATE_SELECTED].to_string())

  return d

# Draw a rounded rectangle in Cairo
c = self.window.cairo_create()
x,y,w,h = w.allocation # x, y, width, height

c.line_to(x+w-r,y);   c.curve_to(x+w,y,x+w,y,x+w,y+r)
c.line_to(x+w,y+h-r); c.curve_to(x+w,y+h,x+w,y+h,x+w-r,y+h)
c.line_to(x+r,y+h);   c.curve_to(x,y+h,x,y+h,x,y+h-r)
c.line_to(x,y+r);     c.curve_to(x,y,x,y,x+r,y)

# A Gtk+ label that supports text wrapping with fluid reflow

import gtk, pango, gobject

class WrapLabel(gtk.Frame):
  def __init__(self, markup = None, text = None):

    self.pango_layout = self.create_pango_layout(text or "")
    if markup: self.pango_layout.set_markup(markup)

    ev = gtk.EventBox()

  def do_expose_event(self, event):
    gtk.Frame.do_expose_event(self, event)
    self.set_size_request(-1, (self.pango_layout.get_size()[1] // pango.SCALE + 10))

    x,y,w,h = self.allocation
    gc = self.window.new_gc()
    self.pango_layout.set_width(w * pango.SCALE)
    self.window.draw_layout(gc, x, y, self.pango_layout)


w = gtk.Window()
w.connect("destroy", gtk.main_quit)

label = WrapLabel("This is a test")


# Build a Gtk+ toolbar with UIManager
def on_action(action):
  print "Action performed!"

actions = gtk.ActionGroup("Actions")
  ("bold", gtk.STOCK_BOLD, "_Bold", "<ctrl>B", None, on_action),
  ("italic", gtk.STOCK_ITALIC, "_Italic", "<ctrl>I", None, on_action),
  ("underline", gtk.STOCK_UNDERLINE, "_Underline", "<ctrl>U", None, on_action),

ui_def = """
<toolbar name="toolbar_format">
  <toolitem action="bold" />
  <toolitem action="italic" />
  <toolitem action="underline" />

ui = gtk.UIManager()

vb = gtk.VBox()
vb.pack_start(ui.get_widget("/toolbar_format"), False)
vb.pack_start(editor, True)

# what to do instead of using eval() [this is safe security-wise]
import ast
ast.literal_eval ('[1,2,3,(4,5,6)]')

# How to use doctests well.
# Don't.

# getting your packages updated
# import os
# os.system('evolution')
# actually, he'll notice by himself.
from time import sleep
sleep (8 * 60 * 60) # go to bed

# How to set up a threaded GTK+ app
import pygtk
import gobject
import gtk

from threading import Thread

class Window(gtk.Window):
    '''GtkWindow wrapper'''

    def __init__(self):
        self.set_title("Threaded GTK+ Sample")
        self.set_default_size(320, 240)

    def timeout_thread():
        '''Threaded timeout demo'''

if __name__ == "__main__":
        win = Window()
    except KeyboardInterrupt:

#set the text on a pygtk widget in a Quickly app
widge = self.builder.get_object("object_name").set_text(my_string)

#get the text for a pygtk widdget in a Quickly app

#download an image from the web and save it
import urllib
img_stream = urllib.urlopen(url)
img_file = open(fname,'w')
del img_file

#download a large file using a read buffer, saves memory
import urllib
img_stream = urllib.urlopen(url)
img_file = open(fname,'w')
while 1:
    buf =
    if buf == "":
del img_file

# Still dealing with large files
# Compute the md5sum of a file without loading it all in memory
f = open(filepath)
digest =
while 1:
    buf =
    if buf == "":
print digest.hexdigest()

#how to use couchgrid and change the label of the column
from desktopcouch.records.couchgrid import CouchGrid
db="db name"
record_type="record type"
#the keys field is for to label the column and give a discription of what is in that column
keys=["key","another key"]

#put the couchgrid into a vbox

#change the name of the couchgrid column
couchgrid.get_column(0).set_title("some name")

#make the couchgrid column name dissapear
self.couchgrid.set_headers_visible (False)

#how to get stuff from a desktop couch db

from desktopcouch.records.server import CouchDatabase
from desktopcouch.records.record import Record

__couchdb = CouchDatabase("db name",create=True)
record_type="record type"       
results = __couchdb.get_records(record_type=record_type,create_view=True)

#this takes the output of results and puts it into a string x
for r in results:
    x+=r.value["key"]+" "

# PDB tip
pp locals()

# Parsing a line-based text file with separators
# Not that advanced, but I seem to have to write this all the time.

def parse_line(lines, separator):
    for line in lines:
        yield [token.strip() for token in line.split(separator)]

 #create a pygtk window on the fly 
  test_window = gtk.Window(gtk.WINDOW_TOPLEVEL) 
  test_window.connect("destroy", gtk.main_quit) 
  test_window.set_title("my title") 

# reading a bunch of stuff out of a function
total = []
for chunk in iter(lambda:, ''):
result = ''.join(total)

# Transposing a list of lists.

# easy (if not efficient) sorted merging of two lists (works also for dicts)
l1 = [4, 5, 6]
l2 = [4, 6, 7]
for item in sorted(set(l1).union(l2)):
  # do whatever

#add a message indicator
import indicate, time

def display(indicator):
    print "Ah, my indicator has been displayed"

def server_display(server):
    print "Ah, my server has been displayed"

server = indicate.indicate_server_ref_default()
server.connect("server-display", server_display)
indicator = indicate.Indicator()
indicator.set_property("subtype", "im")
indicator.set_property("sender", "IM Client Test")
indicator.set_property_time("time", time.time())
indicator.connect("user-display", display)

# post a microblog message using gwibber from karmic
bus = dbus.SessionBus()
db_mb_obj = bus.get_object("com.Gwibber", "/com/gwibber/Microblog")
microblog = dbus.Interface(db_mb_obj, "com.Gwibber")
import gwibber, gwibber.config

accounts = gwibber.config.Accounts()
args = ["This is a test message"]
for account in accounts:
    if account["send_enabled"]:
        acctid = account["id"]
        "source": "lolz",
        "id": "send-%s-%s" % (acctid, time.time()),
        "accountid": acctid,
        "args": args,
        "opname": "send",

# post a microblog message using gwibber in lucid (not yet uploaded)
import gwibber.utils
foo = gwibber.utils.GwibberPublic()"This is a test message")


# parse command line arguments
import optparse
op = optparse.OptionParser('%prog [options] inputfile')
op.add_option('-f', '--force', action='store_true', dest='force', default=False, help='Delete my files without asking')
op.add_option('-o', '--output-file', dest='outfile', help='Output file path; if not given, output to stdout')
(opts, args) = op.parse_args()
if opts.force:
   print 'force enabled'
input_file = args[0]
if opts.outfile:
   outfile = open(opts.outfile, 'w')
   outfile = sys.stdout

# SQLite
import sqlite3 as dbapi2
db = dbapi2.connect('mydb.sqlite')

cur1 = db.cursor()
cur1.execute('CREATE TABLE friends (name VARCHAR(255), phone int)')

cur1 = db.cursor()
cur1.execute('SELECT phone FROM friends WHERE name = ?', ['Fred']) # does proper quoting
for (phone) in cur1:
    print 'Fred has telephone number', phone

# Apply file rights from src to dest
import os, stat
st = os.stat(src_file_name)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dest_file_name, mode)

#translations using gettext 
import gettext

#print hello world(it needs to be translated first though)
print gettext.gettext("hello")

# A really simple unittest module.

import unittest

class TestThing(unittest.TestCase):

    def setUp(self):
        super(unittest.TestCase, self).setUp() = [2, 3, 5]
    def test_list_reversal(self):
        backwards = reversed(
        self.assertEqual([5, 3, 2], backwards)
    def tearDown(self):
# Note that you wouldn't really use setUp and tearDown for something this
# simple. Use them when you have something fairly complicated to set up.

# Look for a program that is already registered over dbus
import dbus
session_bus = dbus.SessionBus()
if session_bus.request_name ('') != 1:
  print 'someone already has this name'

#open a file from a dialog
dialog = gtk.FileChooserDialog("Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN,

  if == gtk.RESPONSE_OK:
    fn = dialog.get_filename()
    if os.path.exists(fn):
        print fn

Quickly/Snippets (last edited 2011-04-09 22:52:34 by punksolid)