Python & Redis PUB/SUB

I recently had an issue where I have three Python scripts that need to be started on my RaspberryPI when it boots. Script 1 is identifying what serial devices are attached to the PI, saving the information to a database. Scripts 2 and 3 need to use this information, so have to wait until script 1 has completed.

I wasn’t sure of the best way to do this but I thought of a method that lets me experiment with Redis PUB/SUB which I’ve wanted an excuse to use for a while!

My Scripts

The redis-py Python Client is well documented and really easy to use. I created a function, RedisCheck(), that Scripts 2 & 3 call when they start. The function subscribes to a Redis channel called ‘startScripts’. It then goes into a loop until it receives a ‘START’ message on that channel. Once this is received the main scripts can continue with their primary jobs.

Script1 is very simple, the ‘START’ message is PUBLISHED via the ‘startScripts’ channel once the main work is done.

The following code should demonstrate how easy the code was to write and it works really well.

RedisCheck() SUB for Scripts 2 & 3

Script 1 PUB START

Publishing Via The Command Line

Another nice thing I found was how easy it was to PUBLISH the ‘START’ message using the redis-cli. All I do is run:

# redis-cli

> PUBLISH startScripts START

This is really useful if I’m debugging and so easy to do. Overall I really like Redis.

Leave a Reply

Your email address will not be published. Required fields are marked *