Created
April 29, 2014 13:41
-
-
Save yuchan/11400749 to your computer and use it in GitHub Desktop.
python implementation of nl command(no options).
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/env python | |
import sys | |
DEFAULT_INDENT = 4 | |
def main(): | |
argc = len(sys.argv) | |
f = None # File IO | |
if argc == 1: | |
print "type text below. enter Ctrl-D to exit." | |
f = sys.stdin | |
elif argc == 2: | |
try: | |
f = open(sys.argv[1], "rU") | |
except IOError: | |
sys.exit("nl.py: %s: No such file or directory" % (sys.argv[1])) | |
else: | |
sys.exit("usage: python nl.py [file]") | |
i = 1 | |
readlines = f.readlines() | |
for line in readlines: | |
if len(line.strip()) <= 0: | |
print "" | |
else: | |
num = len(str(len(readlines))) - len(str(i)) + DEFAULT_INDENT | |
print "%s%d %s" % (" " * num, i, line.rstrip()) | |
i += 1 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment