python学习七:正则表达式、多线程初探

发布时间:2016-12-9 21:28:25 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"python学习七:正则表达式、多线程初探",主要涉及到python学习七:正则表达式、多线程初探方面的内容,对于python学习七:正则表达式、多线程初探感兴趣的同学可以参考一下。

1. 正则表达式 import re content = """Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others.""" # re module function: compile # re module / regex object functins: match, search, findall, finditer, # matching object functins: split, sub, group, groups print "RE learning" print "1." m = re.match("Python", content) # return match obj if m is not None: print type(m.group()) print m.group() # get a string m = re.search(r"\bthe\b", content) if m is not None: print type(m.group()) print m.group() print "2." m = re.match('(\w\w\w)-(\d\d\d)', 'abc-123') print m.group() print m.group(1) # get the first s ubgroup string print m.group(2) print m.groups() # get the strings in a tuple print "3." m = re.search('^The', 'The end.') if m is not None: print m.group() m = re.search(r'\bthe', 'in the room') if m is not None: print m.group() m = re.findall(r'\bthe\b', content) # return a list of string if m is not None: print m print "4." m = re.sub('X', 'Mr. Zhang', 'to: X\nDear X\n') # return a string print m m = re.subn('X', 'Mr. Zhang', 'to: X\nDear X\n') # return a tuple print m print "5." m = re.split(':', 'str1:str2:str3') # return a list, and can use RE as delimiter print m 2. 多线程 python虚拟机的访问由全局解释器锁(GIL)来控制,保证同一时刻只有一个线程在运行。 流程:1. 设置GIL 2. 运行线程 3. 运行指定数量的指令或者主动让出控制(例如time.sleep(0)) 4. 设置线程为休眠状态 5. 解锁GIL 在调用外部代码(如C/C++扩展函数)的时候,GIL将会被锁定,直到这个函数结束为止。 不使用thread模块的考虑: (1) threading跟完善 (2) threading模块有丰富的同步原语 (3) 对进程什么时候结束完全没有控制,threading模块可以确保重要的子线程退出后进程才退出。 print "Thread learning" print "a running function" import threading from time import sleep, ctime loops = [4,2] def loop(nloop, nsec): print "start loop", nloop, "at time:", ctime() sleep(nsec) print "loop", nloop, "Done at time:", ctime() def main(): print "main starting at:", ctime() threads = [] nloops = range(len(loops)) for i in nloops: t = threading.Thread(target = loop, args = (i, loops[i])) threads.append(t) for i in nloops: threads[i].start() for i in nloops: threads[i].join() print "all Done at time:", ctime() #if __name__ == '__main__': # main() print "an class object" class ThreadFunc(object): def __init__(self, func, args, name=''): self.name = name self.func = func self.args = args def __call__(self): apply(self.func, self.args) def main2(): # t = threading.Thread(target = ThreadFunc(loop, (i, loops[i]), loop.__name__))

上一篇:C#控制台冒泡排序 和百钱百鸡
下一篇:初级游戏外挂编程详解 windows运行原理+游戏辅助编程 游戏外挂编程

相关文章

相关评论