Skip to content

Instantly share code, notes, and snippets.

@yuchan
Created April 29, 2014 13:41
Show Gist options
  • Save yuchan/11400749 to your computer and use it in GitHub Desktop.
Save yuchan/11400749 to your computer and use it in GitHub Desktop.
python implementation of nl command(no options).
#! /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