Python Snippet

# everything is an object

 

    import re  
      
    def build_match_and_apply_functions(pattern, search, replace):  
        def matches_rule(word):  
            return re.search(pattern, word)  
        def apply_rule(word):  
            return re.sub(search, replace, word)  
        return (matches_rule, apply_rule)  
      
    patterns = \  
      (  
        ('[sxz]$', '$',  'es'),  
        ('[^aeioudgkprt]h$', '$', 'es'),  
        ('(qu|[^aeiou])y$', 'y$', 'ies'),  
        ('$', '$',  's')  
      )  
      
    rules = [build_match_and_apply_functions(pattern, search, replace)  
             for (pattern, search, replace) in patterns]  
      
    def plural(noun):  
        for matches_rule, apply_rule in rules:  
            if matches_rule(noun):  
                return apply_rule(noun)  

 

# AOP

 

>>> class interceptor:
...         def __enter__(self):
...             print('enter...')
...         def __exit__(self, *args):
...             print('exit...')
...

>>> def say():
...         print('hello world!')
...
>>> with interceptor() as i:
...         say()
...
enter...
hello world!
exit...

 

>>> def interceptor(func):
...     def wrapper(*args, **kwargs):
...             print('enter...')
...             return func(*args, **kwargs)
...     return wrapper
...
>>>
>>> @interceptor
... def say():
...     print('hello world!')
...
>>>
>>> say()
enter...
hello world!

 

# no switch

 

>>> def do_a():
...     print('do_a')
...
>>> def do_b():
...     print('do_b')
...
>>> switchDict = {
...     'a': do_a,
...     'b': do_b
... }
>>> cases = ['a', 'b']
>>> for c in cases:
...     switchDict[c]()
...
do_a
do_b

 

# Generator

 

>>> def fib():  
        a, b = 0, 1  
    	while True:  
            yield a
            a, b = b, a+b  

>>> f = fib()  
>>> f  
<generator object fib at 0x01224A30>  
>>> print f.next()  
0  
>>> print f.next()  
1  
>>> print [f.next() for i in range(5)]  
[1, 2, 3, 5, 8] 

 

# email

 

import smtplib
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart  
from email.mime.image import MIMEImage 

mail_host = 'smtp.163.com'
mail_user = 'xxx'
mail_pswd = 'xxx'
mail_postfix = '163.com'
me = mail_user + '<' + mail_user + '@' + mail_postfix + '>'
mailto = ['[email protected]']

def send_mail():
	
	msgRoot = MIMEMultipart('related')
	msgRoot['Subject'] = 'test'
	msgRoot['From'] = me
	msgRoot['To'] = ';'.join(mailto)
	
	text = ('<b>Some <i>HTML</i> text</b> and an image.'
			'<br><img src="cid:image1"><br>')
	msgText = MIMEText(text, 'html', 'utf-8')
	
	imagePath = 'xxx.jpg'
	with open(imagePath, 'rb') as fp:
		msgImage = MIMEImage(fp.read())
	msgImage.add_header('Content-ID', '<image1>')

	msgRoot.attach(msgText)
	msgRoot.attach(msgImage)
	
	try:
		s = smtplib.SMTP()
		s.connect(mail_host)
		s.login(mail_user, mail_pswd)
		s.sendmail(me, mailto, msgRoot.as_string())
		s.close()
		return True
	except Exception as e:
		print str(e)
		return False
		
if __name__ == '__main__':
	if send_mail():
		print 'success!'
	else:
		print 'fail!'

 

# MySQLdb

 

from MySQLdb import *

host = 'xxx.xxx.xxx.xxx'
user = 'xxx'
pswd = 'xxx'
db = 'xxx'
with connect(host, user,pswd, db) as cur:
	cur.execute('SELECT version()')
	print 'version: %s' %cur.fetchone()

 

dis

 

# pip

 

pexpect


# pssh 

 

你可能感兴趣的:(python)