Snippets
Revision 8 as of 2009-11-26 19:37:08
Clear message
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
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
9
10
11 #how to test if a string begins or ends with another string
12 my_string = "abcdef"
13 if my_string.startswith("abc"):
14 starts_with_abc = True
15 if my string.endswith("def"):
16 ends_with_def = True
17
18 #how to catch exceptions
19 grades = ['A', 'A-', 'B', 'C']
20 try:
21 grades.index("F")
22 except ValueError, inst:
23 #print out error info
24 print inst.args
25
26 # Catching multiple exceptions in Python.
27 try:
28 "do something"
29 except (ExceptionOne, ExceptionTwo):
30 # Note: The parens are important.
31 "handle the exception"
32
33 # Convert a file url to a file path in a shell script
34 deurledfile = `python -c 'import sys, urlparse, urllib; print urllib.unquote(urlparse.urlparse(sys.argv[1]).path)' $1`
35
36 # change/update value in a file with "="
37 try:
38 fin = file('file1', 'r')
39 fout = file(fin.name + '.new', 'w')
40 for line in fin:
41 fields = line.split('=') # Separate variable from value
42 if "keyname" == fields[0].strip():
43 line = "%s='%s'\n" % (fields[0], "newvalue")
44 fout.write(line)
45 fout.close()
46 fin.close()
47 os.rename(fout.name, fin.name)
48 except (OSError, IOError), e:
49 print("can't update the file")
50
51 # how to make money in open source
52 1. get developers
53 2. bzr commit
54 3.
55 4. profit
56
57 # how to generate pretty charts
58 # http://yokozar.org/blog/archives/48
59 import cairoplot
60
61 # Appears at the top of the chart produced at the end
62 chartTitle = "Simulated model of Wine development"
63 chartData = {"Working Apps" : [], "Happy Users" : []}
64 for x in xrange(100):
65 chartData["Working Apps"].append(float(x))
66 chartData["Happy Users"].append(float(x))
67 x_labels = [
68 "Project start", "25% bugs solved", "50% bugs solved",
69 "75% bugs solved", "All bugs solved"]
70 y_labels = ["0%", "25%", "50%", "75%", "100%"]
71 cairoplot.dot_line_plot(
72 "wine-model-results", chartData, 600, 600, x_labels = x_labels,
73 y_labels = y_labels, axis = True, grid = True,
74 x_title = chartTitle, y_title = "Percentage", series_legend=True )
75
76
77
78 #how to play a sound
79 import gst
80 player = gst.element_factory_make("playbin", "player")
81 player.set_property("uri", "file:///usr/share/sounds/ubuntu/stereo/bell.ogg")
82 player.set_state(gst.STATE_PLAYING)
83 # or
84 import pygame
85 pygame.mixer.init()
86 pygame.mixer.music.load("music.ogg")
87 pygame.mixer.music.play()
88
89
90 #notify-osd
91 import pynotify
92
93 n = pynotify.Notification("message name", "message", "icon")
94 n.show()
95
96 # more notify-osd stuff
97
98 # get the output of a command
99 import subprocess
100
101 date = subprocess.Popen(['date', '+%c'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
102 (out, err) = date.communicate()
103 print 'exit code', date.returncode
104
105
106 #open a link in a web browser
107 import webbrowser
108
109 url = 'http://google.com/'
110 webbrowser.open_new(url)
111
112 #get the text for an html page from the web
113 import urllib
114 f = urllib.urlopen(day_url)
115 html = f.read()
116
117 #create a stock cancel button and pack it into the vbox
118 cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
119 cancel_button.show()
120 cancel_button.connect("clicked", on_cancel_clicked)
121
122
123 # Parse XML file
124 import xml.dom
125 try:
126 dom = xml.dom.minidom.parseString(xml_content)
127 except ExpatError, e:
128 print >> sys.stderr, 'Invalid XML:', e
129
130 for p_node in dom.getElementsByTagName('p'):
131 print 'class of paragraph', p.attributes['class']
132 for child in p_node.childNodes:
133 print 'XML child node:', child
134
135
136 # search a file for a pattern and do something with every match
137 import re
138 for m in re.finditer('bug (\d+) blabla', text):
139 print 'bug number': m.match(1)
140
141
142 # download an URL and process it line by line
143 import urllib
144 for line in urllib.open('http://foo'):
145 print line
146
147
148 # grep all versioned files in a Bazaar tree
149 # Best command ever
150 bzr ls -VR --kind=file --null | xargs -0 grep -In <REGEX>
151 git grep <REGEX>
152
153
154 # Creating a Gtk+ TreeView:
155
156 # Instantiate the tree store and specify the data types
157 store = gtk.TreeStore(str, gtk.gdk.Pixbuf, int, bool)
158
159 # Create a TreeViewColumn
160 col = gtk.TreeViewColumn("File")
161 # Create a column cell to display text
162 col_cell_text = gtk.CellRendererText()
163 # Create a column cell to display an image
164 col_cell_img = gtk.CellRendererPixbuf()
165 # Add the cells to the column
166 col.pack_start(col_cell_img, False)
167 col.pack_start(col_cell_text, True)
168 # Bind the text cell to column 0 of the tree's model
169 col.add_attribute(col_cell_text, "text", 0)
170 # Bind the image cell to column 1 of the tree's model
171 col.add_attribute(col_cell_img, "pixbuf", 1)
172
173 col2 = gtk.TreeViewColumn("Size")
174 col2_cell_text = gtk.CellRendererText()
175 col2.pack_start(col2_cell_text)
176 col2.add_attribute(col2_cell_text, "text", 2)
177
178 # Create the TreeView and set our data store as the model
179 tree = gtk.TreeView(store)
180 # Append the columns to the TreeView
181 tree.append_column(col)
182 tree.append_column(col2)
183
184 #make a new ListStore when columns are calculated at runtim
185 col_count = 100
186 self.list_store = gtk.ListStore(
187 *[gobject.TYPE_STRING for i in range(col_count)])
188
189
190 #Put data into desktop CouchDB:
191
192 from desktopcouch.records.server import CouchDatabase
193 from desktopcouch.records.record import Record as CouchRecord
194
195 db = CouchDatabase("dbname", create=True)
196 record = CouchRecord(
197 {"a": 1, "b": 2}, record_type="http://recordtypeurl",
198 record_id=XXX)
199 db.put_record(record)
200
201 # Call a desktop CouchDB view:
202
203 view = """function(doc) { if (doc) emit(doc._id, doc); }"""
204 if not self.messages.view_exists("myview", "myapp"):
205 self.messages.add_view("myview", view, None, "myapp")
206 result = self.messages.execute_view("myview", "myapp")
207
208 #Creating a new Tomboy note
209 def create_tomboy_note(text):
210 bus = dbus.SessionBus()
211 obj = bus.get_object("org.gnome.Tomboy", "/org/gnome/Tomboy/RemoteControl")
212 tomboy = dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")
213
214 n = tomboy.CreateNote()
215 tomboy.DisplayNote(n)
216 tomboy.SetNoteContents(n, text)
217
218 #Set Pidgin status
219 def set_pidgin_status_text(message):
220 bus = dbus.SessionBus()
221 obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
222 purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
223
224 current = purple.PurpleSavedstatusGetType(purple.PurpleSavedstatusGetCurrent())
225 status = purple.PurpleSavedstatusNew("", current)
226 purple.PurpleSavedstatusSetMessage(status, message)
227 purple.PurpleSavedstatusActivate(status)
228
229 #How to embed a WebKit renderer in an application:
230 import gtk, webkit
231 gtk.gdk.threads_init()
232
233 window = gtk.Window()
234 window.connect("destroy", gtk.main_quit)
235 web = webkit.WebView()
236 web.open("http://ubuntu.com")
237
238 window.add(web)
239 window.show_all()
240 gtk.main()
241
242 # Put an icon in a Gtk+ text entry
243 GtkWidget *entry = gtk_entry_new();
244 gtk_entry_set_icon_from_stock(
245 GTK_ENTRY(entry), // specify which entry widget
246 GTK_ENTRY_ICON_SECONDARY, // put the icon at the end
247 GTK_STOCK_ABOUT); // make it display the "about" icon
248
249 # Display a progress bar in a Gtk+ entry
250 GtkWidget *entry = gtk_entry_new();
251 gtk_entry_set_text(GTK_ENTRY(entry), "This is a test");
252 gtk_entry_set_progress_fraction(GTK_ENTRY(entry), 0.5);
253
254 #Get Gtk+ theme colors
255 def get_theme_colors(w):
256 d = {}
257
258 for i in ["base", "text", "fg", "bg"]:
259 d[i] = Color.from_gtk_color(
260 getattr(w.get_style(), i)[gtk.STATE_NORMAL].to_string())
261
262 d["%s_selected" % i] = Color.from_gtk_color(
263 getattr(w.get_style(), i)[gtk.STATE_SELECTED].to_string())
264
265 return d
266
267 # Draw a rounded rectangle in Cairo
268 c = self.window.cairo_create()
269 x,y,w,h = w.allocation # x, y, width, height
270
271 c.move_to(x+r,y)
272 c.line_to(x+w-r,y); c.curve_to(x+w,y,x+w,y,x+w,y+r)
273 c.line_to(x+w,y+h-r); c.curve_to(x+w,y+h,x+w,y+h,x+w-r,y+h)
274 c.line_to(x+r,y+h); c.curve_to(x,y+h,x,y+h,x,y+h-r)
275 c.line_to(x,y+r); c.curve_to(x,y,x,y,x+r,y)
276 c.close_path()
277 c.fill()
278
279 # A Gtk+ label that supports text wrapping with fluid reflow
280
281 import gtk, pango, gobject
282
283 class WrapLabel(gtk.Frame):
284 def __init__(self, markup = None, text = None):
285 gtk.Frame.__init__(self)
286 self.set_shadow_type(gtk.SHADOW_NONE)
287
288 self.pango_layout = self.create_pango_layout(text or "")
289 if markup: self.pango_layout.set_markup(markup)
290 self.pango_layout.set_wrap(pango.WRAP_WORD_CHAR)
291
292 ev = gtk.EventBox()
293 ev.set_visible_window(False)
294 self.add(ev)
295
296 def do_expose_event(self, event):
297 gtk.Frame.do_expose_event(self, event)
298 self.set_size_request(-1, (self.pango_layout.get_size()[1] // pango.SCALE + 10))
299
300 x,y,w,h = self.allocation
301 gc = self.window.new_gc()
302 self.pango_layout.set_width(w * pango.SCALE)
303 self.window.draw_layout(gc, x, y, self.pango_layout)
304
305 gobject.type_register(WrapLabel)
306
307 w = gtk.Window()
308 w.connect("destroy", gtk.main_quit)
309
310 label = WrapLabel("This is a test")
311 w.add(label)
312
313 w.show_all()
314 gtk.main()
315
316 # Build a Gtk+ toolbar with UIManager
317 def on_action(action):
318 print "Action performed!"
319
320 actions = gtk.ActionGroup("Actions")
321 actions.add_actions([
322 ("bold", gtk.STOCK_BOLD, "_Bold", "<ctrl>B", None, on_action),
323 ("italic", gtk.STOCK_ITALIC, "_Italic", "<ctrl>I", None, on_action),
324 ("underline", gtk.STOCK_UNDERLINE, "_Underline", "<ctrl>U", None, on_action),
325 ])
326
327 ui_def = """
328 <toolbar name="toolbar_format">
329 <toolitem action="bold" />
330 <toolitem action="italic" />
331 <toolitem action="underline" />
332 </toolbar>
333 """
334
335 ui = gtk.UIManager()
336 ui.insert_action_group(actions)
337 ui.add_ui_from_string(ui_def)
338
339 vb = gtk.VBox()
340 vb.pack_start(ui.get_widget("/toolbar_format"), False)
341 vb.pack_start(editor, True)
342
343
344 # what to do instead of using eval() [this is safe security-wise]
345 import ast
346 ast.literal_eval ('[1,2,3,(4,5,6)]')
347
348 # How to use doctests well.
349 # Don't.
350
351 # getting your packages updated
352 # import os
353 # os.system('evolution mailto:seb128@debian.org?subject=hi')
354 # actually, he'll notice by himself.
355 from time import sleep
356 sleep (8 * 60 * 60) # go to bed
357
358 # How to set up a threaded GTK+ app
359 import pygtk
360 pygtk.require('2.0')
361 import gobject
362 import gtk
363
364 from threading import Thread
365
366
367 class Window(gtk.Window):
368 '''GtkWindow wrapper'''
369
370 def __init__(self):
371 gtk.Window.__init__(self)
372 self.set_title("Threaded GTK+ Sample")
373 self.set_default_size(320, 240)
374 Thread(target=self.timeout_thread).start()
375
376 def timeout_thread():
377 '''Threaded timeout demo'''
378 gtk.gdk.threads_enter()
379 self.show()
380 gtk.gdk_threads_leave()
381
382 if __name__ == "__main__":
383 gobject.threads_init()
384 gtk.gdk.threads_init()
385 try:
386 win = Window()
387 win.show()
388 gtk.gdk.threads_enter()
389 gtk.main()
390 gtk.gdk.threads_leave()
391 except KeyboardInterrupt:
392 gtk.main_quit()
393
394
395
396 #set the text on a pygtk widget in a Quickly app
397 widge = self.builder.get_object("object_name").set_text(my_string)
398
399 #get the text for a pygtk widdget in a Quickly app
400 self.builder.get_object("object_name").get_text(my_string)
401
402 #download an image from the web and save it
403 import urllib
404 img_stream = urllib.urlopen(url)
405 img_file = open(fname,'w')
406 img_file.write(img_stream.read())
407 del img_file
408
409
410 #download a large file using a read buffer, saves memory
411 import urllib
412 img_stream = urllib.urlopen(url)
413 img_file = open(fname,'w')
414 while 1:
415 buf = img_stream.read(4096)
416 if buf == "":
417 break
418 img_file.write(buf)
419 del img_file
420
421 # Still dealing with large files
422 # Compute the md5sum of a file without loading it all in memory
423 f = open(filepath)
424 digest = md5.new()
425 while 1:
426 buf = f.read(4096)
427 if buf == "":
428 break
429 digest.update(buf)
430 f.close()
431 print digest.hexdigest()
432
433
434
435 #how to use couchgrid and change the label of the column
436 from desktopcouch.records.couchgrid import CouchGrid
437 db="db name"
438 record_type="record type"
439 #the keys field is for to label the column and give a discription of what is in that column
440 keys=["key","another key"]
441 self.couchgrid=CouchGrid(db,record_type=record_type,keys=keys)
442 self.couchgrid.show()
443
444 #put the couchgrid into a vbox
445 self.builder.get_object("vbox1").pack_end(self.couchgrid)
446 self.couchgrid.editable=True
447
448 #change the name of the couchgrid column
449 couchgrid.get_column(0).set_title("some name")
450
451 #make the couchgrid column name dissapear
452 self.couchgrid.set_headers_visible (False)
453
454 #how to get stuff from a desktop couch db
455
456 from desktopcouch.records.server import CouchDatabase
457 from desktopcouch.records.record import Record
458
459 __couchdb = CouchDatabase("db name",create=True)
460 record_type="record type"
461 results = __couchdb.get_records(record_type=record_type,create_view=True)
462
463 #this takes the output of results and puts it into a string x
464 x=""
465 for r in results:
466 x+=r.value["key"]+" "
467
468 # PDB tip
469 pp locals()
470
471
472 # Parsing a line-based text file with separators
473 # Not that advanced, but I seem to have to write this all the time.
474
475 def parse_line(lines, separator):
476 for line in lines:
477 yield [token.strip() for token in line.split(separator)]
478
479 #create a pygtk window on the fly
480 test_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
481 test_window.connect("destroy", gtk.main_quit)
482 test_window.set_title("my title")
483 test_window.set_default_size(200,75)
484 test_window.show()
485
486
487 # reading a bunch of stuff out of a function
488 total = []
489 for chunk in iter(lambda: file.read(4096), ''):
490 total.append(chunk)
491 result = ''.join(total)
492
493
494 # Transposing a list of lists.
495 zip(*list_of_lists)
496
497
498 # easy (if not efficient) sorted merging of two lists (works also for dicts)
499 l1 = [4, 5, 6]
500 l2 = [4, 6, 7]
501 for item in sorted(set(l1).union(l2)):
502 do_a_thing(item)
503
504
505 #add a message indicator
506 import indicate, time
507
508 def display(indicator):
509 print "Ah, my indicator has been displayed"
510
511 def server_display(server):
512 print "Ah, my server has been displayed"
513
514 server = indicate.indicate_server_ref_default()
515 server.set_type("message.im")
516 server.set_desktop_file("/usr/share/applications/empathy.desktop")
517 server.connect("server-display", server_display)
518 indicator = indicate.Indicator()
519 indicator.set_property("subtype", "im")
520 indicator.set_property("sender", "IM Client Test")
521 indicator.set_property_time("time", time.time())
522 indicator.show()
523 indicator.connect("user-display", display)
524
525
526 # post a microblog message using gwibber from karmic
527 bus = dbus.SessionBus()
528 db_mb_obj = bus.get_object("com.Gwibber", "/com/gwibber/Microblog")
529 microblog = dbus.Interface(db_mb_obj, "com.Gwibber")
530 import gwibber, gwibber.config
531
532 accounts = gwibber.config.Accounts()
533 args = ["This is a test message"]
534 for account in accounts:
535 if account["send_enabled"]:
536 acctid = account["id"]
537 microblog.operation({
538 "source": "lolz",
539 "id": "send-%s-%s" % (acctid, time.time()),
540 "accountid": acctid,
541 "args": args,
542 "opname": "send",
543 })
544
545
546 # post a microblog message using gwibber in lucid (not yet uploaded)
547 import gwibber.utils
548 foo = gwibber.utils.GwibberPublic()
549 foo.post("This is a test message")
550
551
552
553
554 # parse command line arguments
555 import optparse
556 op = optparse.OptionParser('%prog [options] inputfile')
557 op.add_option('-f', '--force', action='store_true', dest='force', default=False, help='Delete my files without asking')
558 op.add_option('-o', '--output-file', dest='outfile', help='Output file path; if not given, output to stdout')
559 (opts, args) = op.parse_args()
560 if opts.force:
561 print 'force enabled'
562 input_file = args[0]
563 if opts.outfile:
564 outfile = open(opts.outfile, 'w')
565 else:
566 outfile = sys.stdout
567
568
569 # SQLite
570 import sqlite3 as dbapi2
571 db = dbapi2.connect('mydb.sqlite')
572
573 cur1 = db.cursor()
574 cur1.execute('CREATE TABLE friends (name VARCHAR(255), phone int)')
575 cur1.commit()
576
577 cur1 = db.cursor()
578 cur1.execute('SELECT phone FROM friends WHERE name = ?', ['Fred']) # does proper quoting
579 for (phone) in cur1:
580 print 'Fred has telephone number', phone
581
582
583 # Apply file rights from src to dest
584 import os, stat
585 st = os.stat(src_file_name)
586 mode = stat.S_IMODE(st.st_mode)
587 os.chmod(dest_file_name, mode)
588
589
590
591 #translations using gettext
592 import gettext
593
594 #print hello world(it needs to be translated first though)
595 print gettext.gettext("hello")
596
597
598 # A really simple unittest module.
599
600 import unittest
601
602 class TestThing(unittest.TestCase):
603
604 def setUp(self):
605 super(unittest.TestCase, self).setUp()
606 self.data = [2, 3, 5]
607
608 def test_list_reversal(self):
609 backwards = reversed(self.data)
610 self.assertEqual([5, 3, 2], backwards)
611
612 def tearDown(self):
613 del self.data
614
615 # Note that you wouldn't really use setUp and tearDown for something this
616 # simple. Use them when you have something fairly complicated to set up.
617
618
619
620 # Look for a program that is already registered over dbus
621 import dbus
622 session_bus = dbus.SessionBus()
623 if session_bus.request_name ('net.soft.name') != 1:
624 print 'someone already has this name'
625 exit()
626
627 #open a file from a dialog
628 dialog = gtk.FileChooserDialog("Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN,
629 (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
630
631 if dialog.run() == gtk.RESPONSE_OK:
632 fn = dialog.get_filename()
633 if os.path.exists(fn):
634 print fn
635 dialog.destroy()