how to bail if stdin is empty

Discussion in 'Python' started by Jon Schull, May 31, 2004.

  1. Jon Schull

    Jon Schull Guest

    I want to write a filter that will take input from files on the
    command line and/or from stdin.

    But if nothing has been piped to stdin, I don't want my program to
    hang--I want it to do something else.

    This is standard behavior for pipeable-programs I believe, but I can't
    figure out how to do it...neither by reading from stdin nor by using
    the fileinput module.

    Thanks in advance!
     
    Jon Schull, May 31, 2004
    #1
    1. Advertising

  2. Jon Schull

    Jeff Epler Guest

    You can test whether stdin is a "terminal", and act accordingly.

    $ ./tt.py
    Standard input is a terminal. Aborting!
    $ ./tt.py < /dev/null
    Standard input is a file. Doing something.

    #!/usr/bin/env python

    import os
    if os.isatty(0):
    print "Standard input is a terminal. Aborting!"
    else:
    print "Standard input is a file. Doing something."

    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.2.4 (GNU/Linux)

    iD8DBQFAuzbZJd01MZaTXX0RAh/FAJ9gyjEQG3T+JpRXYTYd1C+/DsFuVwCeKAH+
    JsomiFe8DWJ2YtXMKRc6Y9E=
    =8zxf
    -----END PGP SIGNATURE-----
     
    Jeff Epler, May 31, 2004
    #2
    1. Advertising

  3. Op 2004-05-31, Jon Schull schreef <>:
    > I want to write a filter that will take input from files on the
    > command line and/or from stdin.
    >
    > But if nothing has been piped to stdin, I don't want my program to
    > hang--I want it to do something else.
    >
    > This is standard behavior for pipeable-programs I believe,


    No it is not. Standard behaviour for filters (on unix that is)
    is to use standard input if no file arguments are given.

    If you start such a program without arguments and not connected
    to another programs with a pipe, such a program will hang and
    wait for user input from the keyboard.

    --
    Antoon Pardon
     
    Antoon Pardon, Jun 1, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Johnathan Doe

    peek at stdin, flush stdin

    Johnathan Doe, May 15, 2004, in forum: C Programming
    Replies:
    5
    Views:
    25,453
    Chatoyer
    May 17, 2013
  2. Charlie Zender

    Reading stdin once confuses second stdin read

    Charlie Zender, Jun 19, 2004, in forum: C Programming
    Replies:
    6
    Views:
    823
    Dan Pop
    Jun 21, 2004
  3. Ben
    Replies:
    2
    Views:
    1,401
    jacob navia
    Aug 29, 2009
  4. Kurt Euler
    Replies:
    2
    Views:
    124
    Anita Date
    Sep 3, 2003
  5. Terry Cooper
    Replies:
    7
    Views:
    451
    Janos Sebok
    Jun 9, 2009
Loading...

Share This Page