Python学习 14day__高级语法

线程替代方案

  subprocess
   完全跳过线程,使用进程
   是派生进程的主要替代方案
  multiprocessiong
   使用threading接口派生,使用紫子进程
  concurrent.futures
   新的异步执行模块
   任务级别的操作

多进程

  进程间通讯
  进程间无任何共享状态

 1 # 进程的创建
 2 import multiprocessing
 3 from time import sleep,ctime
 4 
 5 def clock(interval):
 6     while True:
 7         print("The time is %s"%ctime())
 8         sleep(interval)
 9 
10 if __name__ == '__main__':
11     p = multiprocessing.Process(target= clock, args = (5,))
12     p.start()
13 
14     while True:
15         print("sleeping.....")
16         sleep(1)
 1         import multiprocessing
 2         from time import sleep, ctime
 3 
 4 
 5         class ClockProcess(multiprocessing.Process):
 6             """
 7             两个函数比较重要
 8              init构造函数
 9              run
10             """
11 
12             def __init__(self, interval):
13                 super().__init__()
14                 self.interval = interval
15 
16             def run(self):
17                 while True:
18                     print("The time is %s" % ctime())
19                     sleep(self.interval)
20 
21 
22         if __name__ == '__main__':
23             p = ClockProcess(3)
24             p.start()
25 
26             while True:
27                 print("sleeping.....")
28                 sleep(1)

派生子类
 1 import multiprocessing
 2 from time import sleep, ctime
 3 
 4 class ClockProcess(multiprocessing.Process):
 5     """
 6     两个函数比较重要
 7      init构造函数
 8      run
 9     """
10 
11     def __init__(self, interval):
12         super().__init__()
13         self.interval = interval
14 
15     def run(self):
16         while True:
17             print("The time is %s"% ctime())
18             sleep(self.interval)
19 
20 if __name__ == '__main__':
21     p = ClockProcess(3)
22     p.start()
23 
24     while True:
25         print("sleeping.....")
26         sleep(1)

  在os中查看pid, ppid以及他们的关系

 1 from multiprocessing import Process
 2 import os
 3 
 4 def info(title):
 5     print(title)
 6     print("module name:", __name__)
 7     # 得到父类进程的id
 8     print("parent process:", os.getppid())
 9     # 得到本身进程的id
10     print("process id:", os.getpid())
11 
12 
13 def f(name):
14     info('function f')
15     print('hello', name)
16 
17 if __name__ == '__main__':
18     info("main line")
19     p = Process(target=f, args=("bob",))
20     p.start()
21     p.join()

迭代器

  可迭代(Iterable):直接作用于for循环变量
  迭代器(Iterator): 不但可以作用于for循环,还可以被next调用
  list是可迭代对象,但不是迭代器

1 l = [i for i in range (5)]
2 #l 是可迭代对象,但不是迭代器
3 for x in l:
4     print(x)
5 # range 是迭代器
6 for i in range(5):
7     print(i)

通过isintance判断
1 from collections import Iterable
2 
3 ll = [1, 2, 3, 4, 5]
4 print(isinstance(ll, Iterable))  # 判断ll是否可迭代
5 
6 from collections import Iterator
7 print(isinstance(ll, Iterator))  # 判断ll是否为迭代器

通过iter()函数可以将Iterable和Iterator进行转换
1 s = 'I Love Python'
2 
3 print(isinstance(s, Iterable))
4 print(isinstance(s, Iterator))
5 
6 s_iter = iter(s)                #  通过iter()函数将s变为迭代器
7 print(isinstance(s_iter, Iterable))
8 print(isinstance(s_iter, Iterator))

生成器

  generator: 一边循环一边计算下一个元素的机制/算法
  需要满足三个条件:
   每次调用都生产出for循环需要的下一个元素
   如果达到左后一个后,爆出StopIteration异常
   可以被next调用

直接使用生成器
1 L = [x*x for x in range(5)] # 放在中括号里面是列表生成式
2 l = (x*x for x in range(5)) # 放在小括号中就是生成器
3 
4 print(type(L))
5 print(type(l))


在函数odd中,yield负责返回
 1 def odd():
 2     print("Step 1")
 3     yield 1
 4     print("Step 2")
 5     yield 1
 6     print("Step 3")
 7     yield 1
 8 
 9 # odd()是调用生成器
10 g = odd()
11 one = next(g)
12 print(one)
13 two = next(g)
14 print(two)


# for循环调用生成器
# 斐波那契数列的生成器写法
 1 def fib(max):
 2     n, a, b = 0, 0, 1
 3     while n < max:
 4         yield b
 5         a, b = b, a+b
 6         n += 1
 7     return 'Done'
 8 
 9 g = fib(5)
10 for i in range(6):
11     rst = next(g)
12     print(rst)

协程

  协程是为非抢占式多任务产生子程序的计算机程序组件,协程允许不同入口点在不同位置暂停或开始执行程序
  协程的四个状态:
   GEN_CREATED: 等待开始执行
   GEN_RUNNING: 解释器正在执行
   GEN_SUSPENED: 在yield表达式处暂停
   GEN_CLOSED: 执行结束

 1 # 协程代码1
 2 def simple_coroutine():
 3     print("——> strat")
 4     x = yield
 5     print("——> recived", x)
 6 
 7 # 主线程
 8 sc = simple_coroutine()
 9 print(1111)
10 # 可以使用sc.send(None)
11 next(sc)           # 执行一次在yield处终止
12 
13 print(2222)
14 sc.send("zhexiao")

猜你喜欢

转载自www.cnblogs.com/Burtit/p/9438614.html