getting output from a command into a list to work with

Peter Otten __peter__ at web.de
Mon May 21 03:12:42 EDT 2007


Anthony Irwin wrote:

> I would like to run the command below and have each line from the
> output stored as an element in a list.
> 
> find /some/path/ -maxdepth 1 -type f -size +100000k -exec ls -1 '{}' \
> 
> The reason for this is so I can then work on each file in the
> following manner
> 
> var = command
> 
> for i in var:
>      # do stuff to file code here
> 
> not sure the best way to get the output of the command so each line of
> output is one element in the list.


from subprocess import Popen, PIPE

for line in Popen("find ...", shell=True, stdout=PIPE).stdout:
   # do stuff

or if you don't need shell expansion

for line in Popen(["find", "/some/path", ...], stdout=PIPE).stdout:
    # do stuff

See http://docs.python.org/lib/module-subprocess.html for more.

Peter



More information about the Python-list mailing list