Snippets

Revision 4 as of 2009-11-20 22:29:36

Clear message

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