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