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
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 @return: The number of matching lines in the input file
37 @rtype: integer
38 @raises FileNotFoundException: Raised if the input file does not exist
39
40 """
41 matches = getmatches(file, regexpr)
42 return len(matches)
43
44
45
46 if __name__ == "__main__":
47 try:
48 if len(sys.argv) == 3:
49 count = linecount(sys.argv[1], sys.argv[2])
50 elif len(sys.argv) == 2:
51 count = linecount(sys.argv[1])
52 else:
53 print "Usage: lineCount.py <file> [regexpr]"
54 sys.exit()
55
56 print "Line count = %d" % (count)
57
58 except FileNotFoundException, value:
59 print "caught %s: %s" % (sys.exc_info()[0], value)
60 print "unable to perform line count... exiting"
61