I'm looking for a way to check if a redis instance (on a local machine with default port) is running or not. If not, I want to start it from my python code.
3 Answers
If you start a redis client you can first try to ping -- if you get a redis.exceptions.ConnectionError then the service is probably not running. Below is an example of such a function. There are other ways to get a similar or more robust result -- this one is just an easy approach. Also note that this doesn't tell you if a particular key is setup or anything about the redis setup. It only tells you if there is a live redis server on localhost or not.
def redisLocalhostLive():
redtest = redis.StrictRedis() # non-default ports could go here
try:
return redtest.ping()
except ConnectionError:
return False
Comments
One approach is to use psutil, which is a Python module that provides a cross-platform way to retrieve info on running processes.
>>> import psutil
>>> processes = psutil.process_iter() # Get all running processes
>>> if any(process.name == 'redis-server' for process in processes):
... print "redis is running"
...
redis is running