《Python核心编程》读书笔记(二)

让一个实例可调用

class C(object):
def call(self, *args):
print “I’m callable”
c =C()
callable(c)

#True
c()

#I’m callable

执行python字符串

#eval_code(string, file, type)

#eval(obj, globals=globals(), locals=locals()) 也可以是字符串表达式

#exec obj

#input(prompt=’’)

#可求值表达式
eval_code = compile(‘100+200’, ‘’, ‘eval’)
eval(eval_code)

#300

#单一可执行语句
single_code = compile(‘print “hello world” ‘, ‘’, ‘single’ )
exec single_code

#hello world

eval(‘100+200’)

#300
exec和eval相似,不过exec会执行经过compile编译的python代码,所以执行编译过后的代码性能比exec会好一些,当然exec也可以执行原始字符串:
exec “”” some code “””

exec执行和execfile执行
exec “””
x = 0
print ‘x is currently:’,x
while x < 5
x += 1
print ‘incrementing x to:’, x
“”””
我们把上述代码保存为 xcount.py,当然不包括exec
f = open(‘xcount.py’)
exec f

#打印信息

#再执行一次
exec f

#什么都没有了
这时候我们调用 f.tell()
f.tell()

#116
import os
os.path.getsize(‘xcount.py’)

#116,表示文件指针已经到末尾了,可以使用 f.seek(0) 返回头部
f.seek(0)

#打印信息
f.close()
上述代码也可以使用 execfile 来代替
execfile(filename, globals=globals(), locals=locals())

执行其他非python程序
system(cmd)
spawn(mode, file, args [,env])
execlp(cmd, arg0, arg1)
execvp(cmd, arglist)

os.fork 创建子进程
ret = os.fork()
if ret == 0: #子进程代码
execvp(‘xbill’, [‘xbill’])
else: #父进程代码
os.wait() #等待子进程退出

结束进程
import sys
sys.exit(1)

正则表达式re模块
compile(pattern, flags=0) #对正则表达式进行编译,返回一个regex对象
match(pattern, string ,flags=0) #尝试对正则表达式 pattern 匹配字符串 string,如果匹配成功则返回匹配对象
search(pattern, string, flags=0) #匹配string第一次在pattern出现,如果匹配成功,则返回匹配对象,否则为None
findall(pattern, string, [flags]) #字符串在正则表达式pattern的所有(非重复)出现,保存为匹配对象数组
finditer(pattern, string, [flags]) #和findall相同,但是返回的是迭代器,可以用for in
split(pattern, string, max=0) #根据正则表达式的分隔符,把字符串分割成一个列表,最多分割max次,默认是所有
sub(pattern,repl,string,max=0) #根据pattern把string中的匹配地方换成repl
group(num=0) #返回全部匹配对象,或指定num的子组
groups() #返回一个包含全部匹配的子组的元组,如果没有匹配成功返回空元组

match的用法,判断字符串开头
m = re.match(‘foo’, ‘food on the table’)
m.group()

#foo

search从字符串中间开始搜索,匹配多个
m = re.search(‘foo’, ‘seafood’)
m.group()

#’foo’
bt = ‘bat|bet|bit’
m = re.search(bt, ‘big’)
m.group()
‘bit’

使用threading模块,避免使用thread模块,尽可能使用threading
Thread类,表示一个线程对象
Lock,锁对象
RLock,可重入锁对象
Condition,条件变量,能让一个线程停下来,等待其他线程满足了这个条件
Event,多个线程可以等待某个事件的发生,发生后,所有的线程都将被激活
Semaphore,为等待锁的线程,提供一个等候室
BoundedSemaphore,与Semaphore相同,不过不允许超过初始值
Timer,与Thread相似,不过要等待一段时间后才开始运行

Thread类的方法
start(),开始线程执行
run(),定义线程的功能函数,一般会被子类重写
join(timeout=None),程序挂起,直到线程结束,如果给定timeout,则最多阻塞timeout秒
getName(),返回线程的名字
setName(),设定线程的名字
isAlive(),布尔标志,表示这个线程是否还在运行中
isDaemon(),返回县城的daemon标志
setDaemon(daemonic),把线程的daemon标志设为daemonic,要在调用start()函数前调用

urlparse模块
import urlparse
x = urlparse.urlparse(‘http://www.aaa.com/aaa/aaa.html?a=1#f')

#ParseResult(scheme=’http’, netloc=’www.aaa.com', path=’/aaa/aaa.html’, params=’’, query=’a=1’, fragment=’f’)
urlparse.urlunparse(x)

#’http://www.aaa.com/aaa/aaa.html?a=1#f'

urllib模块,http的encode和decode
import urllib
x = urllib.quote(‘http://snoopyxdy.blog.163.com/blog/getBlog.do?bid=fks')
print x

#http%3A//snoopyxdy.blog.163.com/blog/getBlog.do%3Fbid%3Dfks
y = urllib.quote_plus(‘http://snoopyxdy.blog.163.com/blog/getBlog.do?bid=fks')
print y

#http%3A%2F%2Fsnoopyxdy.blog.163.com%2Fblog%2FgetBlog.do%3Fbid%3Dfks
解码则用 urllib.unquote() 和 urllib.unquote_plus()

urllib.urlencode() 将字典变为key=value存储
aDict = {‘a’:’1’, ‘b’:’ ~x ‘}
urllib.urlencode(aDict)

#’a=1&b=+%7Ex+’

string.capwords() 自动将字符串每个单词首字母大写
import string
string.capwords(‘foo aoo’)

unicode字符串转城utf-8
hello = u’hello’
hello.encode(‘utf-8’)

字符串和unicode转换

#将Unicode转换成普通的Python字符串:”编码(encode)”
unicodestring = u”Hello world”
utf8string = unicodestring.encode(“utf-8”)
asciistring = unicodestring.encode(“ascii”)
isostring = unicodestring.encode(“ISO-8859-1”)
utf16string = unicodestring.encode(“utf-16”)

#将普通的Python字符串转换成Unicode: “解码(decode)”
plainstring1 = unicode(utf8string, “utf-8”)
plainstring2 = unicode(asciistring, “ascii”)
plainstring3 = unicode(isostring, “ISO-8859-1”)
plainstring4 = unicode(utf16string, “utf-16”)

httplib的post或get请求例子,伪代码
conn = httplib.HTTPConnection(host)

#尝试连接coreservice主机

errPrefix = ‘method:{0},host:{1},url:{2},param:{3}’.format(method,host,url,paramDictStr)

try:
if method == ‘POST’:
headers = {“Content-type”: “application/x-www-form-urlencoded”,
“Accept”: “text/plain”}

    #如果是coreservice转json
    if host == app.config['CORESERVICE_HOST']:
        headers = {"Content-type": "application/json",
                "Accept": "application/json"}


    conn.request(method, url, paramDictStr, headers)
else: 
    conn.request(method, url+'?'+paramDictStr)

except Exception as err:
return {‘error’:1,’data’:’{0},{1}’.format(errPrefix,err)}

#获取响应
res = conn.getresponse()
data = res.read() #读取响应

#关闭连接

#print(res)

if res.status != 200 :
return {‘error’:1,’data’:’{0}, coreservice服务异常,状态:{1},响应:{2}’.format(errPrefix,res.status,data)}
conn.close()