piping into a python script

Paddy paddy3118 at googlemail.com
Thu Jan 24 10:26:27 EST 2008


On Jan 24, 3:17 pm, Donn Ingle <donn.in... at gmail.com> wrote:
> Hi,
> (Gnu/Linux - Python 2.4/5)
> 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?
>
> 2. import fileinput
> for line in fileinput.input():
>     print (line)
> But this opens each file and I don't want that.
>
> I have seen a lot of search results that don't quite answer this angle of
> the question, so I'm trying on the list.
>
> \d

Try the fileinput module.
What you describe above is pretty close to the unix 'standard' but not
quite.
if we substitute the lp command instead of ./fui, the command normally
takes a list of files to act on as its arguments, and anything piped
in goes to its stdin where it is processed if it has an argument of -
fileinput works that way but you may have problems with your:
  ls *.jpg | ./fui.py *.png
Which might better be expressed as:
  ./fui.py `ls *.jpg` *.png
which would work for ls and a python program using the fileinput
module.

- Paddy.



More information about the Python-list mailing list