zmq#
Python bindings for 0MQ
Basic Classes#
Note
For typing purposes, zmq.Context
and zmq.Socket
are Generics,
which means they will accept any Context or Socket implementation.
The base zmq.Context()
constructor returns the type
zmq.Context[zmq.Socket[bytes]]
.
If you are using type annotations and want to exclude the async subclasses,
use the resolved types instead of the base Generics:
ctx: zmq.Context[zmq.Socket[bytes]] = zmq.Context()
sock: zmq.Socket[bytes]
in pyzmq 26, these are available as the Type Aliases (not actual classes!):
ctx: zmq.SyncContext = zmq.Context()
sock: zmq.SyncSocket
Context
#
- class zmq.Context(io_threads: int = 1)#
- class zmq.Context(io_threads: Context)
- class zmq.Context(*, shadow: Context | int)
Create a zmq Context
A zmq Context creates sockets via its
ctx.socket
method.Changed in version 24: When using a Context as a context manager (
with zmq.Context()
), or deleting a context without closing it first,ctx.destroy()
is called, closing any leftover sockets, instead ofctx.term()
which requires sockets to be closed first.This prevents hangs caused by
ctx.term()
if sockets are left open, but means that unclean destruction of contexts (with sockets left open) is not safe if sockets are managed in other threads.Added in version 25: Contexts can now be shadowed by passing another Context. This helps in creating an async copy of a sync context or vice versa:
ctx = zmq.Context(async_ctx)
Which previously had to be:
ctx = zmq.Context.shadow(async_ctx.underlying)
- closed#
boolean - whether the context has been terminated. If True, you can no longer use this Context.
- destroy(linger: int | None = None) None #
Close all sockets associated with this context and then terminate the context.
Warning
destroy involves calling
Socket.close()
, which is NOT threadsafe. If there are active sockets in other threads, this must not be called.- Parameters:
linger (int, optional) – If specified, set LINGER on sockets prior to closing them.
- get(option: int)#
Get the value of a context option.
See the 0MQ API documentation for zmq_ctx_get for details on specific options.
Added in version libzmq-3.2.
Added in version 13.0.
- getsockopt(opt: int) str | bytes | int #
get default socket options for new sockets created by this Context
Added in version 13.0.
- classmethod instance(io_threads: int = 1) zmq.Context #
Returns a global Context instance.
Most single-process applications have a single, global Context. Use this method instead of passing around Context instances throughout your code.
A common pattern for classes that depend on Contexts is to use a default argument to enable programs with multiple Contexts but not require the argument for simpler applications:
class MyClass(object): def __init__(self, context=None): self.context = context or Context.instance()
Changed in version 18.1: When called in a subprocess after forking, a new global instance is created instead of inheriting a Context that won’t work from the parent process.
- set(option: int, optval)#
Set a context option.
See the 0MQ API documentation for zmq_ctx_set for details on specific options.
Added in version libzmq-3.2.
Added in version 13.0.
- setsockopt(opt: int, value: Any) None #
set default socket options for new sockets created by this Context
Added in version 13.0.
- classmethod shadow(address: int | Context) zmq.Context #
Shadow an existing libzmq context
address is a zmq.Context or an integer (or FFI pointer) representing the address of the libzmq context.
Added in version 14.1.
Added in version 25: Support for shadowing
zmq.Context
objects, instead of just integer addresses.
- classmethod shadow_pyczmq(ctx: Any) zmq.Context #
Shadow an existing pyczmq context
ctx is the FFI
zctx_t *
pointerAdded in version 14.1.
- socket(socket_type: int, socket_class: Callable[[zmq.Context, int], zmq.Socket] | None = None, **kwargs: Any) zmq.Socket #
Create a Socket associated with this Context.
- Parameters:
socket_type (int) – The socket type, which can be any of the 0MQ socket types: REQ, REP, PUB, SUB, PAIR, DEALER, ROUTER, PULL, PUSH, etc.
socket_class (zmq.Socket) –
The socket class to instantiate, if different from the default for this Context. e.g. for creating an asyncio socket attached to a default Context or vice versa.
Added in version 25.
kwargs – will be passed to the __init__ method of the socket class.
- term() None #
Close or terminate the context.
Context termination is performed in the following steps:
Any blocking operations currently in progress on sockets open within context shall raise
zmq.ContextTerminated
. With the exception of socket.close(), any further operations on sockets open within this context shall raisezmq.ContextTerminated
.- After interrupting all blocking calls, term shall block until the following conditions are satisfied:
All sockets open within context have been closed.
For each socket within context, all messages sent on the socket have either been physically transferred to a network peer, or the socket’s linger period set with the zmq.LINGER socket option has expired.
For further details regarding socket linger behaviour refer to libzmq documentation for ZMQ_LINGER.
This can be called to close the context by hand. If this is not called, the context will automatically be closed when it is garbage collected, in which case you may see a ResourceWarning about the unclosed context.
- underlying#
The address of the underlying libzmq context
Socket
#
- class zmq.Socket(ctx_or_socket: Context, socket_type: int, *, copy_threshold: int | None = None)#
- class zmq.Socket(*, shadow: Socket | int, copy_threshold: int | None = None)
- class zmq.Socket(ctx_or_socket: Socket)
The ZMQ socket object
To create a Socket, first create a Context:
ctx = zmq.Context.instance()
then call
ctx.socket(socket_type)
:s = ctx.socket(zmq.ROUTER)
Added in version 25: Sockets can now be shadowed by passing another Socket. This helps in creating an async copy of a sync socket or vice versa:
s = zmq.Socket(async_socket)
Which previously had to be:
s = zmq.Socket.shadow(async_socket.underlying)
- closed#
boolean - whether the socket has been closed. If True, you can no longer use this Socket.
- copy_threshold#
integer - size (in bytes) below which messages should always be copied. Zero-copy support has nontrivial overhead due to the need to coordinate garbage collection with the libzmq IO thread, so sending small messages (typically < 10s of kB) with
copy=False
is often more expensive than withcopy=True
. The initial default value is 65536 (64kB), a reasonable default based on testing.Defaults to
zmq.COPY_THRESHOLD
on socket construction. Settingzmq.COPY_THRESHOLD
will define the default value for any subsequently created sockets.Added in version 17.
- bind(addr)#
Bind the socket to an address.
This causes the socket to listen on a network port. Sockets on the other side of this connection will use
Socket.connect(addr)
to connect to this socket.Returns a context manager which will call unbind on exit.
Added in version 20.0: Can be used as a context manager.
Added in version 26.0: binding to port 0 can be used as a context manager for binding to a random port. The URL can be retrieved as
socket.last_endpoint
.- Parameters:
addr (str) – The address string. This has the form ‘protocol://interface:port’, for example ‘tcp://127.0.0.1:5555’. Protocols supported include tcp, udp, pgm, epgm, inproc and ipc. If the address is unicode, it is encoded to utf-8 first.
- bind_to_random_port(addr: str, min_port: int = 49152, max_port: int = 65536, max_tries: int = 100) int #
Bind this socket to a random port in a range.
If the port range is unspecified, the system will choose the port.
- Parameters:
addr (str) – The address string without the port to pass to
Socket.bind()
.min_port (int, optional) – The minimum port in the range of ports to try (inclusive).
max_port (int, optional) – The maximum port in the range of ports to try (exclusive).
max_tries (int, optional) – The maximum number of bind attempts to make.
- Returns:
port – The port the socket was bound to.
- Return type:
- Raises:
ZMQBindError – if
max_tries
reached before successful bind
- close(linger=None) None #
Close the socket.
If linger is specified, LINGER sockopt will be set prior to closing.
Note: closing a zmq Socket may not close the underlying sockets if there are undelivered messages. Only after all messages are delivered or discarded by reaching the socket’s LINGER timeout (default: forever) will the underlying sockets be closed.
This can be called to close the socket by hand. If this is not called, the socket will automatically be closed when it is garbage collected, in which case you may see a ResourceWarning about the unclosed socket.
- connect(addr)#
Connect to a remote 0MQ socket.
Returns a context manager which will call disconnect on exit.
Added in version 20.0: Can be used as a context manager.
- Parameters:
addr (str) – The address string. This has the form ‘protocol://interface:port’, for example ‘tcp://127.0.0.1:5555’. Protocols supported are tcp, udp, pgm, inproc and ipc. If the address is unicode, it is encoded to utf-8 first.
- disable_monitor() None #
Shutdown the PAIR socket (created using get_monitor_socket) that is serving socket events.
Added in version 14.4.
- disconnect(addr)#
Disconnect from a remote 0MQ socket (undoes a call to connect).
Added in version libzmq-3.2.
Added in version 13.0.
- Parameters:
addr (str) – The address string. This has the form ‘protocol://interface:port’, for example ‘tcp://127.0.0.1:5555’. Protocols supported are tcp, udp, pgm, inproc and ipc. If the address is unicode, it is encoded to utf-8 first.
- fileno() int #
Return edge-triggered file descriptor for this socket.
This is a read-only edge-triggered file descriptor for both read and write events on this socket. It is important that all available events be consumed when an event is detected, otherwise the read event will not trigger again.
Added in version 17.0.
- get(option: int)#
Get the value of a socket option.
See the 0MQ API documentation for details on specific options.
- get_hwm() int #
Get the High Water Mark.
On libzmq ≥ 3, this gets SNDHWM if available, otherwise RCVHWM
- get_monitor_socket(events: int | None = None, addr: str | None = None) zmq.Socket #
Return a connected PAIR socket ready to receive the event notifications.
Added in version libzmq-4.0.
Added in version 14.0.
- Parameters:
- Returns:
socket – The PAIR socket, connected and ready to receive messages.
- Return type:
- get_string(option: int, encoding='utf-8') str #
Get the value of a socket option.
See the 0MQ documentation for details on specific options.
- getsockopt(option: int)#
Get the value of a socket option.
See the 0MQ API documentation for details on specific options.
- getsockopt_string(option: int, encoding='utf-8') str #
Get the value of a socket option.
See the 0MQ documentation for details on specific options.
- property hwm: int#
Property for High Water Mark.
Setting hwm sets both SNDHWM and RCVHWM as appropriate. It gets SNDHWM if available, otherwise RCVHWM.
- join(group)#
Join a RADIO-DISH group
Only for DISH sockets.
libzmq and pyzmq must have been built with ZMQ_BUILD_DRAFT_API
Added in version 17.
- leave(group)#
Leave a RADIO-DISH group
Only for DISH sockets.
libzmq and pyzmq must have been built with ZMQ_BUILD_DRAFT_API
Added in version 17.
- monitor(addr, events: int = 65535)#
Start publishing socket events on inproc. See libzmq docs for zmq_monitor for details.
While this function is available from libzmq 3.2, pyzmq cannot parse monitor messages from libzmq prior to 4.0.
- poll(timeout: int | None = None, flags: int = <PollEvent.POLLIN: 1>) int #
Poll the socket for events.
See
Poller
to wait for multiple sockets at once.- Parameters:
- Returns:
event_mask – The poll event mask (POLLIN, POLLOUT), 0 if the timeout was reached without an event.
- Return type:
- recv(flags=0, copy: bool = True, track: bool = False)#
Receive a message.
With flags=NOBLOCK, this raises
ZMQError
if no messages have arrived; otherwise, this waits until a message arrives. SeePoller
for more general non-blocking I/O.- Parameters:
flags (int) – 0 or NOBLOCK.
copy (bool) – Should the message be received in a copying or non-copying manner? If False a Frame object is returned, if True a string copy of message is returned.
track (bool) – Should the message be tracked for notification that ZMQ has finished with it? (ignored if copy=True)
- Returns:
msg – The received message frame. If
copy
is False, then it will be a Frame, otherwise it will be bytes.- Return type:
- Raises:
ZMQError – for any of the reasons zmq_msg_recv might fail (including if NOBLOCK is set and no new messages have arrived).
- recv_json(flags: int = 0, **kwargs) list | str | int | float | dict #
Receive a Python object as a message using json to serialize.
Keyword arguments are passed on to json.loads
- Parameters:
flags (int) – Any valid flags for
Socket.recv()
.- Returns:
obj – The Python object that arrives as a message.
- Return type:
Python object
- Raises:
- recv_multipart(flags: int = 0, *, copy: Literal[True], track: bool = False) list[bytes] #
- recv_multipart(flags: int = 0, *, copy: Literal[False], track: bool = False) list[Frame]
- recv_multipart(flags: int = 0, *, track: bool = False) list[bytes]
- recv_multipart(flags: int = 0, copy: bool = True, track: bool = False) list[Frame] | list[bytes]
Receive a multipart message as a list of bytes or Frame objects
- Parameters:
flags (int, optional) – Any valid flags for
Socket.recv()
.copy (bool, optional) – Should the message frame(s) be received in a copying or non-copying manner? If False a Frame object is returned for each part, if True a copy of the bytes is made for each frame.
track (bool, optional) – Should the message frame(s) be tracked for notification that ZMQ has finished with it? (ignored if copy=True)
- Returns:
msg_parts – A list of frames in the multipart message; either Frames or bytes, depending on
copy
.- Return type:
- Raises:
- recv_pyobj(flags: int = 0) Any #
Receive a Python object as a message using pickle to serialize.
- Parameters:
flags (int) – Any valid flags for
Socket.recv()
.- Returns:
obj – The Python object that arrives as a message.
- Return type:
Python object
- Raises:
- recv_serialized(deserialize, flags=0, copy=True)#
Receive a message with a custom deserialization function.
Added in version 17.
- Parameters:
deserialize (callable) – The deserialization function to use. deserialize will be called with one argument: the list of frames returned by recv_multipart() and can return any object.
flags (int, optional) – Any valid flags for
Socket.recv()
.copy (bool, optional) – Whether to recv bytes or Frame objects.
- Returns:
obj – The object returned by the deserialization function.
- Return type:
- Raises:
- recv_string(flags: int = 0, encoding: str = 'utf-8') str #
Receive a unicode string, as sent by send_string.
- Parameters:
flags (int) – Any valid flags for
Socket.recv()
.encoding (str) – The encoding to be used
- Returns:
s – The Python unicode string that arrives as encoded bytes.
- Return type:
- Raises:
ZMQError – for any of the reasons
Socket.recv()
might fail
- send(data: Any, flags: int = 0, copy: bool = True, *, track: Literal[True], routing_id: int | None = None, group: str | None = None) MessageTracker #
- send(data: Any, flags: int = 0, copy: bool = True, *, track: Literal[False], routing_id: int | None = None, group: str | None = None) None
- send(data: Any, flags: int = 0, *, copy: bool = True, routing_id: int | None = None, group: str | None = None) None
- send(data: Any, flags: int = 0, copy: bool = True, track: bool = False, routing_id: int | None = None, group: str | None = None) MessageTracker | None
Send a single zmq message frame on this socket.
This queues the message to be sent by the IO thread at a later time.
With flags=NOBLOCK, this raises
ZMQError
if the queue is full; otherwise, this waits until space is available. SeePoller
for more general non-blocking I/O.- Parameters:
data (bytes, Frame, memoryview) – The content of the message. This can be any object that provides the Python buffer API (i.e.
memoryview(data)
can be called).flags (int) – 0, NOBLOCK, SNDMORE, or NOBLOCK|SNDMORE.
copy (bool) – Should the message be sent in a copying or non-copying manner.
track (bool) – Should the message be tracked for notification that ZMQ has finished with it? (ignored if copy=True)
routing_id (int) – For use with SERVER sockets
group (str) – For use with RADIO sockets
- Returns:
None (if
copy
or not track) – None if message was sent, raises an exception otherwise.MessageTracker (if track and not copy) – a MessageTracker object, whose
done
property will be False until the send is completed.
- Raises:
TypeError – If a unicode object is passed
ValueError – If
track=True
, but an untracked Frame is passed.ZMQError – If the send does not succeed for any reason (including if NOBLOCK is set and the outgoing queue is full).
Changed in version 17.0: DRAFT support for routing_id and group arguments.
- send_json(obj: Any, flags: int = 0, **kwargs) None #
Send a Python object as a message using json to serialize.
Keyword arguments are passed on to json.dumps
- Parameters:
obj (Python object) – The Python object to send
flags (int) – Any valid flags for
Socket.send()
- send_multipart(msg_parts: Sequence, flags: int = 0, copy: bool = True, track: bool = False, **kwargs)#
Send a sequence of buffers as a multipart message.
The zmq.SNDMORE flag is added to all msg parts before the last.
- Parameters:
msg_parts (iterable) – A sequence of objects to send as a multipart message. Each element can be any sendable object (Frame, bytes, buffer-providers)
flags (int, optional) – Any valid flags for
Socket.send()
. SNDMORE is added automatically for frames before the last.copy (bool, optional) – Should the frame(s) be sent in a copying or non-copying manner. If copy=False, frames smaller than self.copy_threshold bytes will be copied anyway.
track (bool, optional) – Should the frame(s) be tracked for notification that ZMQ has finished with it (ignored if copy=True).
- Returns:
None (if copy or not track)
MessageTracker (if track and not copy) – a MessageTracker object, whose
done
property will be False until the last send is completed.
- send_pyobj(obj: Any, flags: int = 0, protocol: int = 4, **kwargs) Frame | None #
Send a Python object as a message using pickle to serialize.
- Parameters:
obj (Python object) – The Python object to send.
flags (int) – Any valid flags for
Socket.send()
.protocol (int) – The pickle protocol number to use. The default is pickle.DEFAULT_PROTOCOL where defined, and pickle.HIGHEST_PROTOCOL elsewhere.
- send_serialized(msg, serialize, flags=0, copy=True, **kwargs)#
Send a message with a custom serialization function.
Added in version 17.
- Parameters:
msg (The message to be sent. Can be any object serializable by
serialize
.)serialize (callable) – The serialization function to use. serialize(msg) should return an iterable of sendable message frames (e.g. bytes objects), which will be passed to send_multipart.
flags (int, optional) – Any valid flags for
Socket.send()
.copy (bool, optional) – Whether to copy the frames.
- send_string(u: str, flags: int = 0, copy: bool = True, encoding: str = 'utf-8', **kwargs) Frame | None #
Send a Python unicode string as a message with an encoding.
0MQ communicates with raw bytes, so you must encode/decode text (str) around 0MQ.
- Parameters:
u (str) – The unicode string to send.
flags (int, optional) – Any valid flags for
Socket.send()
.encoding (str) – The encoding to be used
- set(option: int, optval)#
Set socket options.
See the 0MQ API documentation for details on specific options.
- Parameters:
Notes
Warning
All options other than zmq.SUBSCRIBE, zmq.UNSUBSCRIBE and zmq.LINGER only take effect for subsequent socket bind/connects.
- set_hwm(value: int) None #
Set the High Water Mark.
On libzmq ≥ 3, this sets both SNDHWM and RCVHWM
Warning
New values only take effect for subsequent socket bind/connects.
- set_string(option: int, optval: str, encoding='utf-8') None #
Set socket options with a unicode object.
This is simply a wrapper for setsockopt to protect from encoding ambiguity.
See the 0MQ documentation for details on specific options.
- setsockopt(option: int, optval)#
Set socket options.
See the 0MQ API documentation for details on specific options.
- Parameters:
Notes
Warning
All options other than zmq.SUBSCRIBE, zmq.UNSUBSCRIBE and zmq.LINGER only take effect for subsequent socket bind/connects.
- setsockopt_string(option: int, optval: str, encoding='utf-8') None #
Set socket options with a unicode object.
This is simply a wrapper for setsockopt to protect from encoding ambiguity.
See the 0MQ documentation for details on specific options.
- classmethod shadow(address: int | Socket) zmq.Socket #
Shadow an existing libzmq socket
address is a zmq.Socket or an integer (or FFI pointer) representing the address of the libzmq socket.
Added in version 14.1.
Added in version 25: Support for shadowing
zmq.Socket
objects, instead of just integer addresses.
- subscribe(topic: str | bytes) None #
Subscribe to a topic
Only for SUB sockets.
Added in version 15.3.
- unbind(addr)#
Unbind from an address (undoes a call to bind).
Added in version libzmq-3.2.
Added in version 13.0.
- Parameters:
addr (str) – The address string. This has the form ‘protocol://interface:port’, for example ‘tcp://127.0.0.1:5555’. Protocols supported are tcp, udp, pgm, inproc and ipc. If the address is unicode, it is encoded to utf-8 first.
- underlying#
The address of the underlying libzmq socket
Frame
#
- class zmq.Frame#
A zmq message Frame class for non-copying send/recvs and access to message properties.
A
zmq.Frame
wraps an underlyingzmq_msg_t
.Message properties can be accessed by treating a Frame like a dictionary (
frame["User-Id"]
).Added in version 14.4,: libzmq 4
Frames created by
recv(copy=False)
can be used to access message properties and attributes, such as the CURVE User-Id.For example:
frames = socket.recv_multipart(copy=False) user_id = frames[0]["User-Id"]
This class is used if you want to do non-copying send and recvs. When you pass a chunk of bytes to this class, e.g.
Frame(buf)
, the ref-count ofbuf
is increased by two: once because the Frame savesbuf
as an instance attribute and another because a ZMQ message is created that points to the buffer ofbuf
. This second ref-count increase makes sure thatbuf
lives until all messages that use it have been sent. Once 0MQ sends all the messages and it doesn’t need the buffer ofbuf
, 0MQ will callPy_DECREF(s)
.- Parameters:
data (object, optional) – any object that provides the buffer interface will be used to construct the 0MQ message data.
track (bool) – whether a MessageTracker should be created to track this object. Tracking a message has a cost at creation, because it creates a threadsafe Event object.
copy (bool) – default: use copy_threshold Whether to create a copy of the data to pass to libzmq or share the memory with libzmq. If unspecified, copy_threshold is used.
copy_threshold (int) – default:
zmq.COPY_THRESHOLD
If copy is unspecified, messages smaller than this many bytes will be copied and messages larger than this will be shared with libzmq.
- buffer#
A memoryview of the message contents.
- bytes#
The message content as a Python bytes object.
The first time this property is accessed, a copy of the message contents is made. From then on that same copy of the message is returned.
- get(option)#
Get a Frame option or property.
See the 0MQ API documentation for zmq_msg_get and zmq_msg_gets for details on specific options.
Added in version libzmq-3.2.
Added in version 13.0.
Changed in version 14.3: add support for zmq_msg_gets (requires libzmq-4.1) All message properties are strings.
Changed in version 17.0: Added support for
routing_id
andgroup
. Only available if draft API is enabled with libzmq >= 4.2.
- property group#
The RADIO-DISH group of the message.
Requires libzmq >= 4.2 and pyzmq built with draft APIs enabled.
Added in version 17.
- property routing_id#
The CLIENT-SERVER routing id of the message.
Requires libzmq >= 4.2 and pyzmq built with draft APIs enabled.
Added in version 17.
- set(option, value)#
Set a Frame option.
See the 0MQ API documentation for zmq_msg_set for details on specific options.
Added in version libzmq-3.2.
Added in version 13.0.
Changed in version 17.0: Added support for
routing_id
andgroup
. Only available if draft API is enabled with libzmq >= 4.2.
MessageTracker
#
- class zmq.MessageTracker(*towatch: tuple[MessageTracker | Event | Frame])#
A class for tracking if 0MQ is done using one or more messages.
When you send a 0MQ message, it is not sent immediately. The 0MQ IO thread sends the message at some later time. Often you want to know when 0MQ has actually sent the message though. This is complicated by the fact that a single 0MQ message can be sent multiple times using different sockets. This class allows you to track all of the 0MQ usages of a message.
- Parameters:
towatch (Event, MessageTracker, zmq.Frame) – This objects to track. This class can track the low-level Events used by the Message class, other MessageTrackers or actual Messages.
- property done#
Is 0MQ completely done with the message(s) being tracked?
Polling#
Poller
#
- class zmq.Poller#
A stateful poll interface that mirrors Python’s built-in poll.
- modify(socket, flags=<PollEvent.POLLIN|POLLOUT: 3>)#
Modify the flags for an already registered 0MQ socket or native fd.
- poll(timeout: int | None = None) list[tuple[Any, int]] #
Poll the registered 0MQ or native fds for I/O.
If there are currently events ready to be processed, this function will return immediately. Otherwise, this function will return as soon the first event is available or after timeout milliseconds have elapsed.
- Parameters:
timeout (int) – The timeout in milliseconds. If None, no
timeout
(infinite). This is in milliseconds to be compatible withselect.poll()
.- Returns:
events – The list of events that are ready to be processed. This is a list of tuples of the form
(socket, event_mask)
, where the 0MQ Socket or integer fd is the first element, and the poll event mask (POLLIN, POLLOUT) is the second. It is common to callevents = dict(poller.poll())
, which turns the list of tuples into a mapping ofsocket : event_mask
.- Return type:
- register(socket, flags=POLLIN | POLLOUT)#
Register a 0MQ socket or native fd for I/O monitoring.
register(s,0) is equivalent to unregister(s).
- Parameters:
socket (zmq.Socket or native socket) – A zmq.Socket or any Python object having a
fileno()
method that returns a valid file descriptor.flags (int) – The events to watch for. Can be POLLIN, POLLOUT or POLLIN|POLLOUT. If
flags=0
, socket will be unregistered.
- zmq.select(rlist, wlist, xlist, timeout=None)#
Return the result of poll as a lists of sockets ready for r/w/exception.
This has the same interface as Python’s built-in
select.select()
function.- Parameters:
timeout (float, optional) – The timeout in seconds. If None, no timeout (infinite). This is in seconds to be compatible with
select.select()
.rlist (list) – sockets/FDs to be polled for read events
wlist (list) – sockets/FDs to be polled for write events
xlist (list) – sockets/FDs to be polled for error events
- Returns:
rlist (list) – list of sockets or FDs that are readable
wlist (list) – list of sockets or FDs that are writable
xlist (list) – list of sockets or FDs that had error events (rare)
Constants#
All libzmq constants are available as top-level attributes
(zmq.PUSH
, etc.),
as well as via enums (zmq.SocketType.PUSH
, etc.).
Changed in version 23: constants for unavailable socket types or draft features will always be defined in pyzmq, whether the features themselves are available or not.
Added in version 23: Each category of zmq constant is now available as an IntEnum.
- zmq.COPY_THRESHOLD#
The global default “small message” threshold for copying when
copy=False
. Copying has a thread-coordination cost, so zero-copy only has a benefit for sufficiently large messages.
- enum zmq.SocketType(value)#
zmq socket types
Added in version 23.
- Member Type:
Valid values are as follows:
- PAIR = <SocketType.PAIR: 0>#
- PUB = <SocketType.PUB: 1>#
- SUB = <SocketType.SUB: 2>#
- REQ = <SocketType.REQ: 3>#
- REP = <SocketType.REP: 4>#
- DEALER = <SocketType.DEALER: 5>#
- ROUTER = <SocketType.ROUTER: 6>#
- PULL = <SocketType.PULL: 7>#
- PUSH = <SocketType.PUSH: 8>#
- XPUB = <SocketType.XPUB: 9>#
- XSUB = <SocketType.XSUB: 10>#
- STREAM = <SocketType.STREAM: 11>#
- SERVER = <SocketType.SERVER: 12>#
- CLIENT = <SocketType.CLIENT: 13>#
- RADIO = <SocketType.RADIO: 14>#
- DISH = <SocketType.DISH: 15>#
- GATHER = <SocketType.GATHER: 16>#
- SCATTER = <SocketType.SCATTER: 17>#
- DGRAM = <SocketType.DGRAM: 18>#
- PEER = <SocketType.PEER: 19>#
- CHANNEL = <SocketType.CHANNEL: 20>#
- enum zmq.SocketOption(value)#
Options for Socket.get/set
Added in version 23.
- Member Type:
Valid values are as follows:
- HWM = <SocketOption.HWM: 1>#
- AFFINITY = <SocketOption.AFFINITY: 4>#
- ROUTING_ID = <SocketOption.ROUTING_ID: 5>#
- SUBSCRIBE = <SocketOption.SUBSCRIBE: 6>#
- UNSUBSCRIBE = <SocketOption.UNSUBSCRIBE: 7>#
- RATE = <SocketOption.RATE: 8>#
- RECOVERY_IVL = <SocketOption.RECOVERY_IVL: 9>#
- SNDBUF = <SocketOption.SNDBUF: 11>#
- RCVBUF = <SocketOption.RCVBUF: 12>#
- RCVMORE = <SocketOption.RCVMORE: 13>#
- FD = <SocketOption.FD: 14>#
- EVENTS = <SocketOption.EVENTS: 15>#
- TYPE = <SocketOption.TYPE: 16>#
- LINGER = <SocketOption.LINGER: 17>#
- RECONNECT_IVL = <SocketOption.RECONNECT_IVL: 18>#
- BACKLOG = <SocketOption.BACKLOG: 19>#
- RECONNECT_IVL_MAX = <SocketOption.RECONNECT_IVL_MAX: 21>#
- MAXMSGSIZE = <SocketOption.MAXMSGSIZE: 22>#
- SNDHWM = <SocketOption.SNDHWM: 23>#
- RCVHWM = <SocketOption.RCVHWM: 24>#
- MULTICAST_HOPS = <SocketOption.MULTICAST_HOPS: 25>#
- RCVTIMEO = <SocketOption.RCVTIMEO: 27>#
- SNDTIMEO = <SocketOption.SNDTIMEO: 28>#
- LAST_ENDPOINT = <SocketOption.LAST_ENDPOINT: 32>#
- ROUTER_MANDATORY = <SocketOption.ROUTER_MANDATORY: 33>#
- TCP_KEEPALIVE = <SocketOption.TCP_KEEPALIVE: 34>#
- TCP_KEEPALIVE_CNT = <SocketOption.TCP_KEEPALIVE_CNT: 35>#
- TCP_KEEPALIVE_IDLE = <SocketOption.TCP_KEEPALIVE_IDLE: 36>#
- TCP_KEEPALIVE_INTVL = <SocketOption.TCP_KEEPALIVE_INTVL: 37>#
- IMMEDIATE = <SocketOption.IMMEDIATE: 39>#
- XPUB_VERBOSE = <SocketOption.XPUB_VERBOSE: 40>#
- ROUTER_RAW = <SocketOption.ROUTER_RAW: 41>#
- IPV6 = <SocketOption.IPV6: 42>#
- MECHANISM = <SocketOption.MECHANISM: 43>#
- PLAIN_SERVER = <SocketOption.PLAIN_SERVER: 44>#
- PLAIN_USERNAME = <SocketOption.PLAIN_USERNAME: 45>#
- PLAIN_PASSWORD = <SocketOption.PLAIN_PASSWORD: 46>#
- CURVE_SERVER = <SocketOption.CURVE_SERVER: 47>#
- CURVE_PUBLICKEY = <SocketOption.CURVE_PUBLICKEY: 48>#
- CURVE_SECRETKEY = <SocketOption.CURVE_SECRETKEY: 49>#
- CURVE_SERVERKEY = <SocketOption.CURVE_SERVERKEY: 50>#
- PROBE_ROUTER = <SocketOption.PROBE_ROUTER: 51>#
- REQ_CORRELATE = <SocketOption.REQ_CORRELATE: 52>#
- REQ_RELAXED = <SocketOption.REQ_RELAXED: 53>#
- CONFLATE = <SocketOption.CONFLATE: 54>#
- ZAP_DOMAIN = <SocketOption.ZAP_DOMAIN: 55>#
- ROUTER_HANDOVER = <SocketOption.ROUTER_HANDOVER: 56>#
- TOS = <SocketOption.TOS: 57>#
- CONNECT_ROUTING_ID = <SocketOption.CONNECT_ROUTING_ID: 61>#
- GSSAPI_SERVER = <SocketOption.GSSAPI_SERVER: 62>#
- GSSAPI_PRINCIPAL = <SocketOption.GSSAPI_PRINCIPAL: 63>#
- GSSAPI_SERVICE_PRINCIPAL = <SocketOption.GSSAPI_SERVICE_PRINCIPAL: 64>#
- GSSAPI_PLAINTEXT = <SocketOption.GSSAPI_PLAINTEXT: 65>#
- HANDSHAKE_IVL = <SocketOption.HANDSHAKE_IVL: 66>#
- SOCKS_PROXY = <SocketOption.SOCKS_PROXY: 68>#
- XPUB_NODROP = <SocketOption.XPUB_NODROP: 69>#
- BLOCKY = <SocketOption.BLOCKY: 70>#
- XPUB_MANUAL = <SocketOption.XPUB_MANUAL: 71>#
- XPUB_WELCOME_MSG = <SocketOption.XPUB_WELCOME_MSG: 72>#
- STREAM_NOTIFY = <SocketOption.STREAM_NOTIFY: 73>#
- INVERT_MATCHING = <SocketOption.INVERT_MATCHING: 74>#
- HEARTBEAT_IVL = <SocketOption.HEARTBEAT_IVL: 75>#
- HEARTBEAT_TTL = <SocketOption.HEARTBEAT_TTL: 76>#
- HEARTBEAT_TIMEOUT = <SocketOption.HEARTBEAT_TIMEOUT: 77>#
- XPUB_VERBOSER = <SocketOption.XPUB_VERBOSER: 78>#
- CONNECT_TIMEOUT = <SocketOption.CONNECT_TIMEOUT: 79>#
- TCP_MAXRT = <SocketOption.TCP_MAXRT: 80>#
- THREAD_SAFE = <SocketOption.THREAD_SAFE: 81>#
- MULTICAST_MAXTPDU = <SocketOption.MULTICAST_MAXTPDU: 84>#
- VMCI_BUFFER_SIZE = <SocketOption.VMCI_BUFFER_SIZE: 85>#
- VMCI_BUFFER_MIN_SIZE = <SocketOption.VMCI_BUFFER_MIN_SIZE: 86>#
- VMCI_BUFFER_MAX_SIZE = <SocketOption.VMCI_BUFFER_MAX_SIZE: 87>#
- VMCI_CONNECT_TIMEOUT = <SocketOption.VMCI_CONNECT_TIMEOUT: 88>#
- USE_FD = <SocketOption.USE_FD: 89>#
- GSSAPI_PRINCIPAL_NAMETYPE = <SocketOption.GSSAPI_PRINCIPAL_NAMETYPE: 90>#
- GSSAPI_SERVICE_PRINCIPAL_NAMETYPE = <SocketOption.GSSAPI_SERVICE_PRINCIPAL_NAMETYPE: 91>#
- BINDTODEVICE = <SocketOption.BINDTODEVICE: 92>#
- TCP_ACCEPT_FILTER = <SocketOption.TCP_ACCEPT_FILTER: 38>#
- IPC_FILTER_PID = <SocketOption.IPC_FILTER_PID: 58>#
- IPC_FILTER_UID = <SocketOption.IPC_FILTER_UID: 59>#
- IPC_FILTER_GID = <SocketOption.IPC_FILTER_GID: 60>#
- IPV4ONLY = <SocketOption.IPV4ONLY: 31>#
- ZAP_ENFORCE_DOMAIN = <SocketOption.ZAP_ENFORCE_DOMAIN: 93>#
- LOOPBACK_FASTPATH = <SocketOption.LOOPBACK_FASTPATH: 94>#
- METADATA = <SocketOption.METADATA: 95>#
- MULTICAST_LOOP = <SocketOption.MULTICAST_LOOP: 96>#
- ROUTER_NOTIFY = <SocketOption.ROUTER_NOTIFY: 97>#
- XPUB_MANUAL_LAST_VALUE = <SocketOption.XPUB_MANUAL_LAST_VALUE: 98>#
- SOCKS_USERNAME = <SocketOption.SOCKS_USERNAME: 99>#
- SOCKS_PASSWORD = <SocketOption.SOCKS_PASSWORD: 100>#
- IN_BATCH_SIZE = <SocketOption.IN_BATCH_SIZE: 101>#
- OUT_BATCH_SIZE = <SocketOption.OUT_BATCH_SIZE: 102>#
- WSS_KEY_PEM = <SocketOption.WSS_KEY_PEM: 103>#
- WSS_CERT_PEM = <SocketOption.WSS_CERT_PEM: 104>#
- WSS_TRUST_PEM = <SocketOption.WSS_TRUST_PEM: 105>#
- WSS_HOSTNAME = <SocketOption.WSS_HOSTNAME: 106>#
- WSS_TRUST_SYSTEM = <SocketOption.WSS_TRUST_SYSTEM: 107>#
- ONLY_FIRST_SUBSCRIBE = <SocketOption.ONLY_FIRST_SUBSCRIBE: 108>#
- RECONNECT_STOP = <SocketOption.RECONNECT_STOP: 109>#
- HELLO_MSG = <SocketOption.HELLO_MSG: 110>#
- DISCONNECT_MSG = <SocketOption.DISCONNECT_MSG: 111>#
- PRIORITY = <SocketOption.PRIORITY: 112>#
- BUSY_POLL = <SocketOption.BUSY_POLL: 113>#
- HICCUP_MSG = <SocketOption.HICCUP_MSG: 114>#
- XSUB_VERBOSE_UNSUBSCRIBE = <SocketOption.XSUB_VERBOSE_UNSUBSCRIBE: 115>#
- TOPICS_COUNT = <SocketOption.TOPICS_COUNT: 116>#
- NORM_MODE = <SocketOption.NORM_MODE: 117>#
- NORM_UNICAST_NACK = <SocketOption.NORM_UNICAST_NACK: 118>#
- NORM_BUFFER_SIZE = <SocketOption.NORM_BUFFER_SIZE: 119>#
- NORM_SEGMENT_SIZE = <SocketOption.NORM_SEGMENT_SIZE: 120>#
- NORM_BLOCK_SIZE = <SocketOption.NORM_BLOCK_SIZE: 121>#
- NORM_NUM_PARITY = <SocketOption.NORM_NUM_PARITY: 122>#
- NORM_NUM_AUTOPARITY = <SocketOption.NORM_NUM_AUTOPARITY: 123>#
- NORM_PUSH = <SocketOption.NORM_PUSH: 124>#
- enum zmq.Flag(value)#
Send/recv flags
Added in version 23.
- Member Type:
Valid values are as follows:
- DONTWAIT = <Flag.DONTWAIT: 1>#
- SNDMORE = <Flag.SNDMORE: 2>#
- enum zmq.PollEvent(value)#
Which events to poll for in poll methods
- Member Type:
Valid values are as follows:
- POLLIN = <PollEvent.POLLIN: 1>#
- POLLOUT = <PollEvent.POLLOUT: 2>#
- POLLERR = <PollEvent.POLLERR: 4>#
- POLLPRI = <PollEvent.POLLPRI: 8>#
- enum zmq.ContextOption(value)#
Options for Context.get/set
Added in version 23.
- Member Type:
Valid values are as follows:
- IO_THREADS = <ContextOption.IO_THREADS: 1>#
- MAX_SOCKETS = <ContextOption.MAX_SOCKETS: 2>#
- SOCKET_LIMIT = <ContextOption.SOCKET_LIMIT: 3>#
- THREAD_SCHED_POLICY = <ContextOption.THREAD_SCHED_POLICY: 4>#
- MAX_MSGSZ = <ContextOption.MAX_MSGSZ: 5>#
- MSG_T_SIZE = <ContextOption.MSG_T_SIZE: 6>#
- THREAD_AFFINITY_CPU_ADD = <ContextOption.THREAD_AFFINITY_CPU_ADD: 7>#
- THREAD_AFFINITY_CPU_REMOVE = <ContextOption.THREAD_AFFINITY_CPU_REMOVE: 8>#
- THREAD_NAME_PREFIX = <ContextOption.THREAD_NAME_PREFIX: 9>#
- enum zmq.MessageOption(value)#
Options on zmq.Frame objects
Added in version 23.
- Member Type:
Valid values are as follows:
- MORE = <MessageOption.MORE: 1>#
- SHARED = <MessageOption.SHARED: 3>#
- SRCFD = <MessageOption.SRCFD: 2>#
- enum zmq.Event(value)#
Socket monitoring events
Added in version 23.
- Member Type:
Valid values are as follows:
- PROTOCOL_ERROR_ZMTP_UNSPECIFIED = <Event.PROTOCOL_ERROR_ZMTP_UNSPECIFIED: 268435456>#
- PROTOCOL_ERROR_ZAP_UNSPECIFIED = <Event.PROTOCOL_ERROR_ZAP_UNSPECIFIED: 536870912>#
- CONNECTED = <Event.CONNECTED: 1>#
- CONNECT_DELAYED = <Event.CONNECT_DELAYED: 2>#
- CONNECT_RETRIED = <Event.CONNECT_RETRIED: 4>#
- LISTENING = <Event.LISTENING: 8>#
- BIND_FAILED = <Event.BIND_FAILED: 16>#
- ACCEPTED = <Event.ACCEPTED: 32>#
- ACCEPT_FAILED = <Event.ACCEPT_FAILED: 64>#
- CLOSED = <Event.CLOSED: 128>#
- CLOSE_FAILED = <Event.CLOSE_FAILED: 256>#
- DISCONNECTED = <Event.DISCONNECTED: 512>#
- MONITOR_STOPPED = <Event.MONITOR_STOPPED: 1024>#
- HANDSHAKE_FAILED_NO_DETAIL = <Event.HANDSHAKE_FAILED_NO_DETAIL: 2048>#
- HANDSHAKE_SUCCEEDED = <Event.HANDSHAKE_SUCCEEDED: 4096>#
- HANDSHAKE_FAILED_PROTOCOL = <Event.HANDSHAKE_FAILED_PROTOCOL: 8192>#
- HANDSHAKE_FAILED_AUTH = <Event.HANDSHAKE_FAILED_AUTH: 16384>#
- PIPES_STATS = <Event.PIPES_STATS: 65536>#
- enum zmq.NormMode(value)#
Values for zmq.NORM_MODE socket option
Added in version 26.
Added in version libzmq-4.3.5: (draft)
- Member Type:
Valid values are as follows:
- FIXED = <NormMode.FIXED: 0>#
- CC = <NormMode.CC: 1>#
- CCL = <NormMode.CCL: 2>#
- CCE = <NormMode.CCE: 3>#
- CCE_ECNONLY = <NormMode.CCE_ECNONLY: 4>#
- enum zmq.RouterNotify(value)#
Values for zmq.ROUTER_NOTIFY socket option
Added in version 26.
Added in version libzmq-4.3.0: (draft)
- Member Type:
Valid values are as follows:
- CONNECT = <RouterNotify.CONNECT: 1>#
- DISCONNECT = <RouterNotify.DISCONNECT: 2>#
- enum zmq.ReconnectStop(value)#
Select behavior for socket.reconnect_stop
Added in version 25.
- Member Type:
Valid values are as follows:
- CONN_REFUSED = <ReconnectStop.CONN_REFUSED: 1>#
- HANDSHAKE_FAILED = <ReconnectStop.HANDSHAKE_FAILED: 2>#
- AFTER_DISCONNECT = <ReconnectStop.AFTER_DISCONNECT: 4>#
- enum zmq.SecurityMechanism(value)#
Security mechanisms (as returned by
socket.get(zmq.MECHANISM)
)Added in version 23.
- Member Type:
Valid values are as follows:
- NULL = <SecurityMechanism.NULL: 0>#
- PLAIN = <SecurityMechanism.PLAIN: 1>#
- CURVE = <SecurityMechanism.CURVE: 2>#
- GSSAPI = <SecurityMechanism.GSSAPI: 3>#
- enum zmq.DeviceType(value)#
Device type constants for zmq.device
- Member Type:
Valid values are as follows:
- STREAMER = <DeviceType.STREAMER: 1>#
- FORWARDER = <DeviceType.FORWARDER: 2>#
- QUEUE = <DeviceType.QUEUE: 3>#
- enum zmq.Errno(value)#
libzmq error codes
Added in version 23.
- Member Type:
Valid values are as follows:
- EAGAIN = <Errno.EAGAIN: 11>#
- EFAULT = <Errno.EFAULT: 14>#
- EINVAL = <Errno.EINVAL: 22>#
- ENOTSUP = <Errno.ENOTSUP: 95>#
- EPROTONOSUPPORT = <Errno.EPROTONOSUPPORT: 93>#
- ENOBUFS = <Errno.ENOBUFS: 105>#
- ENETDOWN = <Errno.ENETDOWN: 100>#
- EADDRINUSE = <Errno.EADDRINUSE: 98>#
- EADDRNOTAVAIL = <Errno.EADDRNOTAVAIL: 99>#
- ECONNREFUSED = <Errno.ECONNREFUSED: 111>#
- EINPROGRESS = <Errno.EINPROGRESS: 115>#
- ENOTSOCK = <Errno.ENOTSOCK: 88>#
- EMSGSIZE = <Errno.EMSGSIZE: 90>#
- EAFNOSUPPORT = <Errno.EAFNOSUPPORT: 97>#
- ENETUNREACH = <Errno.ENETUNREACH: 101>#
- ECONNABORTED = <Errno.ECONNABORTED: 103>#
- ECONNRESET = <Errno.ECONNRESET: 104>#
- ENOTCONN = <Errno.ENOTCONN: 107>#
- ETIMEDOUT = <Errno.ETIMEDOUT: 110>#
- EHOSTUNREACH = <Errno.EHOSTUNREACH: 113>#
- ENETRESET = <Errno.ENETRESET: 102>#
- EFSM = <Errno.EFSM: 156384763>#
- ENOCOMPATPROTO = <Errno.ENOCOMPATPROTO: 156384764>#
- ETERM = <Errno.ETERM: 156384765>#
- EMTHREAD = <Errno.EMTHREAD: 156384766>#
Exceptions#
ZMQError
#
ZMQVersionError
#
- class zmq.ZMQVersionError(min_version: str, msg: str = 'Feature')#
Raised when a feature is not provided by the linked version of libzmq.
Added in version 14.2.
- add_note()#
Exception.add_note(note) – add a note to the exception
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
Again
#
- class zmq.Again(errno='ignored', msg='ignored')#
Wrapper for zmq.EAGAIN
Added in version 13.0.
ContextTerminated
#
- class zmq.ContextTerminated(errno='ignored', msg='ignored')#
Wrapper for zmq.ETERM
Added in version 13.0.
NotDone
#
- class zmq.NotDone#
Raised when timeout is reached while waiting for 0MQ to finish with a Message
See also
MessageTracker.wait
object for tracking when ZeroMQ is done
ZMQBindError
#
- class zmq.ZMQBindError#
An error for
Socket.bind_to_random_port()
.See also
Functions#
- zmq.zmq_version_info() tuple[int, int, int] #
Return the version of ZeroMQ itself as a 3-tuple of ints.
- zmq.pyzmq_version_info() tuple[int, int, int] | tuple[int, int, int, float] #
return the pyzmq version as a tuple of at least three numbers
If pyzmq is a development version,
inf
will be appended after the third integer.
- zmq.has(capability) bool #
Check for zmq capability by name (e.g. ‘ipc’, ‘curve’)
Added in version libzmq-4.1.
Added in version 14.1.
- zmq.device(device_type: int, frontend: zmq.Socket, backend: zmq.Socket = None)#
Start a zeromq device.
Deprecated since version libzmq-3.2: Use zmq.proxy
- zmq.proxy(frontend: zmq.Socket, backend: zmq.Socket, capture: zmq.Socket = None)#
Start a zeromq proxy (replacement for device).
Added in version libzmq-3.2.
Added in version 13.0.
- zmq.proxy_steerable(frontend: zmq.Socket, backend: zmq.Socket, capture: zmq.Socket = None, control: zmq.Socket = None)#
Start a zeromq proxy with control flow.
Added in version libzmq-4.1.
Added in version 18.0.
- zmq.curve_public(secret_key) bytes #
Compute the public key corresponding to a secret key for use with zmq.CURVE security
Requires libzmq (≥ 4.2) to have been built with CURVE support.
- Parameters:
private – The private key as a 40 byte z85-encoded bytestring
- Returns:
The public key as a 40 byte z85-encoded bytestring
- Return type:
- zmq.curve_keypair() tuple[bytes, bytes] #
generate a Z85 key pair for use with zmq.CURVE security
Requires libzmq (≥ 4.0) to have been built with CURVE support.
Added in version libzmq-4.0.
Added in version 14.0.
- Returns:
public (bytes) – The public key as 40 byte z85-encoded bytestring.
private (bytes) – The private key as 40 byte z85-encoded bytestring.
- zmq.get_includes()#
Return a list of directories to include for linking against pyzmq with cython.
- zmq.get_library_dirs()#
Return a list of directories used to link against pyzmq’s bundled libzmq.