当前位置: 首页 > 图灵资讯 > 行业资讯> python中Queue如何通信

python中Queue如何通信

发布时间:2024-08-04 17:30:38

说明

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

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

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

实例

frommultiprocessingimportQueue


defqueue_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())


#推荐方法,首先判断消息列队是否已满,再写入
ifnotq.full():
q.put_nowait("消息4")


#读取消息时,首先判断消息列队是否为空,再读取
ifnotq.empty():
foriinrange(q.qsize()):
print(q.get_nowait())


defmain():
queue_test()


if__name__=="__main__"
main()

以上是python中Queue通信的方法,希望对大家有所帮助。学习更多的编程基础知识:python学习网

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

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09