Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility To Count Number Of Lines Of Code In Python Or Bash

Is there a quick and dirty way in either python or bash script, that can recursively descend a directory and count the total number of lines of code? We would like to be able to exclude certain directories though.

For example:

start at: /apps/projects/reallycoolapp
exclude: lib/, frameworks/

The excluded directories should be recursive as well. For example:

/app/projects/reallycool/lib SHOULD BE EXCLUDED
/app/projects/reallycool/modules/apple/frameworks SHOULD ALSO BE EXCLUDED

This would be a really useful utility.

like image 204
Justin Avatar asked Sep 21 '11 23:09

Justin


People also ask

How do you count lines of code in Python?

Use os. walk to traverse the files and sub directories, use endswith to filter the files you want to count, open each file and use sum(1 for line in f) to count the lines, aggregate all the file line counts.

How do I count lines in bash?

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

How do you count the number of lines of code?

To use cloc simply type cloc followed by the file or directory which you wish to examine. Now lets run cloc on it. As you can see it counted the number of files, blank lines, comments and lines of code. Another cool feature of cloc is that can even be used on compressed files.


1 Answers

Found an awesome utility CLOC. https://github.com/AlDanial/cloc

Here is the command we ran:

perl cloc.pl /apps/projects/reallycoolapp --exclude-dir=lib,frameworks

And here is the output

--------------------------------------------------------------------------------
Language                      files          blank        comment           code   
--------------------------------------------------------------------------------
PHP                              32            962           1352           2609
Javascript                        5            176            225            920
Bourne Again Shell                4             45             70            182
Bourne Shell                     12             52            113            178
HTML                              1              0              0             25
--------------------------------------------------------------------------------
SUM:                             54           1235           1760           3914
--------------------------------------------------------------------------------
like image 52
Justin Avatar answered Sep 18 '22 15:09

Justin