队列queue

队列简单使用:

import queue

def a():
    print("this is fun a")

class B():
    def p(self):
        print("this is class B")

# 先进先出
q1 = queue.Queue()
b = B()
q1.put(1)
q1.put(a)
q1.put(b)
d = q1.get()
print(d)
d = q1.get()
d()
d = q1.get()
d.p()
del q1
"""运行结果
1
this is fun a
this is class B
"""
# q.empty()判断q是否为空。
# q.full(0判断q是否为满

# 设置queue的大小
q1 = queue.Queue(maxsize=3)
try:
    q1.get(timeout=1)  # 当q为空时,超过1秒还是空时会报异常:queue.Empty
except Exception as e:
    print(e)
try:
    q1.get_nowait()  # 当q为空时,会报异常:queue.Empty
except Exception:
    pass

q1.put("xxx")  # 当q满时会阻塞
q1.put("xxx")  # 当q满时会阻塞
q1.put("xxx")  # 当q满时会阻塞
try:
    q1.put_nowait("xxx")  # 当q满时会报异常:queue.Full
except Exception:
    pass

try:
    q1.put(b,timeout=2)   # 超过2秒q还是满时会报异常:queue.Full
except Exception as e:
    print(e)
print(q1.get()) #当q为空时会阻塞
del q1

# 先进后出队列
q1 = queue.LifoQueue(maxsize=5)
del q1
# 优先级队列
q1 = queue.PriorityQueue(maxsize=5)
# 数字晓得优先级高
q1.put((1,"yes"))
q1.put((5,"no"))
q1.put((3,"yes"))
print(q1.get())
print(q1.get())
print(q1.get())
"""运行结果
(1, 'yes')
(3, 'yes')
(5, 'no')
"""

  

原文地址:https://www.cnblogs.com/owasp/p/5597909.html