Snippets

Write text to a file (not safe)

   1 #how to write text to a file (not safe)
   2 open('foo.txt', 'w').write('hello')

Loop a certain number of times

   1 for x in range(10):
   2     print x

Concetenate a number and a string

   1 x = 1
   2 print str(x) + " is a string"
   3 print "%s is a string" % x

Test if a string contains another string

   1 my_string = "abcdef"
   2 if "abc" in my_string:
   3     has_abc = True

Check if an item is in a list or dictionary or tuple or set

   1 my_list = [1, 2, 3, 4, 5]
   2 if 1 in my_list:
   3     has_one = True
   4 
   5 my_dict = {"a": 1, "b": 2, "c": 3}
   6 if "a" in my_dict:
   7    has_a = True

Anonymous functions (lambda)

   1 add = lambda x, y: x + y
   2 print add(3, 4) # prints "7"

Reduce

   1 from functools import reduce # remove this line on 2.x
   2 def factorial(x):
   3     return reduce(lambda accum, x: accum * x, range(1, x + 1), 1)

Non-destructive sort on key

   1 people = [ ... list of people objects ... ]
   2 people_by_age = sorted(people, key=lambda person: person.age)

Ternary expression

Python 2.5 or later

   1 # Ternary expression (i.e. "BOOLEAN ? IF_TRUE : IF_FALSE")
   2 print "a" if x == 1 else "b"

Python 2.4 or earlier

   1 print (x == 1) and "a" or "b"

Printing stuff nicely

   1 from pprint import pprint
   2 pprint('Complex thing')

Generators / Iteration

   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

How to test if a string begins or ends with another string

   1 my_string = "abcdef"
   2 if my_string.startswith("abc"):
   3     starts_with_abc = True
   4 if my string.endswith("def"):
   5     ends_with_def = True

How to catch exceptions

   1 grades = ['A', 'A-', 'B', 'C']
   2 try:
   3     grades.index("F")
   4 except ValueError, inst:
   5     # Print the error information
   6     print inst.args

Catching multiple exceptions

   1 try:
   2     "do something"
   3 except (ExceptionOne, ExceptionTwo):
   4     # Note: The parens are important.
   5     "handle the exception"

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

  1. get developers
  2. bzr commit
  3. ???
  4. 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

   1 import gst
   2 player = gst.element_factory_make("playbin", "player")
   3 player.set_property("uri", "file:///usr/share/sounds/ubuntu/stereo/bell.ogg")
   4 player.set_state(gst.STATE_PLAYING)
   5 # or
   6 import pygame
   7 pygame.mixer.init()
   8 pygame.mixer.music.load("music.ogg")
   9 pygame.mixer.music.play()

notify-osd

   1 import pynotify
   2 
   3 pynotify.init('someName')
   4 
   5 n = pynotify.Notification("message name", "message", "icon")
   6 n.show()

# more notify-osd stuff

