Snippets
Differences between revisions 4 and 17 (spanning 13 versions)
18900
Comment:
|
22803
using hashlib instead for md5
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
{{{ #!python |
== Write text to a file (not safe) == {{{ #!python |
Line 6: | Line 6: |
#how to loop a certain number (e.g. 10) of times for x in range(10): |
}}} == Loop a certain number of times == {{{ #!python for x in range(10): |
Line 10: | Line 13: |
#how to concatenate a number and a string x = 1 print str(x) + " is a string" |
}}} == Concetenate a number and a string == {{{ #!python x = 1 print str(x) + " is a string" |
Line 15: | Line 21: |
#how to test if a string contains another string |
}}} == Test if a string contains another string == {{{ #!python |
Line 20: | Line 30: |
#check if an item is in a list or dictionary or tuple or set |
}}} == Check if an item is in a list or dictionary or tuple or set == {{{ #!python |
Line 26: | Line 40: |
my_dict = {"a":1, "b": 2, "c": 3} | my_dict = {"a": 1, "b": 2, "c": 3} |
Line 29: | Line 43: |
# Lambda (anonymous functions) |
}}} == Anonymous functions (lambda) == {{{ #!python |
Line 32: | Line 50: |
print add(3,4) # prints "7" # Reduce from functools import reduce |
print add(3, 4) # prints "7" }}} == Reduce == {{{ #!python from functools import reduce # remove this line on 2.x |
Line 37: | Line 58: |
return reduce(lambda accum, x: accum * x, range(1, x+1), 1) # Non-destructive sort on key |
return reduce(lambda accum, x: accum * x, range(1, x + 1), 1) }}} == Non-destructive sort on key == {{{ #!python |
Line 42: | Line 66: |
}}} == Ternary expression == === Python 2.5 or later === {{{ #!python |
|
Line 45: | Line 76: |
# Python 2.6 only! # 2.5 or earlier: print (x == 1) and "a" or "b" # Printing stuff nicely. |
}}} === Python 2.4 or earlier === {{{ #!python print (x == 1) and "a" or "b" }}} == Printing stuff nicely == {{{ #!python |
Line 52: | Line 91: |
}}} == Generators / Iteration == {{{ #!python |
|
Line 56: | Line 98: |
yield "x" yield "y" yield "z" |
yield "x" yield "y" yield "z" |
Line 61: | Line 103: |
print item #how to test if a string begins or ends with another string |
print item }}} == How to test if a string begins or ends with another string == {{{ #!python |
Line 67: | Line 112: |
starts_with_abc = True if my string.endswith("def") |
starts_with_abc = True if my string.endswith("def"): |
Line 70: | Line 115: |
#how to catch exceptions grades = ['A', 'A-', 'B', 'C'] try: grades.index("F") except ValueError, inst: #print out error info print inst.args # Catching multiple exceptions in Python. |
}}} == How to catch exceptions == {{{ #!python grades = ['A', 'A-', 'B', 'C'] try: grades.index("F") except ValueError, inst: # Print the error information print inst.args }}} == Catching multiple exceptions == {{{ #!python |
Line 85: | Line 137: |
# 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 "=" |
}}} == 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 '=' == {{{ #!python |
Line 91: | Line 150: |
fin = file('file1', 'r') fout = file(fin.name + '.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") |
fin = file('file1', 'r') fout = file(fin.name + '.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") |
Line 98: | Line 157: |
fout.close() fin.close() os.rename(fout.name, fin.name) |
fout.close() fin.close() os.rename(fout.name, fin.name) |
Line 102: | Line 161: |
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 # http://yokozar.org/blog/archives/48 |
print("can't update the file") }}} == How to make money in open source == 1. get developers 1. bzr commit 1. ??? 1. profit == How to generate pretty charts == See http://yokozar.org/blog/archives/48 {{{ #!python |
Line 113: | Line 179: |
chartTitle = "Simulated model of Wine development" # Appears at the top of the chart produced at the end |
# Appears at the top of the chart produced at the end chartTitle = "Simulated model of Wine development" |
Line 119: | Line 186: |
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 |
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 == {{{ #!python |
Line 132: | Line 204: |
or | # or |
Line 137: | Line 209: |
#notify-osd |
}}} == notify-osd == {{{ #!python |
Line 141: | Line 216: |
pynotify.init('someName') |
|
Line 144: | Line 221: |
}}} | |
Line 147: | Line 225: |
# get the output of a command | == Get the output of a command == {{{ #!python |
Line 153: | Line 234: |
#open a link in a web browser |
}}} == Open a link in a web browser == {{{ #!python |
Line 160: | Line 244: |
#get the text for an html page from the web |
}}} == Get the text for an HTML page from the web == {{{ #!python |
Line 165: | Line 253: |
#create a stock cancel button and pack it into the vbox cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL) cancel_button.show() cancel_button.connect("clicked", on_cancel_clicked) # Parse XML file |
}}} == Create a stock cancel button and pack it into the vbox == {{{ #!python cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL) cancel_button.show() cancel_button.connect("clicked", on_cancel_clicked) }}} == Parse XML file == {{{ #!python |
Line 183: | Line 278: |
# search a file for a pattern and do something with every match |
}}} == Search a text for a pattern and do something with every match == {{{ #!python |
Line 188: | Line 286: |
for m in re.finditer('bug (\d+) blabla', text): print 'bug number': m.match(1) # download an URL and process it line by line |
text = "bug 1: first bug\nbug 2: duplicate of bug 1\nbug 999: the last bug" for m in re.finditer('bug (\d+):', text): print 'bug number: '+ m.group(1) }}} == Download an URL and process it line by line == {{{ #!python |
Line 195: | Line 297: |
print line # grep all versioned files in a Bazaar tree |
print line }}} == Grep all versioned files in a Bazaar tree == {{{ |
Line 202: | Line 305: |
}}} == Grep all versioned files in a Git tree == {{{ |
|
Line 203: | Line 311: |
Creating a Gtk+ TreeView: |
}}} == Creating a Gtk+ TreeView == {{{ #!python |
Line 235: | Line 344: |
#make a new ListStore when columns are calculated at runtim |
}}} == Make a new ListStore when columns are calculated at runtime == {{{ #!python |
Line 238: | Line 351: |
self.list_store = gtk.ListStore( *[gobject.TYPE_STRING for i in range(col_count)]) #Put data into desktop CouchDB: |
self.list_store = gtk.ListStore( *[gobject.TYPE_STRING for i in range(col_count)]) }}} == Put data into desktop CouchDB == {{{ #!python |
Line 248: | Line 364: |
record = CouchRecord({"a": 1, "b": 2}, record_type="http://recordtypeurl", record_id=XXX) | record = CouchRecord( {"a": 1, "b": 2}, record_type="http://recordtypeurl", record_id=XXX) |
Line 250: | Line 368: |
# Call a desktop CouchDB view: |
}}} == Call a desktop CouchDB view == {{{ #!python |
Line 257: | Line 380: |
#Creating a new Tomboy note |
}}} == Listen to changes in CouchDB == {{{ #!python from desktopcouch.records.server import CouchDatabase # we are going to be listening to the changes def changes_cb(seq=None, id=None, changes=None): print seq print id print changes db = CouchDatabase("fosdem") # better, use glib main loop or twisted task! while True: db.report_changes(changes_cb) time.sleep(30) }}} == Add attachments in CouchDB == {{{ #!python from desktopcouch.records.record import Record from desktopcouch.records.server import CouchDatabase db = CouchDatabase("fosdem") record = Record(record_type="url") record.attach("/path/to/image/avatar.jpg", "blob", "image/jpg") db.put_record(record) }}} == Creating a new Tomboy note == {{{ #!python |
Line 260: | Line 420: |
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.DisplayNote(n) tomboy.SetNoteContents(n, text) #Set Pidgin status |
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.DisplayNote(n) tomboy.SetNoteContents(n, text) }}} == Set Pidgin status == {{{ #!python |
Line 270: | Line 435: |
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) purple.PurpleSavedstatusActivate(status) #How to embed a WebKit renderer in an application: |
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) purple.PurpleSavedstatusActivate(status) }}} == Embed a WebKit renderer in an application == {{{ #!python |
Line 291: | Line 461: |
# Put an icon in a Gtk+ text entry |
}}} == Put an icon in a Gtk+ text entry == {{{ |
Line 298: | Line 472: |
# Display a progress bar in a Gtk+ entry |
}}} == Display a progress bar in a Gtk+ entry == {{{ |
Line 303: | Line 480: |
#Get Gtk+ theme colors |
}}} == Get Gtk+ theme colors == {{{ #!python |
Line 306: | Line 487: |
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 |
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 == {{{ #!python |
Line 328: | Line 513: |
# A Gtk+ label that supports text wrapping with fluid reflow |
}}} == A Gtk+ label that supports text wrapping with fluid reflow == {{{ #!python |
Line 334: | Line 523: |
def __init__(self, markup = None, text = None): gtk.Frame.__init__(self) self.set_shadow_type(gtk.SHADOW_NONE) self.pango_layout = self.create_pango_layout(text or "") if markup: self.pango_layout.set_markup(markup) self.pango_layout.set_wrap(pango.WRAP_WORD_CHAR) ev = gtk.EventBox() ev.set_visible_window(False) self.add(ev) 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) |
def __init__(self, markup = None, text = None): gtk.Frame.__init__(self) self.set_shadow_type(gtk.SHADOW_NONE) self.pango_layout = self.create_pango_layout(text or "") if markup: self.pango_layout.set_markup(markup) self.pango_layout.set_wrap(pango.WRAP_WORD_CHAR) ev = gtk.EventBox() ev.set_visible_window(False) self.add(ev) 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) |
Line 365: | Line 554: |
# Build a Gtk+ toolbar with UIManager |
}}} == Build a Gtk+ toolbar with UIManager == {{{ #!python |
Line 368: | Line 562: |
print "Action performed!" | print "Action performed!" |
Line 372: | Line 566: |
("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), ]) |
("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), ]) |
Line 392: | Line 586: |
# what to do instead of using eval() [this is safe security-wise] |
}}} == What to do instead of using eval() [this is safe security-wise] == {{{ #!python |
Line 397: | Line 594: |
# How to use doctests well. # Don't. # getting your packages updated # import os # os.system('evolution mailto:seb128@debian.org?subject=hi') |
}}} == How to use doctests well == Don't. == Getting your packages updated == {{{ #!python import os os.system('evolution mailto:seb128@debian.org?subject=hi') |
Line 407: | Line 609: |
# How to set up a threaded GTK+ app |
}}} == How to set up a threaded GTK+ app == {{{ #!python |
Line 429: | Line 635: |
self.show() | self.show() |
Line 443: | Line 649: |
#set the text on a pygtk widget in a Quickly app |
}}} == Set the text on a pygtk widget in a Quickly app == {{{ #!python |
Line 448: | Line 657: |
#get the text for a pygtk widdget in a Quickly app |
}}} == Get the text for a pygtk widdget in a Quickly app == {{{ #!python |
Line 451: | Line 665: |
#download an image from the web and save it |
}}} == Download an image from the web and save it == {{{ #!python |
Line 458: | Line 676: |
#download a large file using a read buffer, saves memory |
}}} == Download a large file using a read buffer, saves memory == {{{ #!python |
Line 464: | Line 685: |
while 1: | while True: |
Line 470: | Line 691: |
# Still dealing with large files # Compute the md5sum of a file without loading it all in memory |
}}} == Compute the md5sum of a file without loading it all in memory == Still dealing with large files. {{{ #!python import hashlib |
Line 474: | Line 701: |
digest = md5.new() while 1: |
digest = hashlib.md5() while True: |
Line 482: | Line 709: |
#how to use couchgrid and change the label of the column |
}}} == Use couchgrid and change the label of the column == {{{ #!python |
Line 493: | Line 722: |
Line 496: | Line 724: |
self.couchgrid.editable=True | self.couchgrid.editable=True |
Line 500: | Line 727: |
Line 503: | Line 729: |
#how to get stuff from a desktop couch db |
}}} == Get stuff from a desktop couch db == {{{ #!python |
Line 510: | Line 739: |
record_type="record type" | record_type="record type" |
Line 514: | Line 743: |
x="" for r in results: x+=r.value["key"]+" " # PDB tip |
x=" ".join(r.value["key"] for r in results) }}} == PDB tip == {{{ |
Line 520: | Line 750: |
# Parsing a line-based text file with separators # Not that advanced, but I seem to have to write this all the time. |
}}} == Parse a line-based text file with separators == Not that advanced, but I seem to have to write this all the time. {{{ #!python |
Line 528: | Line 761: |
#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") test_window.set_default_size(200,75) test_window.show() # reading a bunch of stuff out of a function |
}}} == Create a pygtk window on the fly == {{{ #!python test_window = gtk.Window(gtk.WINDOW_TOPLEVEL) test_window.connect("destroy", gtk.main_quit) test_window.set_title("my title") test_window.set_default_size(200,75) test_window.show() }}} == Reading a bunch of stuff out of a function == {{{ #!python |
Line 540: | Line 780: |
total.append(chunk) | total.append(chunk) |
Line 542: | Line 782: |
# Transposing a list of lists. |
}}} == Transposing a list of lists == {{{ |
Line 546: | Line 787: |
# easy (if not efficient) sorted merging of two lists (works also for dicts) |
}}} == Easy sorted merging of two lists (works also for dicts) == Not exactly efficient. {{{ #!python |
Line 551: | Line 796: |
for item in sorted(set(l1).union(l2)): # do whatever #add a message indicator |
for item in sorted(set(l1)|set(l2)): do_a_thing(item) }}} == Add a message indicator == {{{ #!python |
Line 574: | Line 822: |
# post a microblog message using gwibber from karmic |
}}} == Post a microblog message using Gwibber == === In Karmic === {{{ #!python |
Line 588: | Line 841: |
"source": "lolz", | "source": "my app name", |
Line 594: | Line 847: |
# post a microblog message using gwibber in lucid (not yet uploaded) | }}} === In Lucid (not yet uploaded) === {{{ #!python |
Line 600: | Line 857: |
# parse command line arguments |
}}} == Parse command line arguments == {{{ #!python |
Line 611: | Line 869: |
print 'force enabled' | print 'force enabled' |
Line 614: | Line 872: |
outfile = open(opts.outfile, 'w') | outfile = open(opts.outfile, 'w') |
Line 616: | Line 874: |
outfile = sys.stdout # SQLite |
outfile = sys.stdout }}} == SQLite == {{{ #!python |
Line 631: | Line 892: |
# Apply file rights from src to dest |
}}} == Apply file rights from src to dest == {{{ #!python |
Line 638: | Line 901: |
#translations using gettext |
}}} == Translations using gettext == {{{ #!python |
Line 644: | Line 910: |
#print hello world(it needs to be translated first though) | # Print 'hello' (it needs to be translated first though). |
Line 646: | Line 912: |
# A really simple unittest module. |
}}} == A really simple unittest module. == {{{ #!python |
Line 657: | Line 926: |
Line 661: | Line 930: |
Line 664: | Line 933: |
# 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 |
}}} 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 == {{{ #!python |
Line 674: | Line 947: |
print 'someone already has this name' exit() #open a file from a dialog dialog = gtk.FileChooserDialog("Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN, |
print 'someone already has this name' exit() }}} == Open a file from a dialog == {{{ #!python dialog = gtk.FileChooserDialog( "Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN, |
Line 681: | Line 960: |
if dialog.run() == gtk.RESPONSE_OK: | if dialog.run() == gtk.RESPONSE_OK: |
Line 684: | Line 963: |
print fn dialog.destroy() }}} |
print fn dialog.destroy() }}} == Create a TextEntry with auto-completion in PyGTK == {{{ #!python import pygtk import gtk import gobject # contains the data for autocomplition, can be dynamic options = ("Friends", "Family", "Person", "Test") def entry_changed (editable, *user_data): comp = user_data[0] text = editable.get_text() matches = [] if text: for current_option in options: if current_option.startswith(text): matches.append(current_option) model = comp.get_model() model.clear() for match in matches: model.append([match]) win = gtk.Window() entry = gtk.Entry() completion = gtk.EntryCompletion() entry.set_completion(completion) liststore = gtk.ListStore(gobject.TYPE_STRING) completion.set_model(liststore) completion.set_text_column(0) win.add(entry) entry.connect("changed", entry_changed, completion) win.connect("delete-event", gtk.main_quit) win.show_all() gtk.main() }}} == Check if script runs as root == {{{ #!python import os, sys if os.geteuid() != 0: print 'You must be root to run this script' sys.exit(0) }}} |
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
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)