Package pysys :: Package utils :: Module linecount
[hide private]
[frames] | no frames]

Source Code for Module pysys.utils.linecount

 1  #!/usr/bin/env python 
 2  # PySys System Test Framework, Copyright (C) 2006-2013  M.B.Grieve 
 3   
 4  # This library is free software; you can redistribute it and/or 
 5  # modify it under the terms of the GNU Lesser General Public 
 6  # License as published by the Free Software Foundation; either 
 7  # version 2.1 of the License, or (at your option) any later version. 
 8   
 9  # This library is distributed in the hope that it will be useful, 
10  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
11  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12  # Lesser General Public License for more details. 
13   
14  # You should have received a copy of the GNU Lesser General Public 
15  # License along with this library; if not, write to the Free Software 
16  # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 
17   
18  # Contact: moraygrieve@users.sourceforge.net 
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):
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 # entry point for running the script as an executable 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