Chosing between sys.argv and sys.stdin

Syn.Terra dream at aevum.net
Fri Oct 27 18:09:44 EDT 2000


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()

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.

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





More information about the Python-list mailing list