1

I found this question in a textbook to write code to count the number of lines of program by running it.

This is what I have:

import commands,os,sys

def count_lines(modul):
    cmd="wc -l " + modul +" | awk '{print $1}'"
    return commands.getoutput(cmd)


if __name__=='__main__':
    print count_lines(sys.modules[__name__].__file__)

It seems to work;but I am not sure if this the right way to do. I thought this is simpler.

4
  • 3
    You're not really writing Python there. You're writing a shell script in a Python wrapper. Commented Jan 15, 2014 at 0:05
  • wc -l "file" | awk '{print $1}' will work without python. Commented Jan 15, 2014 at 0:06
  • @user2357112: I agree; but most of the python functions are wrappers of C. correct me if I am wrong..? Commented Jan 15, 2014 at 0:11
  • @eagertoLearn: Whether that's true or false (I consider it false), it's not relevant. They're definitely not wrappers around shell scripting (which is entirely distinct from C), and whatever the implementation of Python, there's no reason to embed a second programming language and spawn several additional processes just to perform this simple task. Commented Jan 15, 2014 at 0:17

1 Answer 1

3

print "I AM %d LINES LONG"%len(list(open(__file__))) just put that in any file...

if you insist on closing your file (while a good habit , not necessary in cython especially when only reading)

with open(__file__) as f:
    print "I AM %d LINES LONG"%len(list(f))
Sign up to request clarification or add additional context in comments.

5 Comments

you dont need that ... and it would be readlines I think ... but by default it will iterate into a list right?
it has to count the lines of the file that this line is present? will it work?
Ah yeah, he is asking for the lines. My bad.
open without a close or with? Don't teach bad habits; close your file.
it doesnt matter if hes just reading and hes in cython ... but edited all the same ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.