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.

Management Science and Engineering in Stanford University

Thursday, April 9, 2009

Last week I enrolled into Internet Commerce Graduate course offered through Stanford University's Management Science and Engineering Department through SCPD, for those are not aware of SCPD, its Stanford Center for Professional Development which offers Stanford graduate degrees certificates for working professionals.

I enrolled into the Management Science and Engineering course with a long term goal to get an MS Degree in it, before that my short term goal is to complete a Graduate Certificate in Management Science and Engineering by early next year after which I will apply for MS in Management Science and Engineering part time with my GRE scores through Stanford's HCP (Honors Cooperative Program), it was a good experience till date where I attended a couple of lecture classes of Prof. Ashish Goel , I felt I really learnt a lot and satisfied and what more, raring to go for the challenges ahead.

Graduate Certificate in Management Science and Engineering requires 4 courses which includes an elective from different areas of focus in Management Science and Engineering, the good thing is if you pursue your MS in Management Science and Engineering after your graduate certificate, you can substitute the courses you had taken in your graduate certificate towards the degree and based on the subjects in the curriculum, I feel its a great value add for working professionals.

MS in Management Science and Engineering is an unique degree with the right blend of engineering and management subjects, its hard to describe this course with its diverse focus areas above and beoynd engineering, but from the objectives I see that its designed to equip you with the right technical knowledge and business acumen required for strategical decision making and fits exactly to my needs, looking into managerial aspects from an engineer's perspective.

The core subjects like Dynamic Systems, Linear and Nonlineaer Optimization, Strategy in Technology-Based Companies, Risk Analysis, Production Systems, etc should give a better insight on engineering and technological aspects of Management Science.

The electives I feel are highly customized to the needs and interests of the student from different areas like Information Technology, Enterpreneurship, Economics, Operations research, etc, overall I feel the curriculum for this course is very intelligently designed to suit the student's interests and goals.

The final question Why did I opt for this course, mainly because I feel that to be successful in this competitive IT world, business intelligence is more important than business knowledge and the more you explore on how different kinds of business models work, the methods/techniques by which you derive an optimal strategy for success, the better it will be for your profession and I feel that this course has every ingredients of it.

Related Links..

SCPD - http://scpd.stanford.edu
Management Science and Engineering - http://stanford.edu/dept/MSandE/academics/ms.html
Management Science and Engineering Curriculum - http://stanford.edu/dept/MSandE/academics/MSpgm.pdf
Management Science and Engineering FAQ - http://stanford.edu/dept/MSandE/academics/faqms.html

Youtube Error Message - Hello, you either have JavaScript turned off or an old version of Adobe's Flash Player, Possible Solution

Thursday, April 2, 2009

I was hitting the walls before finding the solution for this unusual error message from youtube when viewing some videos from Windows, mostly movies, the error message is

Hello, you either have JavaScript turned off or an old version of Adobe's Flash Player. Get the latest Flash player.

After crosschecking browser javascript settings, I found that javascript is not disabled in my Firefox or IE7, then I installed the latest flash player as suggested above which doesn't solve the problem as well, finally suspected whether the Symantec Firewall installed in my system may be the reason for this error as many a times I visit a website with ActiveX control, it prompts me "The Web page you are trying to view contains an ActiveX control." and the action suggested by Symantec Firewall is Block Once ("Recommended"), but in this case when viewing the youtube video which flashes the above error, the symantec firewall doesn't prompt anything.

So the solution to get rid of the above error is to temporarily disable the Symantec firewall as shown below (right click Symantec Firewall in the desktop tray, click Disable Symantec Firewall for 5 minutes, the least time you can disable the Symantec firewall), although its not advised, its the only hot fix I found to get rid of the above error message although I am still exploring another way to fix the above error by changing Symantec firewall settings to trust the content from youtube, in general firewall may be the reason which may block some youtube videos with the above error message.

But still the unanswered question is why the Symantec firewall didn't prompt before viewing these videos, lets leave it for a future discussion.

Fig 1: Youtube Javascript/Flash error


Fig 2: Symantec Firewall


Fig 3: Disable Symantec Firewall for 5 minutes


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.