how to invoke the shell command and then get the result in python

Nick Craig-Wood nick at craig-wood.com
Tue Dec 5 05:30:05 EST 2006


petercable at gmail.com <petercable at gmail.com> wrote:
>  Also, for a wrapper around popen, try commands:
> 
>    import commands
> 
>    pattern = raw_input('pattern to search? ')
>    print commands.getoutput('grep %s *.txt' % pattern)

What if I entered "; rm -rf * ;" as my pattern?

Don't ever pass user input (from file/web/raw_input) to the shell if
you want to write a secure program!

If you use subprocess then you can use a sequence of args to bypass
the shell rather than a string to be passed to the shell.  That will
get over lots of shell escaping problems too.  Eg

from subprocess import Popen, PIPE
from glob import glob
pattern = raw_input('pattern to search? ')
files = glob("*.txt")
output = Popen(["grep", pattern] + files, stdout=PIPE).communicate()[0]
print output

You can also use subprocess to read the return code of the command and
its stderr both of which you'll need if you are programming
defensively!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list