📄 checker.py
字号:
try: file = open(filename) except IOError: pass else: self._setupMainCode(file, filename, module) return self._initModule(module) return 1 def _initModule(self, module): self.module = module self.attributes = dir(self.module) pychecker_attr = getattr(module, Config.CHECKER_VAR, None) if pychecker_attr is not None : utils.pushConfig() utils.updateCheckerArgs(pychecker_attr, 'suppressions', 0, []) for tokenName in _filterDir(self.module, _DEFAULT_MODULE_TOKENS) : token = getattr(self.module, tokenName) if isinstance(token, types.ModuleType) : # get the real module name, tokenName could be an alias self.addModule(token.__name__) elif isinstance(token, types.FunctionType) : self.addFunction(token) elif isinstance(token, types.ClassType) or \ hasattr(token, '__bases__') : self.addClass(tokenName) else : self.addVariable(tokenName, type(token)) if pychecker_attr is not None : utils.popConfig() return 1 def setupMainCode(self) : file, filename, smt = _findModule(self.moduleName) # FIXME: if the smt[-1] == imp.PKG_DIRECTORY : load __all__ module = imp.load_module(self.moduleName, file, filename, smt) self._setupMainCode(file, filename, module) return module def _setupMainCode(self, file, filename, module): try : self.main_code = function.create_from_file(file, filename, module) finally : if file != None : file.close()def getAllModules() : "Returns a list of all modules that should be checked." modules = [] for module in _allModules.values() : if module.check : modules.append(module) return modules_BUILTIN_MODULE_ATTRS = { 'sys': [ 'ps1', 'ps2', 'tracebacklimit', 'exc_type', 'exc_value', 'exc_traceback', 'last_type', 'last_value', 'last_traceback', ], }def fixupBuiltinModules(needs_init=0): for moduleName in sys.builtin_module_names : if needs_init: _ = Module(moduleName, 0) module = _allModules.get(moduleName, None) if module is not None : try : m = imp.init_builtin(moduleName) except ImportError : pass else : extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, []) module.attributes = [ '__dict__' ] + dir(m) + extra_attrsdef _printWarnings(warnings, stream=None): if stream is None: stream = sys.stdout warnings.sort() lastWarning = None for warning in warnings : if lastWarning != None : # ignore duplicate warnings if cmp(lastWarning, warning) == 0 : continue # print blank line between files if lastWarning.file != warning.file : global _output _output.AddLines("\n") lastWarning = warning _output.AddLines(warning.format() + "\n")def processFiles(files, cfg = None, pre_process_cb = None) : # insert this here, so we find files in the local dir before std library if sys.path[0] != '' : sys.path.insert(0, '') # ensure we have a config object, it's necessary global _cfg if cfg is not None : _cfg = cfg elif _cfg is None : _cfg = Config.Config() warnings = [] utils.initConfig(_cfg) for moduleName, filename in getModules(files) : if callable(pre_process_cb) : pre_process_cb(moduleName) module = Module(moduleName, fullpath = filename) # reload the given module, otherwise won't get new syntax errors. sysModule = sys.modules.get(moduleName) if sysModule: try: reload(sysModule) except: pass module.load(warnings) utils.popConfig() return warningsdef getWarnings(files, cfg = None, suppressions = None): warnings = processFiles(files, cfg) fixupBuiltinModules() return warnings + warn.find(getAllModules(), _cfg, suppressions)def _print_processing(name) : if not _cfg.quiet : global _output, _statusDlg, _count txt = _("Processing %s...\n") % name _output.AddLines(txt) _count += 1 _statusDlg.Update(_count, txt) def checkSyntax(filename, messageView): """ Massively hacked version of main for ActiveGrid IDE integration """ global _cfg _cfg, files, suppressions = Config.setupFromArgs([filename]) if not files : return 0 global _output, _statusDlg, _count _output = messageView # wxBug: Need to show progress dialog box, or message window never gets updated until the method returns _statusDlg = wx.ProgressDialog(_("Check Code"), _("Checking %s") % filename, maximum = 100, style = wx.PD_AUTO_HIDE | wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME) _count = 0 # insert this here, so we find files in the local dir before std library if sys.path[0] != '' : sys.path.insert(0, '') importWarnings = processFiles(files, _cfg, _print_processing) fixupBuiltinModules() if _cfg.printParse : for module in getAllModules() : printer.module(module) warnings = warn.find(getAllModules(), _cfg, suppressions) _statusDlg.Update(100, _("Done")) _statusDlg.Destroy() if not _cfg.quiet : _output.AddLines(_("\nWarnings and Errors...\n")) if warnings or importWarnings : _printWarnings(importWarnings + warnings) return 1 if not _cfg.quiet : _output.AddLines(_("No Syntax Errors")) return 0 ######def main(argv) :## __pychecker__ = 'no-miximport'## import pychecker## if LOCAL_MAIN_VERSION != pychecker.MAIN_MODULE_VERSION :## sys.stderr.write(_VERSION_MISMATCH_ERROR)## sys.exit(100)#### # remove empty arguments## argv = filter(None, argv)## ## # if the first arg starts with an @, read options from the file## # after the @ (this is mostly for windows)## if len(argv) >= 2 and argv[1][0] == '@':## # read data from the file## command_file = argv[1][1:]## try:## f = open(command_file, 'r')## command_line = f.read()## f.close()## except IOError, err:## sys.stderr.write("Unable to read commands from file: %s\n %s\n" % \## (command_file, err))## sys.exit(101)#### # convert to an argv list, keeping argv[0] and the files to process## argv = argv[:1] + string.split(command_line) + argv[2:]## ## global _cfg## _cfg, files, suppressions = Config.setupFromArgs(argv[1:])## if not files :## return 0#### # insert this here, so we find files in the local dir before std library## sys.path.insert(0, '')#### importWarnings = processFiles(files, _cfg, _print_processing)## fixupBuiltinModules()## if _cfg.printParse :## for module in getAllModules() :## printer.module(module)#### warnings = warn.find(getAllModules(), _cfg, suppressions)## if not _cfg.quiet :## print "\nWarnings...\n"## if warnings or importWarnings :## _printWarnings(importWarnings + warnings)## return 1#### if not _cfg.quiet :## print "None"## return 0######if __name__ == '__main__' :## try :## sys.exit(main(sys.argv))## except Config.UsageError :## sys.exit(127)####else :## _orig__import__ = None## _suppressions = None## _warnings_cache = {}#### def _get_unique_warnings(warnings):## for i in range(len(warnings)-1, -1, -1):## w = warnings[i].format()## if _warnings_cache.has_key(w):## del warnings[i]## else:## _warnings_cache[w] = 1## return warnings#### def __import__(name, globals=None, locals=None, fromlist=None):## if globals is None:## globals = {}## if locals is None:## locals = {}## if fromlist is None:## fromlist = []#### check = not sys.modules.has_key(name) and name[:10] != 'pychecker.'## pymodule = _orig__import__(name, globals, locals, fromlist)## if check :## try :## module = Module(pymodule.__name__)## if module.initModule(pymodule):## warnings = warn.find([module], _cfg, _suppressions)## _printWarnings(_get_unique_warnings(warnings))## else :## print 'Unable to load module', pymodule.__name__## except Exception:## name = getattr(pymodule, '__name__', str(pymodule))## importError(name)#### return pymodule#### def _init() :## global _cfg, _suppressions, _orig__import__#### args = string.split(os.environ.get('PYCHECKER', ''))## _cfg, files, _suppressions = Config.setupFromArgs(args)## utils.initConfig(_cfg)## fixupBuiltinModules(1)#### # keep the orig __import__ around so we can call it## import __builtin__## _orig__import__ = __builtin__.__import__## __builtin__.__import__ = __import__#### if not os.environ.get('PYCHECKER_DISABLED') :## _init()##
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -