How to check if memcached is running and start it if not from python?

memcached, python

Solution

The best way to check may depend on your platform. Here's some methods you could try:

- Try to connect to the memcached server. If a connection fails, assume that the server is not running.

- If you expect memcached to be running locally, look for a PID file. On Debian this is usually located at `/var/run/memcached.pid` and contains the process id of the running memcached daemon. To be extra sure you could read the PID contained in the file and verify that a process with this PID is still running.

- Use the `subprocess` module to run a command which can directly check for a locally running daemon. eg. Run the command `pidof memcached` using `subprocess` and check the return code.

Problem

I'm developing a web application using python and memcached. First I want to start memcached from my python program, and if I'm right `subprocess.Popen(["memcached"]);` will do it. What really bothers me is how to check if memcached is already running in the background. I want something like ``` if check_memcached(): start_memcached(); ``` The `check_memcached()` function should return true if memcached is not already running. Anybody got any idea how to do this?

Original source