[Tutor] Unix philosophy
Guillermo Fernandez Castellanos
guillermo.fernandez at epfl.ch
Tue Nov 18 06:23:49 EST 2003
Hi,
Thanks for the answers.
I'm reading the digest version of the mailing list, that's why I grouped
the answers.
> There are probably other ways to do this using exec or
> something, but I'd probably make all of the programs
> as libraries and make one short script connecting them
> all together. You know how do do that, don't you?
Actually it was my philosophy until now. I am developing a utility and I'm separating it into libraries (one to parse text, another to join files, another to make database queries) but I always try to also allow the libraries to be used as single programs (with the if __name__=='__main__':). But I though it would be neat to do it the 'pipeline' way :-) It would allow the user to reproduce my program using a single command line and that way 'personalize' the execution (if he don't need a library for example).
> I use the fileinput module to do this:
> http://www.python.org/doc/current/lib/module-fileinput.html
>
> works great for all kinds of files, multiple files, stdin, etc.
Indeed it seems to answer what I was looking for :-)
> Basically, what you have to do is read input from stdin and write
> output to stdout. That makes it possible to use it as a filter in a
> pipeline like
>
> grep something < file | python myprog.py | lp
>
> or whatever. The "|" signs here connect the first program's stdout to
> the second program's stdin.
> This is a bit unfriendly so its common to write programs that
> take a command line argument which switches filter behavious
> on or off. There is no fixed convention for how this is done.
That means that if I wanted to do it in a more general way that with fileinput module I should use the sys.stdin/out functions?
Are you thinking to something like this:
guillecat.py
# Simple cat UNIX command
import sys
if len(sys.argv)==1:
while(1):
readed=sys.stdin.read(1)
sys.stdout.write(readed)
else:
for files in sys.argv[1:]:
filed=file(files,'r')
readed=filed.read()
sys.stdout.write(readed)
Thanks,
Guille
More information about the Tutor
mailing list