Python 元类例子

class ChattyType(type):
    def __new__(cls, name, bases, dct):
       print "Allocating memory for class", name
       return type.__new__(cls, name, bases, dct)

    def __init__(cls, name, bases, dct):
        print "Init'ing (configuring) class", name
        super(ChattyType, cls).__init__(name, bases, dct)
X = ChattyType('X',(),{'foo':lambda self:'foo'})

Python 改变救济的例子

from Tkinter import *

class GUI(Frame):
    def __init__(self):
        Frame.__init__(self)
        button = Button(relief=RAISED,text='Test Button')
        button.pack()
        button.bind("<Button-1>",self.changeRelief)

    def changeRelief(self,event):
        event.widget.config(relief=SUNKEN)


myGUI = GUI()
myGUI.mainloop()

Python 斐波那契

def fibon(n):
    if n<2:
        return n
    else:
        return fibon(n-1) + fibon(n-2)

print fibon(30)

Python OpenERP:XML-RPC Web服务(CRUD示例)

"""
:The login function is under
::    http://localhost:8069/xmlrpc/common
:For object retrieval use:
::    http://localhost:8069/xmlrpc/object
"""
import xmlrpclib

user = 'admin'
pwd = 'admin'
dbname = 'terp3'
model = 'res.partner'

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock.login(dbname ,user ,pwd)

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')

# CREATE A PARTNER
partner_data = {'name':'Tiny', 'active':True, 'vat':'ZZZZZ'}
partner_id = sock.execute(dbname, uid, pwd, model, 'create', partner_data)

# The relation between res.partner and res.partner.category is of type many2many
# To add  categories to a partner use the following format:
partner_data = {'name':'Provider2', 'category_id': [(6,0,[3, 2, 1])]}
# Where [3, 2, 1] are id fields of lines in res.partner.category

# SEARCH PARTNERS
args = [('vat', '=', 'ZZZZZ'),]
ids = sock.execute(dbname, uid, pwd, model, 'search', args)

# READ PARTNER DATA
fields = ['name', 'active', 'vat', 'ref']
results = sock.execute(dbname, uid, pwd, model, 'read', ids, fields)
print results

# EDIT PARTNER DATA
values = {'vat':'ZZ1ZZ'}
results = sock.execute(dbname, uid, pwd, model, 'write', ids, values)

# DELETE PARTNER DATA
results = sock.execute(dbname, uid, pwd, model, 'unlink', ids)

Python 多个数据库连接的管理器

# -*- coding: utf-8 -*-

"""
Sample settings:

DATABASE_ENGINE = 'postgresql_psycopg2'
DATABASE_NAME = 'default_db_name'
DATABASE_USER = 'user'
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''

# Any omitted property will inherit the default value from settings
DATABASES = {
    'default': {},
    'alternative': {
        'DATABASE_NAME': 'alternative_db_name',
    },
}
"""

from django.conf import settings
from django.db import models, backend

# Default connection
db_settings = {
    'DATABASE_HOST': settings.DATABASE_HOST,
    'DATABASE_NAME': settings.DATABASE_NAME,
    'DATABASE_OPTIONS': settings.DATABASE_OPTIONS,
    'DATABASE_PASSWORD': settings.DATABASE_PASSWORD,
    'DATABASE_PORT': settings.DATABASE_PORT,
    'DATABASE_USER': settings.DATABASE_USER,
    'TIME_ZONE': settings.TIME_ZONE,
}

def prepare_db_settings(db_profile_name):
    """
    Takes custom database settings, replaces missing values with the
    defaults from settings and returns a new connection dict.
    """
    return dict(db_settings, **settings.DATABASES[db_profile_name])

class MultiDBManager(models.Manager):
    """
    A manager that can connect to different databases.
    """
    def use(self, db_profile_name):
    	"""
    	Return a queryset connected to a custom database.
    	"""
        # Get customized database settings to use in a new connection wrapper
        db_settings = prepare_db_settings(db_profile_name)

    	# Get the queryset and replace its connection
        qs = self.get_query_set()
        qs.query.connection = backend.DatabaseWrapper(db_settings)
        return qs

Python 将列表传递给dict()

>>> i
['a', 'b']
>>> l
[1, 2]
>>> dict([i,l])
{'a': 'b', 1: 2}

Python Python:生成一个随机数

'''
Dice Roller - Generate two pseudo-random numbers
@author: chrisaiv
'''

import random

die1 = random.randrange(6) + 1
die2 = random.randrange(6) + 1

total = die1 + die2

print "You rolled a", die1, "and a", die2, "for a total of ", total

Python 备份我的twitter-log

# vim: ts=2 sw=2 expandtab
import sys
from os import mkdir
from os.path import exists
import time
from urllib2 import urlopen
from xml.dom import Node
from xml.dom.minidom import parseString
from time import strptime, strftime, localtime, time, sleep
from calendar import timegm

