[Tutor] Sys.stdin Question

Steve Willoughby steve at alchemy.com
Wed Jan 14 03:10:38 CET 2009

On Tue, January 13, 2009 17:59, Damon Timm wrote:
> ... then, I guess, I can just have it do an if statement that asks: if
> args[0] == "-" then ... blah.  I may do that ... the script, itself,

Look at the fileinput module.  If you're looking at the command line for a
list of filenames, which may include "-" to mean (read stdin at this point
in the list of files), your script's logic is reduced to simply:

while line in fileinput.input():
  # process the line

and your script focuses on its specific task.

>> or not.  So instead of seeing if anything's showing up (and introducing
>> timing dependencies and uncertainty), see if it's attached to a real
>> terminal at all.  On Unix, os.isatty(sys.stdin) will tell you this.
> Does this concern still apply with John's suggestion?  I just tested
> it in my little application and didn't have an issue ... of course, I

Yes, it does.  And in a trivial case, it will usually work.  But don't
base your solutions on something that looks like it sorta works most of
the time but isn't really the recommended practice, because it will break
later and you'll spend a lot of time figuring out why it's not being

> I can go to using the "-" option ... although, to be honest, I like
> the idea of the script thinking for itself ... that is: if there is
> stdin, use it -- if not, not ... and, I was thinking of attaching the
> stdin as a text file, if present.  And not attaching anything, if not.

As the Zen of Python states, "explicit is better than implicit."

Scripts which just magically "do the right thing" can be cool to play
with, but they have a nasty tendency to guess wrong about what the right
thing might be.  In this case, you're making assumptions about how to
*guess* whether there's standard input piped at your script, and running
with those assumptions... but there are easily identified cases where
those assumptions don't hold true.

Also, think of anyone other than you (or you at a later date) using this
script.  The number of things the script does for no apparent reason can
lead to frustration and doubt that you really know, as a user, what the
script is really going to try to do in a given situation, and what you'll
have to do on your end to "trick" it into doing what you really wanted in
the first place.  It's cute, but ultimately implicit behavior doesn't make
for good, long-lasting solid applications.

More information about the Tutor mailing list