• Immutable Page
• Info
• Attachments

## Snippets

Differences between revisions 8 and 9

## Write text to a file (not safe)

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

## Loop a certain number of times

```   1 for x in range(10):
2     print x
```

## Concetenate a number and a string

```   1 x = 1
2 print str(x) + " is a string"
3 print "%s is a string" % x
```

## Test if a string contains another string

```   1 my_string = "abcdef"
2 if "abc" in my_string:
3     has_abc = True
```

## Check if an item is in a list or dictionary or tuple or set

```   1 my_list = [1, 2, 3, 4, 5]
2 if 1 in my_list:
3     has_one = True
4
5 my_dict = {"a": 1, "b": 2, "c": 3}
6 if "a" in my_dict:
7    has_a = True
```

## Anonymous functions (lambda)

```   1 add = lambda x, y: x + y
2 print add(3, 4) # prints "7"
```

## Reduce

```   1 from functools import reduce
2 def factorial(x):
3     return reduce(lambda accum, x: accum * x, range(1, x + 1), 1)
```

## Non-destructive sort on key

```   1 people = [ ... list of people objects ... ]
2 people_by_age = sorted(people, key=lambda person: person.age)
```

## Ternary expression

### Python 2.6 or later

```   1 # Ternary expression (i.e. "BOOLEAN ? IF_TRUE : IF_FALSE")
2 print "a" if x == 1 else "b"
```

### Python 2.5 or earlier

```   1 print (x == 1) and "a" or "b"
```

## Printing stuff nicely

```   1 from pprint import pprint
2 pprint('Complex thing')
```

## Generators / Iteration

```   1 # generators/iteration
2 def generate_stuff ():
3     yield "x"
4     yield "y"
5     yield "z"
6
7 for item in generate_stuff ():
8     print item
```

## How to test if a string begins or ends with another string

```   1 my_string = "abcdef"
2 if my_string.startswith("abc"):
3     starts_with_abc = True
4 if my string.endswith("def"):
5     ends_with_def = True
```

## How to catch exceptions

```   1 grades = ['A', 'A-', 'B', 'C']
2 try:
4 except ValueError, inst:
5     # Print the error information
6     print inst.args
```

## Catching multiple exceptions