debug=True

def getRemain():
  url='http://twitter.com/account/rate_limit_status.xml'
  raw=urlopen(url).read()
  dom=parseString(raw)
  tag=dom.getElementsByTagName('remaining-hits').item(0)
  remain=int(tag.firstChild.data)
  return remain

def getResetTime():
  url='http://twitter.com/account/rate_limit_status.xml'
  raw=urlopen(url).read()
  dom=parseString(raw)
  tag=dom.getElementsByTagName('reset-time').item(0)
  resetTime=tag.firstChild.data
  return resetTime

def getIds(dom):
  ids=[]
  for idNode in dom.getElementsByTagName('id'):
    ids.append(int(idNode.childNodes[0].data))
  return ids

def getPage(user, page):
  url='http://twitter.com/statuses/user_timeline/'
  rawData=urlopen(url+user+'.xml?page='+str(page)).read()
  return rawData

def getEpoch(str):
	dd = strptime(str, "%a %b %d %H:%M:%S +0000 %Y")
	return timegm(dd)

def addEpochAttr(dom):
	ds=dom.getElementsByTagName('created_at')
	for d in ds:
		dtext=d.firstChild.data
		depoch=getEpoch(dtext)
		d.setAttribute('epoch', str(depoch))

def debug(str):
  if debug: print 'DEBUG: '+str

### MAIN ####################################################
if(len(sys.argv)<2):
  print 'Usage: '+sys.argv[0]+' <twitter account name> [page offset]'
else:
  user=sys.argv[1]
  print 'twitter account name: '+user
  dir='twitter-log-'+user
  sleepTime=3
  
  # CONFIRM
  s=raw_input('Now logging start, take several times. r u OK? [y/N]: ')
  
  if s.lower()=='y' or s.lower()=='yes':
    # START LOGGING
    remain=getRemain()
    if(remain>0):
      if(not exists(dir)): mkdir(dir) # make dir
      debug('make dir: '+dir)
      idSet=set()                           # init
      if(len(sys.argv)>2): page=int(sys.argv[2])
      else:                page=1
      pageStr='%04d'%page
      rawData=getPage(user, page)           # get log
      dom=parseString(rawData)
      addEpochAttr(dom)
      debug('get log: page='+str(page))
      newIdSet=set(getIds(dom))-idSet
      idSet=idSet|newIdSet
      debug('new tweet: '+str(len(newIdSet))+', accum. tweet: '+str(len(idSet)))
      remain=getRemain()
      debug('remain hits: '+str(remain))
  
      while(len(newIdSet)>0 and remain>0):
        rawData=dom.toxml("utf-8")
        path=strftime("%Y%m%d-%H%M%S", localtime(time()))+'-page'+pageStr+'.xml'
        f=open(dir+'/'+path, 'w')
        f.write(rawData)
        debug('write file: '+path)
  
        debug('wait '+str(sleepTime)+'sec.')
        sleep(sleepTime);                   # wait
  
        page+=1
        pageStr='%04d'%page
        rawData=getPage(user, page)           # get log
        dom=parseString(rawData)
        addEpochAttr(dom)
        debug('get log: page='+str(page))
        newIdSet=set(getIds(dom))-idSet
        idSet=idSet|newIdSet
        debug('new tweet: '+str(len(newIdSet))+', accum. tweet: '+str(len(idSet)))
        remain=getRemain()
        debug('remain hits: '+str(remain))

      if(remain==0):
        print 'Error: no more request.'
        print 'Next reset time(UTC): '+getResetTime()
      else: print 'OK!'

    else:
      print 'Error: no more request.'
      print 'Next reset time(UTC): '+getResetTime()
  else: print 'Aborted.'

Python Python:List + Dictionary Basics

#List Example
pals = list()
pals.append( "chris" )
pals.append( "sandy" )
pals.append( "josie" )
print "Items in List => " + str(pals), "List Length => " + str(len(pals))

print "\n"
#Dictionary Example: Great for placing key value pairs without knowing in advance what we will be putting in the dictionary
pal = dict()
pal['first'] = 'Chris'
pal['last']  = 'Aiv'
pal['email'] = 'chrisaiv@gmail.com'
pal['phone'] = '555-555-5555'
print pal

print "\n"

#Forgiving way to find an item within a dictionary
print pal.get("age", "Age not available")
print pal.get("phone", "Phone not available")

print "\n"

#Looping through a Dictionary
print "~~KEY : Value~~"
for key in pal:
	print key, ":", pal[key]
	
print "\n"

#Find out what capabilities are available in a particular Data Object
print dir(pals)

Python 通过Xlib在Linux上进行鼠标定位

from Xlib import X, display
d = display.Display().screen().root.query_pointer()._data

print "x="
print d["root_x"]
print "y="
print d["root_y"]