sys.stdin.readline() waiting for the return of EOF (or a new line), so if I have console input, readline() waiting for user input. Instead, I want to print the help and exit with an error if nothing is processed, and not wait for user input.
Reason: I want to write a python program with command line behavior similar to grep .
Test cases:
No input and nothing sent, print help
$ argparse.py argparse.py - prints arguments echo $?
Parsing command line arguments
$ argparse.py abc 0 a 1 b 2 c
Receive commands with channels
$ ls | argparse.py 0 argparse.py 1 aFile.txt
List of parseargs.py:
# $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 '{}: {:>18} {}'.format(count, msg.strip(), map(ord,msg)) if __name__ == '__main__': USE_BUFFERED_INPUT = False # Case 1: Command line arguments if len(sys.argv) > 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)
source share