piping into a python script

Nick Craig-Wood nick at craig-wood.com
Fri Jan 25 04:30:03 EST 2008


Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:
>  On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote:
> 
> > Given these two examples:
> > 1. 
> > ./fui.py *.py
> > 2.
> > ls *.py | ./fui.py
> > 
> > How can I capture a list of the arguments?
> > I need to get all the strings (file or dir names) passed via the normal
> > command line and any that may come from a pipe.
> > 
> > There is a third case:
> > 3.
> > ls *.jpg | ./fui.py *.png
> > Where I would be gathering strings from two places.
> > 
> > I am trying to write a command-line friendly tool that can be used in
> > traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally.
> > 
> > I have tried:
> > 1. pipedIn = sys.stdin.readlines()
> > Works fine for example 2, but example 1 goes into a 'wait for input' mode
> > and that's no good. Is there a way to tell when no input is coming from a
> > pipe at all?
> 
>  Usually Linux tools that can get the data from command line or files treat
>  a single - as file name special with the meaning of: read from stdin.
> 
>  So the interface if `fui.py` would be:
> 
>  1. ./fui.py *.a
>  2. ls *.a | ./fui.py -
>  3. ls *.a | ./fui.py *.b -

Did anyone mention the (standard library) fileinput module?  (I missed
the start of this thread.)

http://docs.python.org/lib/module-fileinput.html

11.2 fileinput -- Iterate over lines from multiple input streams

This module implements a helper class and functions to quickly write a
loop over standard input or a list of files.

The typical use is:

import fileinput
for line in fileinput.input():
    process(line)

This iterates over the lines of all files listed in sys.argv[1:],
defaulting to sys.stdin if the list is empty. If a filename is '-', it
is also replaced by sys.stdin. To specify an alternative list of
filenames, pass it as the first argument to input(). A single file
name is also allowed.

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



More information about the Python-list mailing list