1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import os, os.path, sys, re, logging
21
22 from pysys import log
23 from pysys.exceptions import *
24 from pysys.utils.filegrep import getmatches
25
26
27 -def linecount(file, regexpr=None, ignores=None):
28 """Count the number of lines in an input file matching a regular expression, return the count.
29
30 If the input regular expression is set to None, the method returns a count of the
31 number of lines in the input file. The regular expression should be passed in as
32 a string, i.e. C{"[a-z]_foo.*"} etc.
33
34 @param file: The full path to the input file
35 @param regexpr: The regular expression used for counting matches
36 @param ignores: A list of regular expressions that will cause lines to be excluded from the count
37 @return: The number of matching lines in the input file
38 @rtype: integer
39 @raises FileNotFoundException: Raised if the input file does not exist
40
41 """
42 matches = getmatches(file, regexpr, ignores=ignores)
43 return len(matches)
44
45
46
47 if __name__ == "__main__":
48 try:
49 if len(sys.argv) == 3:
50 count = linecount(sys.argv[1], sys.argv[2])
51 elif len(sys.argv) == 2:
52 count = linecount(sys.argv[1])
53 else:
54 print "Usage: lineCount.py <file> [regexpr]"
55 sys.exit()
56
57 print "Line count = %d" % (count)
58
59 except FileNotFoundException, value:
60 print "caught %s: %s" % (sys.exc_info()[0], value)
61 print "unable to perform line count... exiting"
62