def main(prog=None, args=None): """Entry point for the script "pyflakes".""" import argparse # Handle "Keyboard Interrupt" and "Broken pipe" gracefully _exitOnSignal('SIGINT', '... stopped') _exitOnSignal('SIGPIPE', 1) parser = argparse.ArgumentParser( prog=prog, description='Check Python source files for errors') parser.add_argument('-V', '--version', action='version', version=_get_version()) parser.add_argument( 'path', nargs='*', help='Path(s) of Python file(s) to check. STDIN if not given.') args = parser.parse_args(args=args).path reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '<stdin>', reporter) raise SystemExit(warnings > 0)
def checkPath(filename, reporter=None): """ Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed """ if reporter is None: reporter = modReporter._makeDefaultReporter() try: # in Python 2.6, compile() will choke on \r\n line endings. In later # versions of python it's smarter, and we want binary mode to give # compile() the best opportunity to do the right thing WRT text # encodings. if sys.version_info < (2, 7): mode = 'rU' else: mode = 'rb' with open(filename, mode) as f: codestr = f.read() if sys.version_info < (2, 7): codestr += '\n' # Work around for Python <= 2.6 except UnicodeError: reporter.unexpectedError(filename, 'problem decoding source') return 1 except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter)
def main(prog=None, args=None): """Entry point for the script "pyflakes".""" import argparse # Handle "Keyboard Interrupt" and "Broken pipe" gracefully _exitOnSignal("SIGINT", "... stopped") _exitOnSignal("SIGPIPE", 1) parser = argparse.ArgumentParser( prog=prog, description="Check Python source files for errors") parser.add_argument("-V", "--version", action="version", version=_get_version()) parser.add_argument( "path", nargs="*", help="Path(s) of Python file(s) to check. STDIN if not given.") args = parser.parse_args(args=args).path reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), "<stdin>", reporter) raise SystemExit(warnings > 0)
def main(): my_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(my_dir, '..'))) from optparse import OptionParser parser = OptionParser() parser.add_option('--with-pep8', action='store_true', dest='with_pep8', default=True) parser.add_option('--with-pyflakes', action='store_true', dest='with_pyflakes', default=True) parser.add_option('--force-all', action='store_true', dest='force_all', default=False) parser.add_option('-v', '--verbose', action='count', dest='verbosity', default=0) parser.add_option('-q', '--quiet', action='count', dest='quietness', default=0) options, extra_args = parser.parse_args() if options.with_pep8: try: import pep8 except ImportError: sys.stderr.write('# Could not find pep8 library.\n') sys.exit(1) guide_main = pep8.StyleGuide( ignore=[], paths=['subte/'], exclude=[], max_line_length=80, ) guide_tests = pep8.StyleGuide( ignore=['E221'], paths=['tests/'], max_line_length=80, ) for guide in (guide_main, guide_tests): report = guide.check_files() if report.total_errors: sys.exit(1) if options.with_pyflakes: try: import pyflakes assert pyflakes # silence pyflakes except ImportError: sys.stderr.write('# Could not find pyflakes library.\n') sys.exit(1) from pyflakes import api, reporter warnings = api.checkRecursive(['subte', 'tests'], reporter._makeDefaultReporter()) if warnings > 0: sys.exit(1) suite = make_suite('', tuple(extra_args), options.force_all) runner = TextTestRunner(verbosity=options.verbosity - options.quietness + 1) result = runner.run(suite) sys.exit(not result.wasSuccessful())
def check(codeString, filename, reporter=None): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: The number of warnings emitted. @rtype: C{int} """ if reporter is None: reporter = modReporter._makeDefaultReporter() # First, compile into an AST and handle syntax errors. try: tree = ast.parse(codeString, filename=filename) except SyntaxError: value = sys.exc_info()[1] msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text if checker.PYPY: if text is None: lines = codeString.splitlines() if len(lines) >= lineno: text = lines[lineno - 1] if sys.version_info >= (3, ) and isinstance(text, bytes): try: text = text.decode('ascii') except UnicodeDecodeError: text = None offset -= 1 # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. reporter.unexpectedError(filename, 'problem decoding source') else: reporter.syntaxError(filename, msg, lineno, offset, text) return 1 except Exception: reporter.unexpectedError(filename, 'problem decoding source') return 1 # Okay, it's syntactically valid. Now check it. file_tokens = checker.make_tokens(codeString) w = checker.Checker(tree, file_tokens=file_tokens, filename=filename) w.messages.sort(key=lambda m: m.lineno) for warning in w.messages: reporter.flake(warning) return len(w.messages)
def main(): args = sys.argv[1:] reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '<stdin>', reporter) raise SystemExit(warnings > 0)
def main(prog=None): parser = OptionParser(prog=prog, version=__version__) __, args = parser.parse_args() reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '<stdin>', reporter) raise SystemExit(warnings > 0)
def test_pyflakes(): rep = reporter._makeDefaultReporter() base_path = os.path.dirname(os.path.dirname(__file__)) paths = [ os.path.join(base_path, 'src'), os.path.join(base_path, 'test'), ] warnings = checkRecursive(paths, rep) assert warnings == 0
def run(self): # Don't import the pyflakes code until now because setup.py needs to be # able to install Pyflakes if its missing. This localizes the import to # only after the setuptools code has run and verified everything is # installed. from pyflakes import api from pyflakes import reporter # Run the Pyflakes check against our package and check its output val = api.checkRecursive([PACKAGE], reporter._makeDefaultReporter()) if val > 0: sys.exit('ERROR: Pyflakes failed with exit code %d' % val)
def main(prog=None): """Entry point for the script "pyflakes".""" import optparse # Handle "Keyboard Interrupt" and "Broken pipe" gracefully _exitOnSignal('SIGINT', '... stopped') _exitOnSignal('SIGPIPE', 1) parser = optparse.OptionParser(prog=prog, version=__version__) (__, args) = parser.parse_args() reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '<stdin>', reporter) raise SystemExit(warnings > 0)
def main(prog=None, args=None): """Entry point for the script "pyflakes".""" import optparse # Handle "Keyboard Interrupt" and "Broken pipe" gracefully _exitOnSignal('SIGINT', '... stopped') _exitOnSignal('SIGPIPE', 1) parser = optparse.OptionParser(prog=prog, version=__version__) (__, args) = parser.parse_args(args=args) reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '<stdin>', reporter) raise SystemExit(warnings > 0)
def check(codeString, filename, reporter=None): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{str} @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: The number of warnings emitted. @rtype: C{int} """ if reporter is None: reporter = modReporter._makeDefaultReporter() # First, compile into an AST and handle syntax errors. try: tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST) except SyntaxError: value = sys.exc_info()[1] msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. reporter.unexpectedError(filename, 'problem decoding source') else: reporter.syntaxError(filename, msg, lineno, offset, text) return 1 except Exception: reporter.unexpectedError(filename, 'problem decoding source') return 1 else: # Okay, it's syntactically valid. Now check it. w = checker.Checker(tree, filename) w.messages.sort(key=lambda m: m.lineno) for warning in w.messages: reporter.flake(warning) return len(w.messages)
def checkPath(filename, reporter=None): """ Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed """ if reporter is None: reporter = modReporter._makeDefaultReporter() try: with open(filename, 'rb') as f: codestr = f.read() except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter)
def main(prog=None): """Entry point for the script "pyflakes".""" import optparse import signal # Handle "Keyboard Interrupt" and "Broken pipe" gracefully try: signal.signal(signal.SIGINT, lambda sig, f: sys.exit('... stopped')) signal.signal(signal.SIGPIPE, lambda sig, f: sys.exit(1)) except ValueError: pass # SIGPIPE is not supported on Windows parser = optparse.OptionParser(prog=prog, version=__version__) (__, args) = parser.parse_args() reporter = modReporter._makeDefaultReporter() if args: warnings = checkRecursive(args, reporter) else: warnings = check(sys.stdin.read(), '<stdin>', reporter) raise SystemExit(warnings > 0)
def check_code(code, name): errors = [] class CustomMessage(object): pass reporter = modReporter._makeDefaultReporter() try: tree = compile(code, name, "exec", _ast.PyCF_ONLY_AST) except SyntaxError: value = sys.exc_info()[1] msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. reporter.unexpectedError(name, 'problem decoding source') else: reporter.syntaxError(name, msg, lineno, offset, text) loc = CustomMessage() loc.lineno = lineno loc.offset = offset msg = Message(name, loc) msg.message = "SyntaxError" errors.append(msg) except Exception, e: loc = CustomMessage() loc.lineno = lineno loc.offset = offset msg = Message(name, loc) msg.message = "Problem decoding source" errors.append(msg) reporter.unexpectedError(name, 'problem decoding source') logger.error("problem decoding source") logger.exception()
def check(filename): from pyflakes import reporter as mod_reporter from pyflakes.checker import Checker codeString = open(filename).read() reporter = mod_reporter._makeDefaultReporter() # First, compile into an AST and handle syntax errors. try: tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST) except SyntaxError: value = sys.exc_info()[1] msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. reporter.unexpectedError(filename, 'problem decoding source') else: reporter.syntaxError(filename, msg, lineno, offset, text) return 1 except Exception: reporter.unexpectedError(filename, 'problem decoding source') return 1 else: # Okay, it's syntactically valid. Now check it. lines = codeString.splitlines() warnings = Checker(tree, filename) warnings.messages.sort(key=lambda m: m.lineno) real_messages = [] for m in warnings.messages: line = lines[m.lineno - 1] if 'pyflakes:ignore' in line.rsplit('#', 1)[-1]: # ignore lines with pyflakes:ignore pass else: real_messages.append(m) reporter.flake(m) return len(real_messages)
def run(self): try: from pyflakes import api from pyflakes import reporter as modReporter except ImportError: print( 'Cannot import pyflakes, you forgot to install?\n' 'run `pip install pyflakes` to install.', file=sys.stderr) sys.exit(1) from os.path import basename reporter = modReporter._makeDefaultReporter() # monkey patch for exclusion of pathes api_iterSourceCode = api.iterSourceCode def _iterSourceCode(paths): for path in api_iterSourceCode(paths): if basename(path) not in EXCLUDE_SCRIPTS: yield path api.iterSourceCode = _iterSourceCode print() print('Options') print('=======') print() print('Exclude:', EXCLUDE_SCRIPTS) print() print('Results') print('=======') print() warnings = api.checkRecursive(CHECK_LIST, reporter) print() print('Total warnings: %d' % warnings)
def checkPath(filename, reporter=None): """ Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed """ if reporter is None: reporter = modReporter._makeDefaultReporter() try: f = open(filename, 'U') try: return check(f.read() + '\n', filename, reporter) finally: f.close() except UnicodeError: reporter.unexpectedError(filename, 'problem decoding source') except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1
def checkPath(filename, reporter=None): """ Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed """ if reporter is None: reporter = modReporter._makeDefaultReporter() try: with open(filename, "rb") as f: codestr = f.read() if sys.version_info < (2, 7): codestr += "\n" # Work around for Python <= 2.6 except UnicodeError: reporter.unexpectedError(filename, "problem decoding source") return 1 except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter)
def checkPath(filename, reporter=None): """ Check the given path, printing out any warnings detected. @param reporter: A L{Reporter} instance, where errors and warnings will be reported. @return: the number of warnings printed """ if reporter is None: reporter = modReporter._makeDefaultReporter() try: with open(filename, 'rb') as f: codestr = f.read() if sys.version_info < (2, 7): codestr += '\n' # Work around for Python <= 2.6 except UnicodeError: reporter.unexpectedError(filename, 'problem decoding source') return 1 except IOError: msg = sys.exc_info()[1] reporter.unexpectedError(filename, msg.args[1]) return 1 return check(codestr, filename, reporter)
def test_pyflakes(self): rep = reporter._makeDefaultReporter() error_count = checkRecursive(CHECK_DIRECTORYS, rep) self.assertEqual(error_count, 0, 'PyFlakes errors: %d' % error_count)
"""
def main(): my_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(my_dir, '..'))) from optparse import OptionParser parser = OptionParser() parser.add_option('--with-pep8', action='store_true', dest='with_pep8', default=True) parser.add_option('--with-pyflakes', action='store_true', dest='with_pyflakes', default=True) parser.add_option('--force-all', action='store_true', dest='force_all', default=False) parser.add_option('-v', '--verbose', action='count', dest='verbosity', default=0) parser.add_option('-q', '--quiet', action='count', dest='quietness', default=0) options, extra_args = parser.parse_args() has_pep8 = False try: import pep8 has_pep8 = True except ImportError: if options.with_pep8: sys.stderr.write('# Could not find pep8 library.') sys.exit(1) if has_pep8: guide_main = pep8.StyleGuide( ignore=['E402'], paths=['asyncflux/'], exclude=[], max_line_length=80, ) guide_tests = pep8.StyleGuide( ignore=['E221'], paths=['tests/'], max_line_length=80, ) for guide in (guide_main, guide_tests): report = guide.check_files() if report.total_errors: sys.exit(1) if options.with_pyflakes: try: import pyflakes assert pyflakes # silence pyflakes except ImportError: sys.stderr.write('# Could not find pyflakes library.\n') sys.exit(1) from pyflakes import api, reporter warnings = api.checkRecursive(['asyncflux', 'tests'], reporter._makeDefaultReporter()) if warnings > 0: sys.exit(1) suite = make_suite('', tuple(extra_args), options.force_all) runner = TextTestRunner(verbosity=options.verbosity - options.quietness + 1) result = runner.run(suite) sys.exit(not result.wasSuccessful())
'glob', 'types', 'pickle', 'zlib', 'struct', 'fractions', 'socket', ] for entry in external_modules: importlib.import_module(entry) lib_modules_ext[entry] = dir(sys.modules[entry]) python_files = bin_files + lib_files + bin_files_2 modReporter.Reporter.syntaxError = my_exception reporter = modReporter._makeDefaultReporter() reporter.undefined_names = [] Checker.report = my_report Checker.undefined_names = [] Checker.unused_imports = [] pym.Message.to_list = my_to_list #python_files = glob.glob('../sphire/bin/sxchains.py') #python_files = glob.glob('../sphire/libpy/applications.py') rounds = 0 while True: rounds += 1 ok = 0 replace = 0 fatal = [0, []]
if self.filename not in IGNORE_FILES: print(messageClass(self.filename, *args, **kwargs)) ERRORS[str(messageClass)] = messageClass(self.filename, *args, **kwargs).to_list() def reset_lists(): GLOBAL_CHECKER.undefined_names = [] GLOBAL_CHECKER.unused_imports = [] GLOBAL_CHECKER.unused_var = [] GLOBAL_CHECKER.shadowed_var = [] GLOBAL_CHECKER.dublicated_funcs = [] modReporter.Reporter.syntaxError = my_exception GLOBAL_REPORTER = modReporter._makeDefaultReporter() GLOBAL_REPORTER.indent_error = [] GLOBAL_REPORTER.general_error = [] GLOBAL_CHECKER = Checker GLOBAL_CHECKER.report = my_report pym.Message.to_list = my_to_list def print_all_info(**kwargs): if PRINT_LINE: if kwargs['line_idx'] in PRINT_LINE: for key in sorted(kwargs.keys()): print(key, ':', kwargs[key]) print('')