```   1 try:
2     "do something"
3 except (ExceptionOne, ExceptionTwo):
4     # Note: The parens are important.
5     "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 '='

```   1 try:
2     fin = file('file1', 'r')
3     fout = file(fin.name + '.new', 'w')
4     for line in fin:
5         fields = line.split('=') # Separate variable from value
6         if "keyname" == fields[0].strip():
7             line = "%s='%s'\n" % (fields[0], "newvalue")
8         fout.write(line)
9     fout.close()
10     fin.close()
11     os.rename(fout.name, fin.name)
12 except (OSError, IOError), e:
13     print("can't update the file")
```

## How to make money in open source

1. get developers
2. bzr commit
3. ???
4. profit

## How to generate pretty charts

```   1 import cairoplot
2
3 # Appears at the top of the chart produced at the end
4 chartTitle = "Simulated model of Wine development"
5 chartData = {"Working Apps" : [], "Happy Users" : []}
6 for x in xrange(100):
7     chartData["Working Apps"].append(float(x))
8     chartData["Happy Users"].append(float(x))
9     x_labels = [
10         "Project start", "25% bugs solved", "50% bugs solved",
11         "75% bugs solved", "All bugs solved"]
12     y_labels = ["0%", "25%", "50%", "75%", "100%"]
13     cairoplot.dot_line_plot(
14         "wine-model-results", chartData, 600, 600, x_labels = x_labels,
15         y_labels = y_labels, axis = True, grid = True,
16         x_title = chartTitle, y_title = "Percentage", series_legend=True )
```

## How to play a sound

```   1 import gst
2 player = gst.element_factory_make("playbin", "player")
3 player.set_property("uri", "file:///usr/share/sounds/ubuntu/stereo/bell.ogg")
4 player.set_state(gst.STATE_PLAYING)
5 # or
6 import pygame
7 pygame.mixer.init()
9 pygame.mixer.music.play()
```

## notify-osd

```   1 import pynotify
2
3 n = pynotify.Notification("message name", "message", "icon")
4 n.show()
```

# more notify-osd stuff

## Get the output of a command

```   1 import subprocess
2
3 date = subprocess.Popen(['date', '+%c'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
4 (out, err) = date.communicate()
5 print 'exit code', date.returncode
```

```   1 import webbrowser
2
4 webbrowser.open_new(url)
```

## Get the text for an HTML page from the web

```   1 import urllib
2 f = urllib.urlopen(day_url)
```

## Create a stock cancel button and pack it into the vbox

```   1 cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
2 cancel_button.show()
3 cancel_button.connect("clicked", on_cancel_clicked)
```

## Parse XML file

```   1 import xml.dom
2 try:
3     dom = xml.dom.minidom.parseString(xml_content)
4 except ExpatError, e:
5     print >> sys.stderr, 'Invalid XML:', e
6
7 for p_node in dom.getElementsByTagName('p'):
8     print 'class of paragraph', p.attributes['class']
9     for child in p_node.childNodes:
10         print 'XML child node:', child
```

## Search a file for a pattern and do something with every match

```   1 import re
2 for m in re.finditer('bug (\d+) blabla', text):
3     print 'bug number': m.match(1)
```

```   1 import urllib
2 for line in urllib.open('http://foo'):
3     print line
```

## Grep all versioned files in a Bazaar tree

```# Best command ever
bzr ls -VR --kind=file --null | xargs -0 grep -In <REGEX>```

## Grep all versioned files in a Git tree

`git grep <REGEX>`

## Creating a Gtk+ TreeView

```   1 # Instantiate the tree store and specify the data types
2 store = gtk.TreeStore(str, gtk.gdk.Pixbuf, int, bool)
3
4 # Create a TreeViewColumn
5 col = gtk.TreeViewColumn("File")
6 # Create a column cell to display text
7 col_cell_text = gtk.CellRendererText()
8 # Create a column cell to display an image
9 col_cell_img = gtk.CellRendererPixbuf()
10 # Add the cells to the column
11 col.pack_start(col_cell_img, False)
12 col.pack_start(col_cell_text, True)
13 # Bind the text cell to column 0 of the tree's model
15 # Bind the image cell to column 1 of the tree's model
17
18 col2 = gtk.TreeViewColumn("Size")
19 col2_cell_text = gtk.CellRendererText()
20 col2.pack_start(col2_cell_text)
22
23 # Create the TreeView and set our data store as the model
24 tree = gtk.TreeView(store)
25 # Append the columns to the TreeView
26 tree.append_column(col)
27 tree.append_column(col2)
```

## Make a new ListStore when columns are calculated at runtime

```   1 col_count = 100
2 self.list_store = gtk.ListStore(
3     *[gobject.TYPE_STRING for i in range(col_count)])
```

## Put data into desktop CouchDB

```   1 from desktopcouch.records.server import CouchDatabase
2 from desktopcouch.records.record import Record as CouchRecord
3
4 db = CouchDatabase("dbname", create=True)
5 record = CouchRecord(
6     {"a": 1, "b": 2}, record_type="http://recordtypeurl",
7     record_id=XXX)
8 db.put_record(record)
```

## Call a desktop CouchDB view

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

## Creating a new Tomboy note

```   1 def create_tomboy_note(text):
2     bus = dbus.SessionBus()
3     obj = bus.get_object("org.gnome.Tomboy", "/org/gnome/Tomboy/RemoteControl")
4     tomboy = dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")
5
6     n = tomboy.CreateNote()
7     tomboy.DisplayNote(n)
8     tomboy.SetNoteContents(n, text)
```

## Set Pidgin status

```   1 def set_pidgin_status_text(message):
2     bus = dbus.SessionBus()
3     obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
4     purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
5
6     current = purple.PurpleSavedstatusGetType(purple.PurpleSavedstatusGetCurrent())
7     status = purple.PurpleSavedstatusNew("", current)
8     purple.PurpleSavedstatusSetMessage(status, message)
9     purple.PurpleSavedstatusActivate(status)
```

## Embed a WebKit renderer in an application

```   1 import gtk, webkit
3
4 window = gtk.Window()
5 window.connect("destroy", gtk.main_quit)
6 web = webkit.WebView()
7 web.open("http://ubuntu.com")
8
10 window.show_all()
11 gtk.main()
```

## Put an icon in a Gtk+ text entry

```GtkWidget *entry = gtk_entry_new();
gtk_entry_set_icon_from_stock(
GTK_ENTRY(entry),           // specify which entry widget
GTK_ENTRY_ICON_SECONDARY,   // put the icon at the end

## 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

```   1 def get_theme_colors(w):
2     d = {}
3
4     for i in ["base", "text", "fg", "bg"]:
5         d[i] = Color.from_gtk_color(
6             getattr(w.get_style(), i)[gtk.STATE_NORMAL].to_string())
7
8         d["%s_selected" % i] = Color.from_gtk_color(
9             getattr(w.get_style(), i)[gtk.STATE_SELECTED].to_string())
10
11     return d
```

## Draw a rounded rectangle in Cairo

```   1 c = self.window.cairo_create()
2 x,y,w,h = w.allocation # x, y, width, height
3
4 c.move_to(x+r,y)
5 c.line_to(x+w-r,y);   c.curve_to(x+w,y,x+w,y,x+w,y+r)
6 c.line_to(x+w,y+h-r); c.curve_to(x+w,y+h,x+w,y+h,x+w-r,y+h)
7 c.line_to(x+r,y+h);   c.curve_to(x,y+h,x,y+h,x,y+h-r)
8 c.line_to(x,y+r);     c.curve_to(x,y,x,y,x+r,y)
9 c.close_path()
10 c.fill()
```

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

```   1 import gtk, pango, gobject
2
3 class WrapLabel(gtk.Frame):
4     def __init__(self, markup = None, text = None):
5         gtk.Frame.__init__(self)
7
8         self.pango_layout = self.create_pango_layout(text or "")
9         if markup: self.pango_layout.set_markup(markup)
10         self.pango_layout.set_wrap(pango.WRAP_WORD_CHAR)
11
12         ev = gtk.EventBox()
13         ev.set_visible_window(False)
15
16     def do_expose_event(self, event):
17         gtk.Frame.do_expose_event(self, event)
18         self.set_size_request(-1, (self.pango_layout.get_size()[1] // pango.SCALE + 10))
19
20         x,y,w,h = self.allocation
21         gc = self.window.new_gc()
22         self.pango_layout.set_width(w * pango.SCALE)
23         self.window.draw_layout(gc, x, y, self.pango_layout)
24
25 gobject.type_register(WrapLabel)
26
27 w = gtk.Window()
28 w.connect("destroy", gtk.main_quit)
29
30 label = WrapLabel("This is a test")
32
33 w.show_all()
34 gtk.main()
```

## Build a Gtk+ toolbar with UIManager

```   1 def on_action(action):
2     print "Action performed!"
3
4 actions = gtk.ActionGroup("Actions")
6         ("bold", gtk.STOCK_BOLD, "_Bold", "<ctrl>B", None, on_action),
7         ("italic", gtk.STOCK_ITALIC, "_Italic", "<ctrl>I", None, on_action),
8         ("underline", gtk.STOCK_UNDERLINE, "_Underline", "<ctrl>U", None, on_action),
9         ])
10
11 ui_def = """
12 <toolbar name="toolbar_format">
13   <toolitem action="bold" />
14   <toolitem action="italic" />
15   <toolitem action="underline" />
16 </toolbar>
17 """
18
19 ui = gtk.UIManager()
20 ui.insert_action_group(actions)
22
23 vb = gtk.VBox()
24 vb.pack_start(ui.get_widget("/toolbar_format"), False)
25 vb.pack_start(editor, True)
```

## What to do instead of using eval() [this is safe security-wise]

```   1 import ast
2 ast.literal_eval ('[1,2,3,(4,5,6)]')
```

## How to use doctests well

Don't.

```   1 import os
2 os.system('evolution mailto:seb128@debian.org?subject=hi')
3 # actually, he'll notice by himself.
4 from time import sleep
5 sleep (8 * 60 * 60) # go to bed
```

## How to set up a threaded GTK+ app

```   1 import pygtk
2 pygtk.require('2.0')
3 import gobject
4 import gtk
5
7
8
9 class Window(gtk.Window):
10     '''GtkWindow wrapper'''
11
12     def __init__(self):
13         gtk.Window.__init__(self)
15         self.set_default_size(320, 240)
17
21         self.show()
23
24 if __name__ == "__main__":
27     try:
28         win = Window()
29         win.show()
31         gtk.main()
33     except KeyboardInterrupt:
34         gtk.main_quit()
```

## Set the text on a pygtk widget in a Quickly app

```   1 widge = self.builder.get_object("object_name").set_text(my_string)
```

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

```   1 self.builder.get_object("object_name").get_text(my_string)
```

```   1 import urllib
2 img_stream = urllib.urlopen(url)
3 img_file = open(fname,'w')
5 del img_file
```

```   1 import urllib
2 img_stream = urllib.urlopen(url)
3 img_file = open(fname,'w')
4 while 1:
6     if buf == "":
7         break
8     img_file.write(buf)
9 del img_file
```

## Compute the md5sum of a file without loading it all in memory

Still dealing with large files.

```   1 f = open(filepath)
2 digest = md5.new()
3 while 1:
5     if buf == "":
6         break
7     digest.update(buf)
8 f.close()
9 print digest.hexdigest()
```

## Use couchgrid and change the label of the column

```   1 from desktopcouch.records.couchgrid import CouchGrid
2 db="db name"
3 record_type="record type"
4 #the keys field is for to label the column and give a discription of what is in that column
5 keys=["key","another key"]
6 self.couchgrid=CouchGrid(db,record_type=record_type,keys=keys)
7 self.couchgrid.show()
8 #put the couchgrid into a vbox
9 self.builder.get_object("vbox1").pack_end(self.couchgrid)
10 self.couchgrid.editable=True
11 #change the name of the couchgrid column
12 couchgrid.get_column(0).set_title("some name")
13 #make the couchgrid column name dissapear
```

## Get stuff from a desktop couch db

```   1 from desktopcouch.records.server import CouchDatabase
2 from desktopcouch.records.record import Record
3
4 __couchdb = CouchDatabase("db name",create=True)
5 record_type="record type"
6 results = __couchdb.get_records(record_type=record_type,create_view=True)
7
8 #this takes the output of results and puts it into a string x
9 x=""
10 for r in results:
11     x+=r.value["key"]+" "
```

## PDB tip

`pp locals()`

## Parse a line-based text file with separators

Not that advanced, but I seem to have to write this all the time.

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

## Create a pygtk window on the fly

```   1 test_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
2 test_window.connect("destroy", gtk.main_quit)
3 test_window.set_title("my title")
4 test_window.set_default_size(200,75)
5 test_window.show()
```

## Reading a bunch of stuff out of a function

```   1 total = []
2 for chunk in iter(lambda: file.read(4096), ''):
3     total.append(chunk)
4 result = ''.join(total)
```

## Transposing a list of lists

`zip(*list_of_lists)`

## Easy sorted merging of two lists (works also for dicts)

Not exactly efficient.

```   1 l1 = [4, 5, 6]
2 l2 = [4, 6, 7]
3 for item in sorted(set(l1).union(l2)):
4     do_a_thing(item)
```

```   1 import indicate, time
2
3 def display(indicator):
4     print "Ah, my indicator has been displayed"
5
6 def server_display(server):
7     print "Ah, my server has been displayed"
8
9 server = indicate.indicate_server_ref_default()
10 server.set_type("message.im")
11 server.set_desktop_file("/usr/share/applications/empathy.desktop")
12 server.connect("server-display", server_display)
13 indicator = indicate.Indicator()
14 indicator.set_property("subtype", "im")
15 indicator.set_property("sender", "IM Client Test")
16 indicator.set_property_time("time", time.time())
17 indicator.show()
18 indicator.connect("user-display", display)
```

## Post a microblog message using Gwibber

### In Karmic

```   1 bus = dbus.SessionBus()
2 db_mb_obj = bus.get_object("com.Gwibber", "/com/gwibber/Microblog")
3 microblog = dbus.Interface(db_mb_obj, "com.Gwibber")
4 import gwibber, gwibber.config
5
6 accounts = gwibber.config.Accounts()
7 args = ["This is a test message"]
8 for account in accounts:
9     if account["send_enabled"]:
10         acctid = account["id"]
11     microblog.operation({
12         "source": "lolz",
13         "id": "send-%s-%s" % (acctid, time.time()),
14         "accountid": acctid,
15         "args": args,
16         "opname": "send",
17         })
```

### In Lucid (not yet uploaded)

```   1 import gwibber.utils
2 foo = gwibber.utils.GwibberPublic()
3 foo.post("This is a test message")
```

## Parse command line arguments

```   1 import optparse
2 op = optparse.OptionParser('%prog [options] inputfile')
4 op.add_option('-o', '--output-file', dest='outfile', help='Output file path; if not given, output to stdout')
5 (opts, args) = op.parse_args()
6 if opts.force:
7     print 'force enabled'
8 input_file = args[0]
9 if opts.outfile:
10     outfile = open(opts.outfile, 'w')
11 else:
12     outfile = sys.stdout
```

## SQLite

```   1 import sqlite3 as dbapi2
2 db = dbapi2.connect('mydb.sqlite')
3
4 cur1 = db.cursor()
5 cur1.execute('CREATE TABLE friends (name VARCHAR(255), phone int)')
6 cur1.commit()
7
8 cur1 = db.cursor()
9 cur1.execute('SELECT phone FROM friends WHERE name = ?', ['Fred']) # does proper quoting
10 for (phone) in cur1:
11     print 'Fred has telephone number', phone
```

## Apply file rights from src to dest

```   1 import os, stat
2 st = os.stat(src_file_name)
3 mode = stat.S_IMODE(st.st_mode)
4 os.chmod(dest_file_name, mode)
```

## Translations using gettext

```   1 import gettext
2
3 # Print 'hello' (it needs to be translated first though).
4 print gettext.gettext("hello")
```

## A really simple unittest module.

```   1 import unittest
2
3 class TestThing(unittest.TestCase):
4
5     def setUp(self):
6         super(unittest.TestCase, self).setUp()
7         self.data = [2, 3, 5]
8
9     def test_list_reversal(self):
10         backwards = reversed(self.data)
11         self.assertEqual([5, 3, 2], backwards)
12
13     def tearDown(self):
14         del self.data
```

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

```   1 import dbus
2 session_bus = dbus.SessionBus()
3 if session_bus.request_name ('net.soft.name') != 1:
4     print 'someone already has this name'
5     exit()
```

## Open a file from a dialog

```   1 dialog = gtk.FileChooserDialog(
2     "Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN,
3     (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
4
5 if dialog.run() == gtk.RESPONSE_OK:
6     fn = dialog.get_filename()
7     if os.path.exists(fn):
8         print fn
9 dialog.destroy()
```

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