Python & Redis PUB/SUB

John Grant
Jul 20, 2017 · 1 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store