python queue模块

2018-06-18 00:37:43来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 1 import queue
 2 # queue - A multi-producer, multi-consumer queue.
 3 # ['Empty', Exception raised by Queue.get(block=0)/get_nowait()
 4 #  'Full', Exception raised by Queue.put(block=0)/put_nowait()
 5 #  'LifoQueue',
 6 #  'PriorityQueue',
 7 #  'Queue',]
 8 
 9 
10 # 1、Empty
11 q = queue.Queue(3)
12 q.get(block=False)   # 抛出Empty异常
13 q.get_nowait()       # 抛出Empty异常
14 
15 # 2、Full
16 q = queue.Queue(3)
17 q.put(1)
18 q.put(1)
19 q.put(1)
20 q.put(1, block=False)  # 抛出Full异常
21 q.put_nowait(1)        # 抛出Full异常
22 
23 # 3、Queue
24 # Create a queue object with a given maximum size.
25 # If maxsize is <= 0, the queue size is infinite.
26 q = queue.Queue(5)  # 创建一个长度为5的队列
27 p = queue.Queue(0)  # 创建一个无限长度的队列
28 # empty(self) Return True if the queue is empty, False otherwise (not reliable!).
29 print(q.empty())
30 # full(self) Return True if the queue is full, False otherwise (not reliable!).
31 print(q.full())
32 # put(self, item, block=True, timeout=None) Put an item into the queue.
33 q.put(1)
34 # get(self, block=True, timeout=None) Remove and return an item from the queue.
35 print(q.get())
36 # put_nowait(self, item) Put an item into the queue without blocking.
37 print(q.put_nowait(2))
38 # get_nowait(self) Remove and return an item from the queue without blocking.
39 print(q.get_nowait())
40 # qsize(self) Return the approximate size of the queue (not reliable!).
41 print(q.qsize())
42 # join(self) Blocks until all items in the Queue have been gotten and processed.
43 # print(q.join())         # 阻塞put,等待全部get完
44 # task_done(self) Indicate that a formerly enqueued task is complete.
45 # print(q.task_done())    # 每次get完之后调用。
46 
47 
48 # 4、LifoQueue继承Queue,栈
49 # 方法同Queue
50 q = queue.LifoQueue(5)
51 q.put(1)
52 q.put(2)
53 q.put(3)
54 q.put(4)
55 print(q.get())  # 4
56 print(q.get())  # 3
57 print(q.get())  # 2
58 print(q.get())  # 1
59 
60 
61 # 5、PriorityQueue继承Queue
62 # 方法同Queue,元素(priority number, data)
63 q = queue.PriorityQueue(5)
64 q.put((1, 'a'))
65 q.put((4, 'd'))
66 q.put((2, 'b'))
67 q.put((3, 'c'))
68 print(q.get())   # (1, 'a')   # 小的数先出
69 print(q.get())   # (2, 'b')
70 print(q.get())   # (3, 'c')
71 print(q.get())   # (4, 'd')

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Django的模版引擎与模版使用

下一篇:爬虫之requests