Chosing between sys.argv and sys.stdin
Steve Holden
sholden at holdenweb.com
Fri Oct 27 18:25:32 EDT 2000
"Syn.Terra" wrote:
>
> I've got a Python script that I want to be used either with commandline
> arguments or using stdin (most likely by piping). My question is, what's
> the simplest way to code that sort of conditional? My current script
> fragment looks like this:
>
> import sys
> try:
> text = sys.argv[1]
> except IndexError:
> print "usage: ..."
> sys.exit()
>
Obviously, you will get the IndexError if len(sys.argv) < 2
so this is the key condition to code around.
> How would I add something that says "use sys.stdin if they don't include
> commandline arguments, but if neither is present, print the error
> message"? Right now, if it calls sys.stdin.read() and it wasn't piped
> into (like calling "spam.py" rather than "cat file | spam.py") it just
> sits there until I hit ctrl-d.
>
Probably what you need is something like the following, which
will work for a single file name. You can easily extend it to
multiple filenames (left as an exercise to the reader...)
if len(sys.argv) < 1:
myfile = sys.stdin
else:
try:
myfile = open(sys.argv[1], 'r')
except:
print "Could not open file", sys.argv[1]
sys.exit(-1)
> Note: I don't frequent the newsgroup, so if you could send replies to
> dream at aevum.net, I'd be greatly appreciative.
>
> ----
> Syn.Terra
> Aevum Industries
> http://www.aevum.net
Posted and mailed.
regards
Steve
--
Helping people meet their information needs with training and technology.
703 967 0887 sholden at bellatlantic.net http://www.holdenweb.com/
More information about the Python-list
mailing list