---
source_url: https://www.pubnub.com/docs/sdks/python/quickstart
title: "Quickstart: PubNub Python SDK"
updated_at: 2026-11-25T12:28:11.000Z
sdk_name: PubNub Python SDK
sdk_version: 10.9.1
description: Send your first message with the PubNub Python SDK. Install it with pip, subscribe to a channel, publish, and see the message arrive.
---

# Quickstart: PubNub Python SDK

PubNub Python SDK, use the latest version: 10.9.1

Install:

```bash
pip install pubnub==10.9.1
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

In this quickstart you write a "Hello, World" Python script. The script connects to PubNub, subscribes to a channel, and publishes a message that arrives in the same script. You need one Python file and a terminal.

To set up a virtual environment or install from source instead, refer to [Set up your Python environment](https://www.pubnub.com/docs/sdks/python/set-up-your-environment.md).

## Before you begin

You need Python 3.9 or later and a PubNub account.

### Get your PubNub keys

Get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal
* Create an app
* Find your publish and subscribe keys in the app dashboard

When you create an app, PubNub generates a keyset. Use separate keysets for development and production.

## Install

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

Install the SDK with `pip`:

```bash
pip install 'pubnub>=10.9.1'
```

## Initialize

Create a new Python script with the following content. This is the minimum configuration for sending and receiving messages.

Replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

```python
# Import required modules
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

# Set up PubNub configuration
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'  # Replace with your subscribe key
pnconfig.publish_key = 'demo'    # Replace with your publish key
pnconfig.user_id = 'python-user'
pnconfig.enable_subscribe = True

# Create a PubNub instance
pubnub = PubNub(pnconfig)
```

Set the `user_id` to identify the user or device that connects to PubNub, and keep it unchanged for the lifetime of that user or device. Without a `user_id`, the `PubNub` constructor raises an `AssertionError`.

See the [Configuration](https://www.pubnub.com/docs/sdks/python/api-reference/configuration.md) section of the SDK documentation.

## Subscribe

Listeners let your app react to events and messages. The Python SDK reports connection status changes to a listener. Add this code to set up a status listener:

```python
from pubnub.pubnub import SubscribeListener

# Create a custom listener for status events
class StatusListener(SubscribeListener):
    def status(self, pubnub, status):
        # This method is called when the status of the connection changes
        print(f'Status: {status.category.name}')

# Add the listener to your PubNub instance
status_listener = StatusListener()
pubnub.add_listener(status_listener)
```

To receive messages sent to a channel, subscribe to it. Create a subscription for the channel, set a message handler, and activate the subscription:

```python
# Define the channel you want to subscribe to
my_channel = 'my-channel'

# Create a subscription for the channel
subscription = pubnub.channel(my_channel).subscription()

# Set up a message handler
subscription.on_message = lambda message: print(f'Message received: {message.message}')

# Subscribe to the channel
subscription.subscribe()

print(f'Subscribed to channel: {my_channel}')
```

See the [Subscribe](https://www.pubnub.com/docs/sdks/python/api-reference/subscribe.md) section of the SDK documentation.

## Publish

When you publish a message to a channel, PubNub delivers it to every subscriber of that channel. A message can be any JSON-serializable data smaller than 32 KiB, such as an object, array, integer, or string.

```python
import time
from pubnub.exceptions import PubNubException

# Wait for a moment so the subscription is active
time.sleep(1)

# Create a message
message = {
    'msg': 'Hello from PubNub Python SDK!'
}

# Publish the message to the channel
try:
    envelope = pubnub.publish().channel(my_channel).message(message).sync()
    print(f'Published message with timetoken: {envelope.result.timetoken}')
except PubNubException as e:
    print(f'Publish failed: {e}')
```

The `sync()` method waits for the response before the script continues. For other ways to run a request, see [Publish](https://www.pubnub.com/docs/sdks/python/api-reference/publish.md).

## Run

The script below combines the code from the previous steps. Save it as `pubnub_demo.py`, replace the placeholder keys, and run it from your terminal:

```python
import time
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub, SubscribeListener
from pubnub.exceptions import PubNubException

# Step 1: Initialize PubNub with configuration
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'  # Replace with your subscribe key
pnconfig.publish_key = 'demo'    # Replace with your publish key
pnconfig.user_id = 'python-user'
pnconfig.ssl = True              # Enable SSL for secure connection
pnconfig.enable_subscribe = True
pnconfig.daemon = True  # If using in a long-running app

pubnub = PubNub(pnconfig)

# Step 2: Create a status listener
class StatusListener(SubscribeListener):
    def status(self, pubnub, status):
        print(f'Status: {status.category.name}')

# Step 3: Add the listener
status_listener = StatusListener()
pubnub.add_listener(status_listener)

# Step 4: Define the channel and create a subscription
my_channel = 'my-channel'
subscription = pubnub.channel(my_channel).subscription()

# Step 5: Set up a message handler for the subscription
subscription.on_message = lambda message: print(f'Message received: {message.message}')

# Step 6: Subscribe to the channel
subscription.subscribe()
print(f'Subscribed to channel: {my_channel}')

# Wait for connection to establish before publishing
time.sleep(1)

# Step 7: Create and publish a message
message = {
    'msg': 'Hello from PubNub Python SDK!'
}

try:
    envelope = pubnub.publish().channel(my_channel).message(message).sync()
    print(f'Published message with timetoken: {envelope.result.timetoken}')
except PubNubException as e:
    print(f'Publish failed: {e}')

# Keep the script running to receive messages
time.sleep(3)

# Step 8: Clean up before exiting
pubnub.stop()
print('Cleanup complete.')
```

```bash
python pubnub_demo.py
```

The script prints output similar to this:

```text
Subscribed to channel: my-channel
Status: PNConnectedCategory
Message received: {'msg': 'Hello from PubNub Python SDK!'}
Published message with timetoken: 16967543908123456
Cleanup complete.
```

You receive the message you published because you are subscribed to the same channel.

If the output differs, see [Troubleshooting](https://www.pubnub.com/docs/sdks/python/troubleshooting.md). If it shows a 403 (Access Denied) error, your keyset may have Access Manager enabled. See [Configure access control](https://www.pubnub.com/docs/security/access-control/configure-access-control.md).

## Next steps

You created your first PubNub Python application. Here is what to explore next:

* Build a feature with the [how-tos](https://www.pubnub.com/docs/sdks/python.md), such as showing who is online or loading message history.
* Add [Channel Groups](https://www.pubnub.com/docs/sdks/python/api-reference/channel-groups.md) to organize your channels.
* Try out [Presence](https://www.pubnub.com/docs/sdks/python/api-reference/presence.md) to track online and offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/python/api-reference/message-persistence.md) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/python/api-reference/access-manager.md) to secure your channels.
* Explore the [GitHub repository](https://github.com/pubnub/python/) and its [examples](https://github.com/pubnub/python/tree/master/examples) for more code samples.
* Check the [SDK reference documentation](https://www.pubnub.com/docs/sdks/python/api-reference/configuration.md) for detailed API information.
* Join the [Discord community](https://discord.gg/pubnub), visit the [support portal](https://support.pubnub.com/), or ask the AI assistant (the magnifying glass icon at the top of the page).

Last updated at: 2026-11-25T12:28:11.000Z
