title: How do I avoid processing an empty stdin with python?
body: <p>The <code>sys.stdin.readline()</code> waits for an EOF (or new line) before returning, so if I have a console input, <code>readline()</code> waits for user input.  Instead I want to print help and exit with an error if there is nothing to process, not wait for user input. </p>
  
  <p>Reason:
  I'm looking to write a python program with command line behaviour similar to <code>grep</code>.</p>
  
  <p>Test cases:</p>
  
  <p>No input and nothing piped, print help</p>
  
  <pre><code>$ argparse.py
  argparse.py - prints arguments
  
  echo $?            # UNIX
  echo %ERRORLEVEL%  # WINDOWS
  2
  </code></pre>
  
  <p>Command line args parsed</p>
  
  <pre><code>$ argparse.py a b c 
  0 a
  1 b
  2 c
  </code></pre>
  
  <p>Accept piped commands</p>
  
  <pre><code>$ ls | argparse.py
  0 argparse.py
  1 aFile.txt
  </code></pre>
  
  <p>parseargs.py listing:</p>
  
  <pre><code># $Id: parseargs.py
  
  import sys
  import argparse
  
  # Tried these too:
  # import fileinput - blocks on no input
  # import subprocess - requires calling program to be known
  
  def usage():
      sys.stderr.write("{} - prints arguments".fomrat(sys.argv[0])
      sys.stderr.flush()
      sys.exit(2)
  
  def print_me(count, msg):
      print '{}: {:&gt;18} {}'.format(count, msg.strip(), map(ord,msg))
  
  if __name__ == '__main__':
      USE_BUFFERED_INPUT = False
      # Case 1: Command line arguments  
      if len(sys.argv) &gt; 1:
          for i, arg in enumerate(sys.argv[1:]):
              print_me( i, arg)
      elif USE_BUFFERED_INPUT:  # Note: Do not use processing buffered inputs  
          for i, arg in enumerate(sys.stdin):
              print_me( i, arg)
      else:
          i=0
          #####  Need to deterime if the sys.stdin is empty.
          #####  if READLINE_EMPTY:
          #####      usage()
          while True:
              arg = sys.stdin.readline() #Blocks if no input
              if not arg:
                  break
              print_me( i, arg)
              i += 1
      sys.exit(0)
  </code></pre>