Get the output of a command

   1 import subprocess
   2 
   3 date = subprocess.Popen(['date', '+%c'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   4 (out, err) = date.communicate()
   5 print 'exit code', date.returncode

   1 import webbrowser
   2 
   3 url = 'http://google.com/'
   4 webbrowser.open_new(url)

Get the text for an HTML page from the web

   1 import urllib
   2 f = urllib.urlopen(day_url)
   3 html = f.read()

Create a stock cancel button and pack it into the vbox

   1 cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
   2 cancel_button.show()
   3 cancel_button.connect("clicked", on_cancel_clicked)

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

   1 import re
   2 text = "bug 1: first bug\nbug 2: duplicate of bug 1\nbug 999: the last bug"
   3 for m in re.finditer('bug (\d+):', text):
   4     print 'bug number: '+ m.group(1)

Download an URL and process it line by line

   1 import urllib
   2 for line in urllib.open('http://foo'):
   3     print 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

   1 col_count = 100
   2 self.list_store = gtk.ListStore(
   3     *[gobject.TYPE_STRING for i in range(col_count)])

Put data into desktop CouchDB

   1 from desktopcouch.records.server import CouchDatabase
   2 from desktopcouch.records.record import Record as CouchRecord
   3 
   4 db = CouchDatabase("dbname", create=True)
   5 record = CouchRecord(
   6     {"a": 1, "b": 2}, record_type="http://recordtypeurl",
   7     record_id=XXX)
   8 db.put_record(record)

Call a desktop CouchDB view

   1 view = """function(doc) { if (doc) emit(doc._id, doc); }"""
   2 if not self.messages.view_exists("myview", "myapp"):
   3     self.messages.add_view("myview", view, None, "myapp")
   4 result = self.messages.execute_view("myview", "myapp")

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

   1 from desktopcouch.records.record import Record
   2 from desktopcouch.records.server import CouchDatabase
   3 
   4 db = CouchDatabase("fosdem")
   5 record = Record(record_type="url")
   6 record.attach("/path/to/image/avatar.jpg", "blob", "image/jpg")
   7 db.put_record(record)

Creating a new Tomboy note

   1 def create_tomboy_note(text):
   2     bus = dbus.SessionBus()
   3     obj = bus.get_object("org.gnome.Tomboy", "/org/gnome/Tomboy/RemoteControl")
   4     tomboy = dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")
   5 
   6     n = tomboy.CreateNote()
   7     tomboy.DisplayNote(n)
   8     tomboy.SetNoteContents(n, text)

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

   1 import gtk, webkit
   2 gtk.gdk.threads_init()
   3 
   4 window = gtk.Window()
   5 window.connect("destroy", gtk.main_quit)
   6 web = webkit.WebView()
   7 web.open("http://ubuntu.com")
   8 
   9 window.add(web)
  10 window.show_all()
  11 gtk.main()

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

   1 def get_theme_colors(w):
   2     d = {}
   3 
   4     for i in ["base", "text", "fg", "bg"]:
   5         d[i] = Color.from_gtk_color(
   6             getattr(w.get_style(), i)[gtk.STATE_NORMAL].to_string())
   7 
   8         d["%s_selected" % i] = Color.from_gtk_color(
   9             getattr(w.get_style(), i)[gtk.STATE_SELECTED].to_string())
  10 
  11     return d

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]

   1 import ast
   2 ast.literal_eval ('[1,2,3,(4,5,6)]')

How to use doctests well

Don't.

Getting your packages updated

   1 import os
   2 os.system('evolution mailto:seb128@debian.org?subject=hi')
   3 # actually, he'll notice by himself.
   4 from time import sleep
   5 sleep (8 * 60 * 60) # go to bed

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

   1 import urllib
   2 img_stream = urllib.urlopen(url)
   3 img_file = open(fname,'w')
   4 img_file.write(img_stream.read())
   5 del img_file

Download a large file using a read buffer, saves memory

   1 import urllib
   2 img_stream = urllib.urlopen(url)
   3 img_file = open(fname,'w')
   4 while True:
   5     buf = img_stream.read(4096)
   6     if buf == "":
   7         break
   8     img_file.write(buf)
   9 del img_file

Compute the md5sum of a file without loading it all in memory

Still dealing with large files.

   1 import hashlib
   2 f = open(filepath)
   3 digest = hashlib.md5()
   4 while True:
   5     buf = f.read(4096)
   6     if buf == "":
   7         break
   8     digest.update(buf)
   9 f.close()
  10 print digest.hexdigest()

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.

   1 def parse_line(lines, separator):
   2     for line in lines:
   3         yield [token.strip() for token in line.split(separator)]

Create a pygtk window on the fly

   1 test_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
   2 test_window.connect("destroy", gtk.main_quit)
   3 test_window.set_title("my title")
   4 test_window.set_default_size(200,75)
   5 test_window.show()

Reading a bunch of stuff out of a function

   1 total = []
   2 for chunk in iter(lambda: file.read(4096), ''):
   3     total.append(chunk)
   4 result = ''.join(total)

Printing to a physical printer on linux

   1 import os
   2 printer=os.popen('lp','w')
   3 printer.write('sometext')
   4 printer.close()

Transposing a list of lists

zip(*list_of_lists)

Easy sorted merging of two lists (works also for dicts)

Not exactly efficient.

   1 l1 = [4, 5, 6]
   2 l2 = [4, 6, 7]
   3 for item in sorted(set(l1)|set(l2)):
   4     do_a_thing(item)

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)

   1 import gwibber.utils
   2 foo = gwibber.utils.GwibberPublic()
   3 foo.post("This is a test message")

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

   1 import os, stat
   2 st = os.stat(src_file_name)
   3 mode = stat.S_IMODE(st.st_mode)
   4 os.chmod(dest_file_name, mode)

Translations using gettext

   1 import gettext
   2 
   3 # Print 'hello' (it needs to be translated first though).
   4 print gettext.gettext("hello")

A really simple unittest module.

   1 import unittest
   2 
   3 class TestThing(unittest.TestCase):
   4 
   5     def setUp(self):
   6         super(unittest.TestCase, self).setUp()
   7         self.data = [2, 3, 5]
   8 
   9     def test_list_reversal(self):
  10         backwards = reversed(self.data)
  11         self.assertEqual([5, 3, 2], backwards)
  12 
  13     def tearDown(self):
  14         del self.data

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

   1 import dbus
   2 session_bus = dbus.SessionBus()
   3 if session_bus.request_name ('net.soft.name') != 1:
   4     print 'someone already has this name'
   5     exit()

Open a file from a dialog

   1 dialog = gtk.FileChooserDialog(
   2     "Select a file", w, gtk.FILE_CHOOSER_ACTION_OPEN,
   3     (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
   4 
   5 if dialog.run() == gtk.RESPONSE_OK:
   6     fn = dialog.get_filename()
   7     if os.path.exists(fn):
   8         print fn
   9 dialog.destroy()

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

   1 import os, sys
   2 
   3 if os.geteuid() != 0:
   4    print 'You must be root to run this script'
   5    sys.exit(0)

Quickly/Snippets (last edited 2011-04-09 22:52:34 by dsl-189-174-18-150-dyn)