cool breeze cool breeze - 1 year ago 100
Python Question

How to get the response of calling a redis command

I'm using python 2.6.6 and I can't upgrade.

I had it working fine with subprocess.check_output but I didn't realize we are using python 2.6.6 and I can't upgrade it on my end.

I tried this:

command = "redis-cli hget some_key some_field"
command_output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]

But I don't think I am passing in the commands correctly, the docs have somethign like:

subprocess.Popen( ['ls', 'li'], ..)

Answer Source

Yup, you should use lists to give your command line.

command = ["redis-cli", "hget", "some_key", "some_field"]
command_output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]

Relevant from Moses Koledoye@

command.split() does the conversion to list.

The reason they did this is pretty simple: every argument given will be directly forward to the redis-cli program. Let's go in details:

Imagine you have this:

key = raw_input("Please give me the key:")
os.system('redis-cli bla bla %s' % key)  # DON'T DO THIS AT HOME.

Now imagine I am a malicious guy, and I input the following: || echo "hacked by h4x0r". The final command will look like this :

redis-cli bla bla || echo "hacked by h4x0r"

Use list. Really.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download