1#!/usr/bin/env python 2 3helpdoc = """ 4A simple utility that verifies the syntax for python scripts. 5The checks it does are : 6 * Check for 'tab' characters in .py files 7 * Compile errors in py sources 8Usage: 9 python syntax_checker.py <python_source_file> [<python_source_file> ..] 10""" 11import py_compile 12import sys 13import os 14import re 15 16tabs_search_rex = re.compile("^\s*\t+",re.MULTILINE|re.DOTALL) 17 18def find_non_ascii(s): 19 for c in s: 20 if ord(c) >= 0x80: return True 21 return False 22 23if __name__ == "__main__": 24 if len(sys.argv) < 2: 25 print >>sys.stderr, "Error: Unknown arguments" 26 print helpdoc 27 sys.exit(1) 28 for fname in sys.argv[1:]: 29 if not os.path.exists(fname): 30 print >>sys.stderr, "Error: Cannot recognize %s as a file" % fname 31 sys.exit(1) 32 if fname.split('.')[-1] != 'py': 33 print "Note: %s is not a valid python file. Skipping." % fname 34 continue 35 fh = open(fname) 36 strdata = fh.readlines() 37 lineno = 0 38 syntax_fail = False 39 for linedata in strdata: 40 lineno += 1 41 if len(tabs_search_rex.findall(linedata)) > 0 : 42 print >>sys.stderr, "Error: Found a TAB character at %s:%d" % (fname, lineno) 43 syntax_fail = True 44 if find_non_ascii(linedata): 45 print >>sys.stderr, "Error: Found a non ascii character at %s:%d" % (fname, lineno) 46 syntax_fail = True 47 if syntax_fail: 48 print >>sys.stderr, "Error: Syntax check failed. Please fix the errors and try again." 49 sys.exit(1) 50 #now check for error in compilation 51 try: 52 compile_result = py_compile.compile(fname, cfile="/dev/null", doraise=True) 53 except py_compile.PyCompileError as exc: 54 print >>sys.stderr, str(exc) 55 print >>sys.stderr, "Error: Compilation failed. Please fix the errors and try again." 56 sys.exit(1) 57 print "Success: Checked %s. No syntax errors found." % fname 58 sys.exit(0) 59 60