Printing line numbers of a source file in Python

Sunday, April 19, 2009

These days I was little busy with my part time studies, therefore many things which I wanted to blog about were stalled for some time, but it should be fine as time goes on. Back to the subject, I was always looking for an easy solution to print the line numbers of a source file for easier understanding of the code, also some syntax highlighters, despite having sophisticated features, doesn't highlight line numbers in a source code, therefore I developed a small script in python to print line numbers of a source file and display the source with line numbers in a browser.

Printing line numbers of a source file will be useful in many ways, to troubleshoot code, explain the code easily with reference to line numbers, feeding the code printed with line numbers to syntax highlighters (the reason why I did this), etc, although as trivial as I thought about this task, its not that simple, its not like you read the lines of a files, append the line number before the every line of source and write it to an output file, the spacing between line numbers and the source should be consistent (i.e all lines of the source code should start in the same column), it involved a little thinking, but thanks to python, which made it look very easy.

Listing 1: file_line_numbers.py

1.  #
2. # Add line numbers to a source file and display in a browser
3. # file_line_numbers.py
4. # Author: S.Prasanna
5. #
6.
7. import sys
8. import traceback
9. import tempfile
10. import os
11.
12. #Default browsers for Windows and UNIX, change as needed
13. BROWSER_WIN="C:\Program Files\Internet Explorer\iexplore"
14. BROWSER_UNIX="/usr/bin/firefox"
15.
16. def add_line_number(infile):
17. """ Prints a source file with line numbers in a browser. """
18.
19. try:
20. fin = open(infile, "r")
21. except:
22. print "An exception occured in opening the input file."
23. traceback.print_exc()
24. return 1
25.
26. outfilename = tempfile.mkstemp()[1]
27.
28. try:
29. fout = open(outfilename, "w")
30. except:
31. print "An exception occured in opening the output file."
32. traceback.print_exc()
33. return 1
34.
35. total_lines = sum(1 for line in fin)
36. total_digits = len(str(total_lines))
37.
38. fin.seek(0)
39.
40. lines_written = 1
41.
42. for lines in fin:
43. fout.write(repr((str(lines_written) + ".")).ljust(total_digits + 4).replace("'", "") + lines)
44. lines_written = lines_written + 1
45.
46. fin.close()
47. fout.close()
48.
49. print "Printing the line numbers of the input file in a browser."
50. print "Close the browser to exit."
51.
52. if os.name == "nt":
53. return os.system("\"" + BROWSER_WIN + "\" " + outfilename)
54. else:
55. return os.system("\"" + BROWSER_UNIX + "\" " + outfilename)
56.
57. if __name__ == "__main__":
58.
59. if len(sys.argv) != 2:
60. print "Usage: file_line_number.py "
61. sys.exit(1)
62.
63. input_file = sys.argv[1]
64. add_line_number(input_file)

Explanation:

This looks like a simple code, but it uses some features of python, the code gets the input file as command line parameter (lines 59 - 61), fetches the number of lines in the file using the sum function (lines 35 - 36)
total_lines = sum(1 for line in fin)
The python sum buiilt-in function retrieves the sum of the line numbers of the file (it reads every line), I can explain more about the sum function with examples in another post, but for now its good enough to know that it returns the number of lines in the input file, from the number of lines, the number of digits in the total lines are calculated to determining the spacing (or padding length) between the line numbers and the source code.

Then the file pointer is moved back to the start to read the file again (line 38), after which the repr function (line 43) in python is used to left justify the line numbers, giving some extra digits to separate the source code from line numbers (the repr function prints the enclosing ' character in the output, which is replaced with ""), after which it's appended to the line read from the input file.

Finally the source file with line numbers is displayed in a browser (lines 52 - 55), the default browser is Internet Explorer for Windows and Firefox for UNIX), a temporary file is created for displaying the source with line numbers (line 26), which will be deleted automatically after the program exits.

Note: You need to close the browser to exit the program.

Fig 1: Sample output, printing line numbers of a source code in browser.

C:\>python file_line_numbers.py unix_command.c
Printing the line numbers of the input file in a browser.
Close the browser to exit.

2 comments:

Anonymous said...

nice, i use
cat -n FILENAME > /tmp/tmp && firefox /tmp/tmp

Prasanna Seshadri said...

Thanks, I will try that.


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.