首页 > 文章列表 > python中Queue如何通信

python中Queue如何通信

Python Queue
270 2022-08-07

说明

1、Queue可以使用multiprocessing模块实现多过程间的数据传输。

2、Queue本身就是一个消息队列程序。

当Queue()对象初始化时(例如:q=Queue()),如果括号中没有指定可接收信息的数量,或者数量为负值,则表示可接收信息的数量没有上限直到内存结束。

实例

from multiprocessing import Queue
 
 
def queue_test():
    q = Queue(3) #初始化一个Queue对象,最多可接收三条put消息
    q.put("消息1")
    q.put("消息2")
    print(q.full()) #False
    q.put("消息3")
    print(q.full()) #True
 
 
    #因为消息列队已满下面的try都会抛出异常,第一个try会等待2秒后再抛出异常,第二个Try会立刻抛出异常
    try:
        q.put("消息4",True,2)
    except:
        print("消息列队已满,现有消息数量:%s"%q.qsize())
 
    try:
        q.put_nowait("消息4")
    except:
        print("消息列队已满,现有消息数量:%s"%q.qsize())
 
 
    #推荐的方式,先判断消息列队是否已满,再写入
    if not q.full():
        q.put_nowait("消息4")
 
 
    #读取消息时,先判断消息列队是否为空,再读取
    if not q.empty():
        for i in range(q.qsize()):
            print(q.get_nowait())
        
        
def main():
    queue_test()
    
 
if __name__ == "__main__"
main()

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。