Posted By

reklis on 07/22/10


Tagged

String stdin Getopt sys unwrap


Versions (?)

unwrap.py


 / Published in: Python
 

unwraps lines from a text file with parameters

  1. #!/usr/bin/python
  2.  
  3. import sys
  4. import getopt
  5.  
  6. def usage():
  7. print
  8. print "Usage: %(filename)s -n 4" % { "filename" : sys.argv[0] }
  9. print " unwraps 4 lines of output to a single line"
  10.  
  11. def main(argv=None):
  12. if argv is None:
  13. argv = sys.argv
  14.  
  15. try:
  16. opts, args = getopt.getopt(argv[1:], "n:", ["number-of-lines"])
  17. num_lines = 0
  18. for o, a in opts:
  19. if o == "-n":
  20. num_lines = int(a)
  21.  
  22.  
  23. assert (num_lines > 0)
  24.  
  25. i = 0
  26. buff = ""
  27. for line in sys.stdin:
  28. buff = buff + " " + line.lstrip().rstrip()
  29. i = i + 1
  30. if i >= num_lines:
  31. print buff
  32. i = 0
  33. buff = ""
  34.  
  35.  
  36. if i != 0:
  37. print buff
  38.  
  39. except getopt.GetoptError, err:
  40. print str(err)
  41. usage()
  42. return 2;
  43.  
  44. return 0;
  45.  
  46. if __name__ == "__main__":
  47. sys.exit(main())

Report this snippet  

You need to login to post a comment.