The Pulsar Python client


The Pulsar Python client library is a wrapper over the existing C++ client library and exposes all of the same features. You can find the code in the python subdirectory of the C++ client code.

Installation

You can install the pulsar-client library either via PyPi, using pip, or by building the library from source.

Installation using pip

To install the pulsar-client library as a pre-built package using the pip package manager:

$ pip install pulsar-client

Installation via PyPi is available for the following Python versions:

Platform Supported Python versions
MacOS 10.12 (Sierra) and 10.13 (High Sierra) 2.7, 3.6
Linux 2.7, 3.3, 3.4, 3.5, 3.6

Installing from source

To install the pulsar-client library by building from source, follow these instructions and compile the Pulsar C++ client library. That will also build the Python binding for the library.

To install the built Python bindings:

$ git clone https://github.com/apache/pulsar
$ cd pulsar/pulsar-client-cpp/python
$ sudo python setup.py install

API Reference

The complete Python API reference is available at api/python.

Examples

Below you’ll find a variety of Python code examples for the pulsar-client library.

Producer example

This creates a Python producer for the persistent://sample/standalone/ns/my-topic topic and send 10 messages on that topic:

import pulsar

TOPIC = 'persistent://sample/standalone/ns/my-topic'
PULSAR_SERVICE_URL = 'pulsar://localhost:6650'

client = pulsar.Client(PULSAR_SERVICE_URL)

producer = client.create_producer(TOPIC)

for i in range(10):
    producer.send('Hello-%d' % i)

client.close()

Consumer example

This creates a consumer with the my-sub subscription on the persistent://sample/standalone/ns/my-topic topic, listen for incoming messages, print the content and ID of messages that arrive, and acknowledge each message to the Pulsar broker:

SUBSCRIPTION = 'my-sub'

consumer = client.subscribe(TOPIC, SUBSCRIPTION)

while True:
    msg = consumer.receive()
    print("Received message '%s' id='%s'", msg.data(), msg.message_id())
    consumer.acknowledge(msg)

client.close()