Created
February 9, 2017 18:31
-
-
Save wh13371/f37df8de9a1b9fb45bbaf5b4cd7bb1ad to your computer and use it in GitHub Desktop.
python - args from file(s) or STDIN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
import fileinput, argparse | |
from glob import glob | |
""" | |
# read from <file(s)> or <STDIN> | |
# Examples: | |
args.py *.txt | |
args.py 1.txt 2.txt 3.txt | |
args.py *.txt -n | |
args.py < *.txt | |
dir | args.py -n | |
df -hP | python3.5 ./args.py -n | |
""" | |
args = argparse.ArgumentParser(description='args from file(s) or STDIN') | |
args.add_argument('--version', action='version', version='%(prog)s ') | |
args.add_argument('files', metavar='FILE', nargs='*', help='file(s) to read') | |
args.add_argument('-n', '--number', action='store_true', help='print line numbers') | |
args = args.parse_args() | |
with fileinput.input([f for files in args.files for f in glob(files)]) as f: | |
for line in f: | |
if args.number: | |
print ("%s : %d : %s" % (f.filename(), f.filelineno(), line.rstrip())) | |
else: | |
print(line.rstrip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment