Python Reference

From Supernifty

Jump to: navigation, search

This is a quick reference, or cheat sheet, to Python (the programming language)

Contents

Humour

<Sonium> someone speak python here?
<lucky> HHHHHSSSSSHSSS
<lucky> SSSSS
<Sonium> the programming language

Installing Modules

Eggs

If the module comes with a .egg file, this is the preferred installation option

  • Visit eggs setup
  • (Windows) Add C:\Python25\Scripts to your PATH
  • Run easy_install [package] e.g. easy_install MySQL-python

Traditional

  • Download the package
  • Run python setup.py install

Output

  • print = quick and dirty, but adds spaces
  • import sys
  • sys.stdout.write = best

Strings

  • len(s) = length of string

Formatting

  • 'format' % ( values )

Conversion characters

  • d,i = signed decimal
  • u = unsigned decimal
  • f,F = floating point
  • c = character
  • s = string

Modifiers

  •  %mc where m is the modifier
  • 0 = zero padded
  • .3 = 3 decimal places
  • - = left justified
  • + = precede with + or -

Regexp

  • import re
  • r = re.compile( r'search' )
  • s = r.sub( r'replace', src )

GUI - Tkinter

tkMessageBox

Quick example:

import tkMessageBox

  • Messageboxes for questions
answer = tkMessageBox.askyesno("askyesno", "Hello from askyesno\n1 of 7")
  • Change default button. Can be ABORT, RETRY, IGNORE, OK, CANCEL, YES, NO
answer = tkMessageBox.askquestion(title="askquestion", message="Hello from askquestion\n2 of 7", fault=tkMessageBox.NO) 
answer = tkMessageBox.askokcancel("askokcancel", "Hello from askokcancel\n3 of 7") 
answer = tkMessageBox.askretrycancel("askretrycancel", "Hello from askretrycancel\n4 of 7") 

  • Messageboxes for info
answer = tkMessageBox.showinfo("showinfo", "Hello from showinfo\n5 of 7") 
answer = tkMessageBox.showerror("showerror", "Hello from showerror\n6 of 7") 
warningMsg = "showwarning" 
answer = tkMessageBox.showwarning("showwarning","Final hello from:\n(%s)\n7 of 7" % warningMsg)

Canvas

Resizing

  • use winfo_width() and winfo_height() to get an up to date widget size

Logging

  • import logging
  • logging.getLogger().setLevel( logging.DEBUG );
  • logging.debug( "note %s", note )

Distributables

py2exe

Multimedia

Audio - tkSnack

Numerical Processing

Other Tasks

Base64

import base64
infile = file( "infile", "rb" )
outfile = file( "outfile", "w" )
base64.encode( infile, outfile )
outfile.close()

Style

Advertisement