在我的项目中,我需要重复构造和销毁上下文,但它会给出错误。
例如:
导入zmq
对于范围内的我(100): 打印(I) context = zmq.Context() data_socket = …
套接字选项必须放在。之前 .connect() 要么 .bind() 方法,您可以从中创建单元实例 zmq.Context() 。
.connect()
.bind()
zmq.Context()
试试吧:
import zmq context = zmq.Context.instance() for i in range(100): print(i) data_socket = context.socket(zmq.SUB) data_socket.setsockopt(zmq.SUBSCRIBE, b"") data_socket.connect("tcp://127.0.0.1:5552") context.destroy()
[ 的 你的答案 强> ]:
但是,如果您想要处理您的方式,则应在每次迭代中关闭套接字,因此您的代码段将为:
import zmq for i in range(100): ctx = zmq.Context.instance() sock = ctx.socket(zmq.SUB) sock.setsockopt(zmq.SUBSCRIBE, b'') sock.connect('tcp://127.0.0.1:5552') sock.close() # Note ctx.destroy() print('ctx closed status: ', ctx.closed, ' iteration: ', i)
日期:
('ctx closed status: ', True, ' iteration: ', 0) ('ctx closed status: ', True, ' iteration: ', 1) ('ctx closed status: ', True, ' iteration: ', 2) ('ctx closed status: ', True, ' iteration: ', 3) ('ctx closed status: ', True, ' iteration: ', 4) ('ctx closed status: ', True, ' iteration: ', 5) ('ctx closed status: ', True, ' iteration: ', 6) ('ctx closed status: ', True, ' iteration: ', 7) ('ctx closed status: ', True, ' iteration: ', 8) ('ctx closed status: ', True, ' iteration: ', 9) ('ctx closed status: ', True, ' iteration: ', 10) ('ctx closed status: ', True, ' iteration: ', 11) ('ctx closed status: ', True, ' iteration: ', 12) ('ctx closed status: ', True, ' iteration: ', 13) ('ctx closed status: ', True, ' iteration: ', 14) . . .