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-2016  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, 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 # entry point for running the script as an executable 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