---
id: mqtt-python
title: Python
sidebar_label: Python
sidebar_position: 2
---

### Sending/receiving messages on mosquitto server using python

Here is an example publish message in python:

```python
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
from random import randrange, uniform
import time

client = mqtt.Client("some_client_id")
client.connect('localhost')

while True:
    randNumber = uniform(20.0, 21.0)
    client.publish("env/test/TEMPERATURE", randNumber)
    print("Just published " + str(randNumber) + " to topic TEMPERATURE")
    time.sleep(1)
```

Here is example subscribe in python:

```python
#!/usr/bin/env python3

import paho.mqtt.client as paho

def on_message(mosq, obj, msg):
    print("%-20s %d %s" % (msg.topic, msg.qos, msg.payload))
    mosq.publish('pong', 'ack', 0)

def on_publish(mosq, obj, mid):
    pass

if __name__ == '__main__':
    client = paho.Client()
    client.on_message = on_message
    client.on_publish = on_publish

    client.connect("localhost", 1883, 60)

    client.subscribe("env/test/TEMPERATURE", 0)

    while client.loop() == 0:
        pass
```
