Snippets
Write text to a file (not safe)
Loop a certain number of times
Concetenate a number and a string
Test if a string contains another string
Check if an item is in a list or dictionary or tuple or set
Anonymous functions (lambda)
Reduce
Non-destructive sort on key
Ternary expression
Python 2.5 or later
Python 2.4 or earlier
1 print (x == 1) and "a" or "b"
Printing stuff nicely
Generators / Iteration
How to test if a string begins or ends with another string
How to catch exceptions
Catching multiple exceptions
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
- get developers
- bzr commit
- ???
- profit
How to generate pretty charts
See http://yokozar.org/blog/archives/48
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
notify-osd
# more notify-osd stuff
Get the output of a command
Open a link in a web browser
Get the text for an HTML page from the web
Create a stock cancel button and pack it into the vbox
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 text for a pattern and do something with every match
Download an URL and process it line by 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
14 col.add_attribute(col_cell_text, "text", 0)
15 # Bind the image cell to column 1 of the tree's model
16 col.add_attribute(col_cell_img, "pixbuf", 1)
17
18 col2 = gtk.TreeViewColumn("Size")
19 col2_cell_text = gtk.CellRendererText()
20 col2.pack_start(col2_cell_text)
21 col2.add_attribute(col2_cell_text, "text", 2)
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
Put data into desktop CouchDB
Call a desktop CouchDB view
Listen to changes in CouchDB
1 from desktopcouch.records.server import CouchDatabase
2
3 # we are going to be listening to the changes
4 def changes_cb(seq=None, id=None, changes=None):
5 print seq
6 print id
7 print changes
8
9 db = CouchDatabase("fosdem")
10 # better, use glib main loop or twisted task!
11 while True:
12 db.report_changes(changes_cb)
13 time.sleep(30)
Add attachments in CouchDB
Creating a new Tomboy note
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
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 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
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)
6 self.set_shadow_type(gtk.SHADOW_NONE)
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)
14 self.add(ev)
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")
31 w.add(label)
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")
5 actions.add_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)
21 ui.add_ui_from_string(ui_def)
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]
How to use doctests well
Don't.
Getting your packages updated
How to set up a threaded GTK+ app
1 import pygtk
2 pygtk.require('2.0')
3 import gobject
4 import gtk
5
6 from threading import Thread
7
8
9 class Window(gtk.Window):
10 '''GtkWindow wrapper'''
11
12 def __init__(self):
13 gtk.Window.__init__(self)
14 self.set_title("Threaded GTK+ Sample")
15 self.set_default_size(320, 240)
16 Thread(target=self.timeout_thread).start()
17
18 def timeout_thread():
19 '''Threaded timeout demo'''
20 gtk.gdk.threads_enter()
21 self.show()
22 gtk.gdk_threads_leave()
23
24 if __name__ == "__main__":
25 gobject.threads_init()
26 gtk.gdk.threads_init()
27 try:
28 win = Window()
29 win.show()
30 gtk.gdk.threads_enter()
31 gtk.main()
32 gtk.gdk.threads_leave()
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)
Download an image from the web and save it
Download a large file using a read buffer, saves memory
Compute the md5sum of a file without loading it all in memory
Still dealing with large files.
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
14 self.couchgrid.set_headers_visible (False)
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=" ".join(r.value["key"] for r in results)
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.
Create a pygtk window on the fly
Reading a bunch of stuff out of a function
Printing to a physical printer on linux
Transposing a list of lists
zip(*list_of_lists)
Easy sorted merging of two lists (works also for dicts)
Not exactly efficient.
Add a message indicator
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": "my app name",
13 "id": "send-%s-%s" % (acctid, time.time()),
14 "accountid": acctid,
15 "args": args,
16 "opname": "send",
17 })
In Lucid (not yet uploaded)
Parse command line arguments
1 import optparse
2 op = optparse.OptionParser('%prog [options] inputfile')
3 op.add_option('-f', '--force', action='store_true', dest='force', default=False, help='Delete my files without asking')
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
Translations using gettext
A really simple unittest module.
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
Open a file from a dialog
Create a TextEntry with auto-completion in PyGTK
1 import pygtk
2 import gtk
3 import gobject
4
5 # contains the data for autocomplition, can be dynamic
6 options = ("Friends", "Family", "Person", "Test")
7
8 def entry_changed (editable, *user_data):
9 comp = user_data[0]
10 text = editable.get_text()
11 matches = []
12 if text:
13 for current_option in options:
14 if current_option.startswith(text):
15 matches.append(current_option)
16 model = comp.get_model()
17 model.clear()
18 for match in matches:
19 model.append([match])
20
21 win = gtk.Window()
22 entry = gtk.Entry()
23 completion = gtk.EntryCompletion()
24 entry.set_completion(completion)
25 liststore = gtk.ListStore(gobject.TYPE_STRING)
26 completion.set_model(liststore)
27 completion.set_text_column(0)
28 win.add(entry)
29 entry.connect("changed", entry_changed, completion)
30 win.connect("delete-event", gtk.main_quit)
31 win.show_all()
32 gtk.main()
Check if script runs as root
Quickly/Snippets (last edited 2011-04-09 22:52:34 by dsl-189-174-18-150-dyn)