Snippets
Differences between revisions 8 and 9
19373
Comment: Start formatting
|
20771
Ultimate formatting power.
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
Line 93: | Line 94: |
{{{ #!python |
== Generators / Iteration == {{{ #!python |
Line 104: | Line 105: |
#how to test if a string begins or ends with another string |
}}} == How to test if a string begins or ends with another string == {{{ #!python |
Line 112: | Line 116: |
#how to catch exceptions |
}}} == How to catch exceptions == {{{ #!python |
Line 118: | Line 126: |
#print out error info | # Print the error information |
Line 120: | Line 128: |
# Catching multiple exceptions in Python. |
}}} == Catching multiple exceptions == {{{ #!python |
Line 127: | Line 138: |
# Convert a file url to a file path in a shell script |
}}} == Convert a file:/// URL to a file path in a shell script == {{{ |
Line 130: | Line 144: |
# change/update value in a file with "=" |
}}} == Change / update value in a file with '=' == {{{ #!python |
Line 145: | Line 163: |
# 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 |
}}} == 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 170: | Line 195: |
#how to play a sound |
}}} == How to play a sound == {{{ #!python |
Line 183: | Line 210: |
#notify-osd |
}}} == notify-osd == {{{ #!python |
Line 190: | Line 220: |
}}} | |
Line 193: | Line 224: |
# get the output of a command | == Get the output of a command == {{{ #!python |
Line 199: | Line 233: |
#open a link in a web browser |
}}} == Open a link in a web browser == {{{ #!python |
Line 206: | Line 243: |
#get the text for an html page from the web |
}}} == Get the text for an HTML page from the web == {{{ #!python |
Line 211: | Line 252: |
#create a stock cancel button and pack it into the vbox |
}}} == Create a stock cancel button and pack it into the vbox == {{{ #!python |
Line 216: | Line 261: |
# Parse XML file |
}}} == Parse XML file == {{{ #!python |
Line 229: | Line 277: |
# search a file for a pattern and do something with every match |
}}} == Search a file for a pattern and do something with every match == {{{ #!python |
Line 235: | Line 287: |
# download an URL and process it line by line |
}}} == Download an URL and process it line by line == {{{ #!python |
Line 241: | Line 296: |
# grep all versioned files in a Bazaar tree |
}}} == Grep all versioned files in a Bazaar tree == {{{ |
Line 246: | Line 303: |
}}} == Grep all versioned files in a Git tree == {{{ |
|
Line 247: | Line 309: |
# Creating a Gtk+ TreeView: |
}}} == Creating a Gtk+ TreeView == {{{ #!python |
Line 278: | Line 342: |
#make a new ListStore when columns are calculated at runtim |
}}} == Make a new ListStore when columns are calculated at runtime == {{{ #!python |
Line 283: | Line 351: |
#Put data into desktop CouchDB: |
}}} == Put data into desktop CouchDB == {{{ #!python |
Line 295: | Line 366: |
# Call a desktop CouchDB view: |
}}} == Call a desktop CouchDB view == {{{ #!python |
Line 302: | Line 378: |
#Creating a new Tomboy note |
}}} == Creating a new Tomboy note == {{{ #!python |
Line 312: | Line 392: |
#Set Pidgin status |
}}} == Set Pidgin status == {{{ #!python |
Line 323: | Line 408: |
#How to embed a WebKit renderer in an application: |
}}} == Embed a WebKit renderer in an application == {{{ #!python |
Line 336: | Line 426: |
# Put an icon in a Gtk+ text entry |
}}} == Put an icon in a Gtk+ text entry == {{{ |
Line 343: | Line 437: |
# Display a progress bar in a Gtk+ entry |
}}} == Display a progress bar in a Gtk+ entry == {{{ |
Line 348: | Line 445: |
#Get Gtk+ theme colors |
}}} == Get Gtk+ theme colors == {{{ #!python |
Line 361: | Line 462: |
# Draw a rounded rectangle in Cairo |
}}} == Draw a rounded rectangle in Cairo == {{{ #!python |
Line 373: | Line 478: |
# A Gtk+ label that supports text wrapping with fluid reflow |
}}} == A Gtk+ label that supports text wrapping with fluid reflow == {{{ #!python |
Line 410: | Line 519: |
# Build a Gtk+ toolbar with UIManager |
}}} == Build a Gtk+ toolbar with UIManager == {{{ #!python |
Line 437: | Line 551: |
# 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 442: | Line 559: |
# 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 452: | Line 574: |
# How to set up a threaded GTK+ app |
}}} == How to set up a threaded GTK+ app == {{{ #!python |
Line 488: | Line 614: |
#set the text on a pygtk widget in a Quickly app |
}}} == Set the text on a pygtk widget in a Quickly app == {{{ #!python |
Line 493: | Line 622: |
#get the text for a pygtk widdget in a Quickly app |
}}} == Get the text for a pygtk widdget in a Quickly app == {{{ #!python |
Line 496: | Line 630: |
#download an image from the web and save it |
}}} == Download an image from the web and save it == {{{ #!python |
Line 503: | Line 641: |
#download a large file using a read buffer, saves memory |
}}} == Download a large file using a read buffer, saves memory == {{{ #!python |
Line 515: | Line 656: |
# 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 |
Line 527: | Line 673: |
#how to use couchgrid and change the label of the column |
}}} == Use couchgrid and change the label of the column == {{{ #!python |
Line 538: | Line 686: |
Line 542: | Line 689: |
Line 545: | Line 691: |
Line 548: | Line 693: |
#how to get stuff from a desktop couch db |
}}} == Get stuff from a desktop couch db == {{{ #!python |
Line 562: | Line 710: |
# PDB tip |
}}} == PDB tip == {{{ |
Line 565: | Line 716: |
# 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 573: | Line 727: |
#create a pygtk window on the fly |
}}} == Create a pygtk window on the fly == {{{ #!python |
Line 580: | Line 738: |
# reading a bunch of stuff out of a function |
}}} == Reading a bunch of stuff out of a function == {{{ #!python |
Line 587: | Line 748: |
# Transposing a list of lists. |
}}} == Transposing a list of lists == {{{ |
Line 591: | Line 753: |
# 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 598: | Line 764: |
#add a message indicator |
}}} == Add a message indicator == {{{ #!python |
Line 619: | Line 788: |
# post a microblog message using gwibber from karmic |
}}} == Post a microblog message using Gwibber == === In Karmic === {{{ #!python |
Line 639: | Line 813: |
# post a microblog message using gwibber in lucid (not yet uploaded) |
}}} === In Lucid (not yet uploaded) === {{{ #!python |
Line 645: | Line 823: |
# parse command line arguments |
}}} == Parse command line arguments == {{{ #!python |
Line 662: | Line 841: |
# SQLite |
}}} == SQLite == {{{ #!python |
Line 676: | Line 858: |
# Apply file rights from src to dest |
}}} == Apply file rights from src to dest == {{{ #!python |
Line 683: | Line 867: |
#translations using gettext |
}}} == Translations using gettext == {{{ #!python |
Line 689: | Line 876: |
#print hello world(it needs to be translated first though) | # Print 'hello' (it needs to be translated first though). |
Line 691: | Line 878: |
# A really simple unittest module. |
}}} == A really simple unittest module. == {{{ #!python |
Line 710: | Line 900: |
# 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 721: | Line 915: |
#open a file from a dialog dialog = gtk.FileChooserDialog("Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN, |
}}} == Open a file from a dialog == {{{ #!python dialog = gtk.FileChooserDialog( "Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN, |
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.6 or later
Python 2.5 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 file 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
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=""
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.
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": "lolz",
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
Quickly/Snippets (last edited 2011-04-09 22:52:34 by dsl-189-174-18-150-dyn)