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

Fredrik Lundh fredrik at pythonware.com
Tue Dec 5 03:41:28 EST 2006


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)

that's not quite as portable as the other alternatives, though.  "grep" 
is at least available for non-Unix platforms, but "commands" requires a 
unix shell.

for Python 2.5 and later, you could use:

    def getoutput(cmd):
        from subprocess import Popen, PIPE, STDOUT
        p = Popen(cmd, stdout=PIPE, stderr=STDOUT,
	   shell=isinstance(cmd, basestring))
        return p.communicate()[0]

    print getoutput(["grep", pattern, glob.glob("*.txt")])

which, if given a list instead of a string, passes the arguments
right through to the underlying process, without going through the
shell (consider searching for "-" or ";rm" with the original code).

</F>




More information about the Python-list mailing list