diff --git a/docs/source/docs/api-reference.rst b/docs/source/docs/api-reference.rst index 6897761..16e1982 100644 --- a/docs/source/docs/api-reference.rst +++ b/docs/source/docs/api-reference.rst @@ -22,7 +22,7 @@ This example showcases some of its features: # store compiled MIBs by calling this function def store_mibs(mibName, jsonDoc, cbCtx): - print('# MIB module %s' % mibName) + print(f'# MIB module {mibName}') print(jsonDoc) mibCompiler = MibCompiler( diff --git a/examples/always-borrow-precompiled-pysnmp-files.py b/examples/always-borrow-precompiled-pysnmp-files.py index 3546310..e50c517 100644 --- a/examples/always-borrow-precompiled-pysnmp-files.py +++ b/examples/always-borrow-precompiled-pysnmp-files.py @@ -38,4 +38,4 @@ # run MIB compilation results = mibCompiler.compile(*inputMibs) -print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results])) +print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}") diff --git a/examples/borrow-precompiled-pysnmp-files-on-failure.py b/examples/borrow-precompiled-pysnmp-files-on-failure.py index 9d5e8fd..5442b0c 100644 --- a/examples/borrow-precompiled-pysnmp-files-on-failure.py +++ b/examples/borrow-precompiled-pysnmp-files-on-failure.py @@ -46,4 +46,4 @@ # run non-recursive MIB compilation results = mibCompiler.compile(*inputMibs) -print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results])) +print("Results: {', '.join(f'{x}:{results[x]}' for x in results}") diff --git a/examples/compile-smistar-mibs-into-pysnmp-files-if-needed.py b/examples/compile-smistar-mibs-into-pysnmp-files-if-needed.py index e96a5e3..9322e79 100644 --- a/examples/compile-smistar-mibs-into-pysnmp-files-if-needed.py +++ b/examples/compile-smistar-mibs-into-pysnmp-files-if-needed.py @@ -50,4 +50,4 @@ # run [possibly recursive] MIB compilation results = mibCompiler.compile(*inputMibs) # , rebuild=True, genTexts=True) -print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results])) +print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}") diff --git a/examples/compile-smiv2-mibs-from-text-into-pysnmp-code.py b/examples/compile-smiv2-mibs-from-text-into-pysnmp-code.py index 70120f3..04a7f92 100644 --- a/examples/compile-smiv2-mibs-from-text-into-pysnmp-code.py +++ b/examples/compile-smiv2-mibs-from-text-into-pysnmp-code.py @@ -40,4 +40,4 @@ # run non-recursive MIB compilation results = mibCompiler.compile(*inputMibs, **dict(noDeps=True)) -print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results])) +print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}") diff --git a/examples/download-and-compile-smistar-mibs-into-json.py b/examples/download-and-compile-smistar-mibs-into-json.py index 30897e3..3c2c21f 100644 --- a/examples/download-and-compile-smistar-mibs-into-json.py +++ b/examples/download-and-compile-smistar-mibs-into-json.py @@ -14,6 +14,7 @@ from pysmi.parser import SmiStarParser from pysmi.codegen import JsonCodeGen from pysmi.compiler import MibCompiler +import os # from pysmi import debug @@ -25,7 +26,7 @@ def printOut(mibName, jsonDoc, cbCtx): - print("\n\n# MIB module %s" % mibName) + print(f"{os.linesep}{os.linesep}# MIB module {mibName}") print(jsonDoc) @@ -45,4 +46,4 @@ def printOut(mibName, jsonDoc, cbCtx): # run recursive MIB compilation results = mibCompiler.compile(*inputMibs) -print("\n# Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results])) +print(f"{os.linesep}# Results: {'', ''.join(f'{x}:{results[x]}' for x in results)}") diff --git a/examples/download-and-compile-smistar-mibs-into-pysnmp-files.py b/examples/download-and-compile-smistar-mibs-into-pysnmp-files.py index c193dfc..7695098 100644 --- a/examples/download-and-compile-smistar-mibs-into-pysnmp-files.py +++ b/examples/download-and-compile-smistar-mibs-into-pysnmp-files.py @@ -39,4 +39,4 @@ # run non-recursive MIB compilation results = mibCompiler.compile(*inputMibs, **dict(noDeps=True)) -print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results])) +print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}") diff --git a/pysmi/borrower/base.py b/pysmi/borrower/base.py index cae5c19..d19c239 100644 --- a/pysmi/borrower/base.py +++ b/pysmi/borrower/base.py @@ -28,9 +28,7 @@ def __init__(self, reader, genTexts=False): self._reader = reader def __str__(self): - return "{}{{{}, genTexts={}, exts={}}}".format( - self.__class__.__name__, self._reader, self.genTexts, self.exts - ) + return f"{self.__class__.__name__}{{{self._reader}, genTexts={self.genTexts}, exts={self.exts}}}" def setOptions(self, **kwargs): self._reader.setOptions(**kwargs) diff --git a/pysmi/codegen/intermediate.py b/pysmi/codegen/intermediate.py index 9586a95..04d8259 100644 --- a/pysmi/codegen/intermediate.py +++ b/pysmi/codegen/intermediate.py @@ -168,7 +168,7 @@ def regSym( moduleCompliance=False, ): if symbol in self._seenSyms and symbol not in self._importMap: - raise error.PySmiSemanticError("Duplicate symbol found: %s" % symbol) + raise error.PySmiSemanticError(f"Duplicate symbol found: {symbol}") self.addToExports(symbol, moduleIdentity) self._out[symbol] = outDict @@ -202,9 +202,9 @@ def genNumericOid(self, oid): continue if module not in self.symbolTable: - # XXX do getname for possible future borrowed mibs + # TODO: do getname for possible future borrowed mibs raise error.PySmiSemanticError( - 'no module "%s" in symbolTable' % module + f'no module "{module}" in symbolTable' ) if parent not in self.symbolTable[module]: @@ -222,7 +222,7 @@ def genNumericOid(self, oid): def getBaseType(self, symName, module): if module not in self.symbolTable: - raise error.PySmiSemanticError('no module "%s" in symbolTable' % module) + raise error.PySmiSemanticError(f'no module "{module}" in symbolTable') if symName not in self.symbolTable[module]: raise error.PySmiSemanticError( @@ -233,7 +233,7 @@ def getBaseType(self, symName, module): "syntax", (("", ""), "") ) if not symType[0]: - raise error.PySmiSemanticError('unknown type for symbol "%s"' % symName) + raise error.PySmiSemanticError(f'unknown type for symbol "{symName}"') if symType[0] in self.baseTypes: return symType, symSubtype @@ -767,8 +767,7 @@ def genDefVal(self, data, objname=None): else: raise error.PySmiSemanticError( - 'unknown type "%s" for defval "%s" of symbol "%s"' - % (defvalType, defval, objname) + f'unknown type "{defvalType}" for defval "{defval}" of symbol "{objname}"' ) return {"default": outDict} @@ -866,7 +865,7 @@ def genOid(self, data): out += (el[1],) # XXX Do we need to create a new object el[0]? else: - raise error.PySmiSemanticError("unknown datatype for OID: %s" % el) + raise error.PySmiSemanticError(f"unknown datatype for OID: {el}") return ".".join([str(x) for x in self.genNumericOid(out)]), parent @@ -885,17 +884,17 @@ def genTime(self, data): if len(timeStr) == 11: timeStr = "19" + timeStr - # XXX raise in strict mode + # TODO: raise in strict mode # elif lenTimeStr != 13: - # raise error.PySmiSemanticError("Invalid date %s" % t) + # raise error.PySmiSemanticError(f"Invalid date {t}") try: times.append( strftime("%Y-%m-%d %H:%M", strptime(timeStr, "%Y%m%d%H%MZ")) ) except ValueError: - # XXX raise in strict mode - # raise error.PySmiSemanticError("Invalid date %s: %s" % (t, sys.exc_info()[1])) + # TODO: raise in strict mode + # raise error.PySmiSemanticError(f"Invalid date {t}") timeStr = "197001010000Z" # dummy date for dates with typos times.append( strftime("%Y-%m-%d %H:%M", strptime(timeStr, "%Y%m%d%H%MZ")) @@ -1068,7 +1067,7 @@ def genCode(self, ast, symbolTable, **kwargs): true_sym = sym[len(RESERVED_KEYWORDS_PREFIX) :] if true_sym not in self._out: - raise error.PySmiCodegenError("No generated code for symbol %s" % sym) + raise error.PySmiCodegenError(f"No generated code for symbol {sym}") outDict[sym] = self._out[true_sym] @@ -1079,8 +1078,7 @@ def genCode(self, ast, symbolTable, **kwargs): outDict["meta"]["comments"] = kwargs["comments"] debug.logger & debug.flagCodegen and debug.logger( - "canonical MIB name %s (%s), imported MIB(s) %s" - % (self.moduleName[0], moduleOid, ",".join(importedModules) or "") + f"canonical MIB name {self.moduleName[0]} ({moduleOid}), imported MIB(s) {','.join(importedModules) or ''}" ) return ( diff --git a/pysmi/codegen/jsondoc.py b/pysmi/codegen/jsondoc.py index ba072ac..3e82d6e 100644 --- a/pysmi/codegen/jsondoc.py +++ b/pysmi/codegen/jsondoc.py @@ -60,18 +60,10 @@ def genCode(self, ast, symbolTable, **kwargs): except jinja2.exceptions.TemplateError: err = sys.exc_info()[1] - raise error.PySmiCodegenError("Jinja template rendering error: %s" % err) + raise error.PySmiCodegenError(f"Jinja template rendering error: {err}") debug.logger & debug.flagCodegen and debug.logger( - "canonical MIB name %s (%s), imported MIB(s) %s, rendered from " - "%s, JSON document size %d bytes" - % ( - mibInfo.name, - mibInfo.identity, - ",".join(mibInfo.imported) or "", - dstTemplate, - len(text), - ) + f"canonical MIB name {mibInfo.name} ({mibInfo.identity}), imported MIB(s) {','.join(mibInfo.imported) or ''}, rendered from {dstTemplate}, JSON document size {len(text)} bytes" ) return mibInfo, text @@ -90,9 +82,7 @@ def genIndex(self, processed, **kwargs): outDict.update(json.loads(kwargs["old_index_data"])) except Exception: - raise error.PySmiCodegenError( - "Index load error: %s" % sys.exc_info()[1] - ) + raise error.PySmiCodegenError(f"Index load error: {sys.exc_info()[1]}") def order(top): if isinstance(top, dict): @@ -165,7 +155,7 @@ def order(top): outDict["meta"]["comments"] = kwargs["comments"] debug.logger & debug.flagCodegen and debug.logger( - "OID->MIB index built, %s entries" % len(processed) + f"OID->MIB index built, {len(processed)} entries" ) return json.dumps(order(outDict), indent=2) diff --git a/pysmi/codegen/null.py b/pysmi/codegen/null.py index 11f035f..728e7ed 100644 --- a/pysmi/codegen/null.py +++ b/pysmi/codegen/null.py @@ -17,7 +17,7 @@ class NullCodeGen(AbstractCodeGen): def genCode(self, ast, symbolTable, **kwargs): debug.logger & debug.flagCodegen and debug.logger( - "%s invoked" % self.__class__.__name__ + f"{self.__class__.__name__} invoked" ) return MibInfo(oid=None, name="", imported=[]), "" diff --git a/pysmi/codegen/pysnmp.py b/pysmi/codegen/pysnmp.py index d7b4f0d..3898c8e 100644 --- a/pysmi/codegen/pysnmp.py +++ b/pysmi/codegen/pysnmp.py @@ -153,18 +153,10 @@ def translateOids(dct): except jinja2.exceptions.TemplateError: err = sys.exc_info()[1] - raise error.PySmiCodegenError("Jinja template rendering error: %s" % err) + raise error.PySmiCodegenError(f"Jinja template rendering error: {err}") debug.logger & debug.flagCodegen and debug.logger( - "canonical MIB name %s (%s), imported MIB(s) %s, rendered from " - "%s, Python code size %d bytes" - % ( - mibInfo.name, - mibInfo.identity, - ",".join(mibInfo.imported) or "", - dstTemplate, - len(text), - ) + f"canonical MIB name {mibInfo.name} ({mibInfo.identity}), imported MIB(s) {','.join(mibInfo.imported) or ''}, rendered from {dstTemplate}, Python code size {len(text)} bytes" ) return mibInfo, text diff --git a/pysmi/codegen/symtable.py b/pysmi/codegen/symtable.py index 7f30b73..0bf3bff 100644 --- a/pysmi/codegen/symtable.py +++ b/pysmi/codegen/symtable.py @@ -187,7 +187,7 @@ def regSym(self, symbol, symProps, parents=()): if ( symbol in self._out or symbol in self._postponedSyms ): # add to strict mode - or symbol in self._importMap: - raise error.PySmiSemanticError("Duplicate symbol found: %s" % symbol) + raise error.PySmiSemanticError(f"Duplicate symbol found: {symbol}") if self.allParentsExists(parents): self._out[symbol] = symProps @@ -506,7 +506,7 @@ def genOid(self, data, classmode=False): out += (el[1],) # XXX Do we need to create a new object el[0]? else: - raise error.PySmiSemanticError("unknown datatype for OID: %s" % el) + raise error.PySmiSemanticError(f"unknown datatype for OID: {el}") return out @@ -644,24 +644,19 @@ def genCode(self, ast, symbolTable, **kwargs): if self._postponedSyms: raise error.PySmiSemanticError( - "Unknown parents for symbols: %s" % ", ".join(self._postponedSyms) + f"Unknown parents for symbols: {', '.join(self._postponedSyms)}" ) for sym in self._parentOids: if sym not in self._out and sym not in self._importMap: - raise error.PySmiSemanticError("Unknown parent symbol: %s" % sym) + raise error.PySmiSemanticError(f"Unknown parent symbol: {sym}") self._out["_symtable_order"] = list(self._symsOrder) self._out["_symtable_cols"] = list(self._cols) self._out["_symtable_rows"] = list(self._rows) debug.logger & debug.flagCodegen and debug.logger( - "canonical MIB name {} ({}), imported MIB(s) {}, Symbol table size {} symbols".format( - self.moduleName[0], - moduleOid, - ",".join(importedModules) or "", - len(self._out), - ) + f"canonical MIB name {self.moduleName[0]} ({moduleOid}), imported MIB(s) {','.join(importedModules) or ''}, Symbol table size {len(self._out)} symbols" ) return ( diff --git a/pysmi/compiler.py b/pysmi/compiler.py index 32fb56f..bc69bcb 100644 --- a/pysmi/compiler.py +++ b/pysmi/compiler.py @@ -109,7 +109,7 @@ def addSources(self, *sources): self._sources.extend(sources) debug.logger & debug.flagCompiler and debug.logger( - "current MIB source(s): %s" % ", ".join([str(x) for x in self._sources]) + f"current MIB source(s): {', '.join(map(str, self._sources))}" ) return self @@ -131,8 +131,7 @@ def addSearchers(self, *searchers): self._searchers.extend(searchers) debug.logger & debug.flagCompiler and debug.logger( - "current compiled MIBs location(s): %s" - % ", ".join([str(x) for x in self._searchers]) + f"current compiled MIBs location(s): {', '.join(map(str, self._searchers))}" ) return self @@ -156,7 +155,7 @@ def addBorrowers(self, *borrowers): self._borrowers.extend(borrowers) debug.logger & debug.flagCompiler and debug.logger( - "current MIB borrower(s): %s" % ", ".join([str(x) for x in self._borrowers]) + f"current MIB borrower(s): {', '.join(map(str, self._borrowers))}" ) return self @@ -218,19 +217,19 @@ class instances (values) if mibname in parsedMibs: debug.logger & debug.flagCompiler and debug.logger( - "MIB %s already parsed" % mibname + f"MIB {mibname} already parsed" ) continue if mibname in failedMibs: debug.logger & debug.flagCompiler and debug.logger( - "MIB %s already failed" % mibname + f"MIB {mibname} already failed" ) continue for source in self._sources: debug.logger & debug.flagCompiler and debug.logger( - "trying source %s" % source + f"trying source {source}" ) try: @@ -256,12 +255,7 @@ class instances (values) canonicalMibNames[mibInfo.name].append(fileInfo.name) debug.logger & debug.flagCompiler and debug.logger( - "{} ({}) read from {}, immediate dependencies: {}".format( - mibInfo.name, - mibname, - fileInfo.path, - ", ".join(mibInfo.imported) or "", - ) + f"{mibInfo.name} ({mibname}) read from {fileInfo.path}, immediate dependencies: {', '.join(mibInfo.imported) or ''}" ) break @@ -281,16 +275,10 @@ class instances (values) exc_class, exc, tb = sys.exc_info() exc.source = source exc.mibname = mibname - exc.msg += " at MIB %s" % mibname + exc.msg += f" at MIB {mibname}" debug.logger & debug.flagCompiler and debug.logger( - "{}error {} from {}".format( - options.get("ignoreErrors") - and "ignoring " - or "failing on ", - exc, - source, - ) + f"{options.get('ignoreErrors') and 'ignoring ' or 'failing on '} {exc} from {source}" ) failedMibs[mibname] = exc @@ -298,10 +286,10 @@ class instances (values) processed[mibname] = statusFailed.setOptions(error=exc) else: - exc = error.PySmiError("MIB source %s not found" % mibname) + exc = error.PySmiError(f"MIB source {mibname} not found") exc.mibname = mibname debug.logger & debug.flagCompiler and debug.logger( - "no %s found everywhere" % mibname + f"no {mibname} found anywhere" ) if mibname not in failedMibs: @@ -320,7 +308,7 @@ class instances (values) fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( - "checking if %s requires updating" % mibname + f"checking if {mibname} requires updating" ) for searcher in self._searchers: @@ -347,7 +335,7 @@ class instances (values) exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname - exc.msg += " at MIB %s" % mibname + exc.msg += f" at MIB {mibname}" debug.logger & debug.flagCompiler and debug.logger( f"error from {searcher}: {exc}" ) @@ -355,12 +343,12 @@ class instances (values) else: debug.logger & debug.flagCompiler and debug.logger( - "no suitable compiled MIB %s found anywhere" % mibname + f"no suitable compiled MIB {mibname} found anywhere" ) if options.get("noDeps") and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( - "excluding imported MIB %s from code generation" % mibname + f"excluding imported MIB {mibname} from code generation" ) del parsedMibs[mibname] processed[mibname] = statusUntouched @@ -384,12 +372,10 @@ class instances (values) platform_info, user_info = self._get_system_info() comments = [ - "ASN.1 source %s" % fileInfo.path, + f"ASN.1 source {fileInfo.path}", f"Produced by {packageName}-{packageVersion} at {time.asctime()}", - "On host {} platform {} version {} by user {}".format( - platform_info[1], platform_info[0], platform_info[2], user_info[0] - ), - "Using Python version %s" % sys.version.split("\n")[0], + f"On host {platform_info[1]} platform {platform_info[0]} version {platform_info[2]} by user {user_info[0]}", + f"Using Python version {sys.version.split('\n')[0]}", ] try: @@ -413,7 +399,7 @@ class instances (values) exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname - exc.msg += " at MIB %s" % mibname + exc.msg += f" at MIB {mibname}" debug.logger & debug.flagCompiler and debug.logger( f"error from {self._codegen}: {exc}" @@ -435,7 +421,7 @@ class instances (values) for mibname in failedMibs.copy(): if options.get("noDeps") and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( - "excluding imported MIB %s from borrowing" % mibname + f"excluding imported MIB {mibname} from borrowing" ) continue @@ -476,7 +462,7 @@ class instances (values) for mibname in borrowedMibs.copy(): debug.logger & debug.flagCompiler and debug.logger( - "checking if failed MIB %s requires borrowing" % mibname + f"checking if failed MIB {mibname} requires borrowing" ) fileInfo, mibInfo, mibData = borrowedMibs[mibname] @@ -505,7 +491,7 @@ class instances (values) exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname - exc.msg += " at MIB %s" % mibname + exc.msg += f" at MIB {mibname}" debug.logger & debug.flagCompiler and debug.logger( f"error from {searcher}: {exc}" @@ -514,18 +500,18 @@ class instances (values) continue else: debug.logger & debug.flagCompiler and debug.logger( - "no suitable compiled MIB %s found anywhere" % mibname + f"no suitable compiled MIB {mibname} found anywhere" ) if options.get("noDeps") and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( - "excluding imported MIB %s from borrowing" % mibname + f"excluding imported MIB {mibname} from borrowing" ) processed[mibname] = statusUntouched else: debug.logger & debug.flagCompiler and debug.logger( - "will borrow MIB %s" % mibname + f"will borrow MIB {mibname}" ) builtMibs[mibname] = borrowedMibs[mibname] @@ -544,9 +530,7 @@ class instances (values) # if failedMibs and not options.get("ignoreErrors"): - debug.logger & debug.flagCompiler and debug.logger( - "failing with problem MIBs %s" % ", ".join(failedMibs) - ) + debug.logger & debug.flagCompiler and debug.logger(f"failing with problem MIBs: {", ".join(failedMibs)}") for mibname in builtMibs: processed[mibname] = statusUnprocessed @@ -554,9 +538,7 @@ class instances (values) return processed debug.logger & debug.flagCompiler and debug.logger( - "proceeding with built MIBs {}, failed MIBs {}".format( - ", ".join(builtMibs), ", ".join(failedMibs) - ) + f"proceeding with built MIBs {', '.join(builtMibs)}, failed MIBs {', '.join(failedMibs)}" ) # @@ -589,11 +571,10 @@ class instances (values) compliance=mibInfo.compliance, ) - except error.PySmiError: - exc_class, exc, tb = sys.exc_info() + except error.PySmiError as exc: exc.handler = self._codegen exc.mibname = mibname - exc.msg += " at MIB %s" % mibname + exc.msg += f" at MIB {mibname}" debug.logger & debug.flagCompiler and debug.logger( f"error {exc} from {self._writer}" @@ -603,11 +584,9 @@ class instances (values) failedMibs[mibname] = exc del builtMibs[mibname] + modified_mibs = [x for x in processed if processed[x] in ("compiled", "borrowed")] debug.logger & debug.flagCompiler and debug.logger( - "MIBs modified: %s" - % ", ".join( - [x for x in processed if processed[x] in ("compiled", "borrowed")] - ) + f"MIBs modified: {', '.join(modified_mibs)}" ) return processed @@ -617,10 +596,8 @@ def buildIndex(self, processedMibs, **options): comments = [ f"Produced by {packageName}-{packageVersion} at {time.asctime()}", - "On host {} platform {} version {} by user {}".format( - platform_info[1], platform_info[0], platform_info[2], user_info[0] - ), - "Using Python version %s" % sys.version.split("\n")[0], + f"On host {platform_info[1]} platform {platform_info[0]} version {platform_info[2]} by user {user_info[0]}", + f"Using Python version {sys.version.split('\n')[0]}", ] try: @@ -635,7 +612,7 @@ def buildIndex(self, processedMibs, **options): ) except error.PySmiError: exc_class, exc, tb = sys.exc_info() - exc.msg += " at MIB index %s" % self.indexFile + exc.msg += f" at MIB index {self.indexFile}" debug.logger & debug.flagCompiler and debug.logger( f"error {exc} when building {self.indexFile}" diff --git a/pysmi/debug.py b/pysmi/debug.py index 741d76d..913e8e8 100644 --- a/pysmi/debug.py +++ b/pysmi/debug.py @@ -94,7 +94,7 @@ def __init__(self, *flags, **options): else: self._printer = Printer() - self("running pysmi version %s" % __version__) + self(f"running pysmi version {__version__}") for flag in flags: inverse = flag and flag[0] in ("!", "~") @@ -109,13 +109,9 @@ def __init__(self, *flags, **options): self._flags |= flagMap[flag] except KeyError: - raise error.PySmiError("bad debug flag %s" % flag) + raise error.PySmiError(f"bad debug flag {flag}") - self( - "debug category '{}' {}".format( - flag, inverse and "disabled" or "enabled" - ) - ) + self(f"debug category '{flag}' {'disabled' if inverse else 'enabled'}") def __str__(self): return f"logger {self._printer}, flags {self._flags:x}" diff --git a/pysmi/error.py b/pysmi/error.py index 6eafef7..8c9126c 100644 --- a/pysmi/error.py +++ b/pysmi/error.py @@ -22,16 +22,7 @@ def __init__(self, *args, **kwargs): setattr(self, k, kwargs[k]) def __repr__(self): - return "{}({})".format( - self.__class__.__name__, - ", ".join( - [ - f"{k}={getattr(self, k)!r}" - for k in dir(self) - if k[0] != "_" and k != "args" - ] - ), - ) + return f"{self.__class__.__name__}({', '.join([f'{k}={getattr(self, k)!r}' for k in dir(self) if k[0] != '_' and k != 'args'] )})" def __str__(self): return self.msg @@ -41,7 +32,7 @@ class PySmiLexerError(PySmiError): lineno = "?" def __str__(self): - return self.msg + ", line %s" % self.lineno + return f"{self.msg}, line {self.lineno}" class PySmiParserError(PySmiLexerError): diff --git a/pysmi/lexer/smi.py b/pysmi/lexer/smi.py index 926804d..12649dd 100644 --- a/pysmi/lexer/smi.py +++ b/pysmi/lexer/smi.py @@ -194,10 +194,10 @@ def t_comment_body(self, t): def t_UPPERCASE_IDENTIFIER(self, t): r'[A-Z][-a-zA-z0-9]*' if t.value in self.forbidden_words: - raise error.PySmiLexerError("%s is forbidden" % t.value, lineno=t.lineno) + raise error.PySmiLexerError(f"{t.value} is forbidden", lineno=t.lineno) if t.value[-1] == '-': - raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) + raise error.PySmiLexerError(f"Identifier should not end with '-': {t.value}", lineno=t.lineno) t.type = self.reserved.get(t.value, 'UPPERCASE_IDENTIFIER') @@ -206,7 +206,7 @@ def t_UPPERCASE_IDENTIFIER(self, t): def t_LOWERCASE_IDENTIFIER(self, t): r'[0-9]*[a-z][-a-zA-z0-9]*' if t.value[-1] == '-': - raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) + raise error.PySmiLexerError(f"Identifier should not end with '-': {t.value}", lineno=t.lineno) return t def t_NUMBER(self, t): @@ -229,7 +229,7 @@ def t_NUMBER(self, t): t.type = 'NUMBER64' else: - raise error.PySmiLexerError("Number %s is too big" % t.value, lineno=t.lineno) + raise error.PySmiLexerError(f"Number {t.value} is too big", lineno=t.lineno) return t @@ -238,9 +238,9 @@ def t_BIN_STRING(self, t): value = t.value[1:-2] while value and value[0] == '0' and len(value) % 8: value = value[1:] - # XXX raise in strict mode + # TODO: raise in strict mode # if len(value) % 8: - # raise error.PySmiLexerError("Number of 0s and 1s have to divide by 8 in binary string %s" % t.value, lineno=t.lineno) + # raise error.PySmiLexerError(f"Number of 0s and 1s have to divide by 8 in binary string {t.value}", lineno=t.lineno) return t def t_HEX_STRING(self, t): @@ -248,9 +248,9 @@ def t_HEX_STRING(self, t): value = t.value[1:-2] while value and value[0] == '0' and len(value) % 2: value = value[1:] - # XXX raise in strict mode + # TODO: raise in strict mode # if len(value) % 2: - # raise error.PySmiLexerError("Number of symbols have to be even in hex string %s" % t.value, lineno=t.lineno) + raise error.PySmiLexerError(f"Number of symbols have to be even in hex string {t.value}", lineno=t.lineno) return t def t_QUOTED_STRING(self, t): @@ -353,7 +353,7 @@ def lexerFactory(**grammarOptions): for option in grammarOptions: if grammarOptions[option]: if option not in relaxedGrammar: - raise error.PySmiError('Unknown lexer relaxation option: %s' % option) + raise error.PySmiError(f'Unknown lexer relaxation option: {option}') for func in relaxedGrammar[option]: classAttr[func.__name__] = func() diff --git a/pysmi/parser/smi.py b/pysmi/parser/smi.py index f014732..0fcb3a8 100644 --- a/pysmi/parser/smi.py +++ b/pysmi/parser/smi.py @@ -1476,7 +1476,7 @@ def parserFactory(**grammarOptions): for option in grammarOptions: if grammarOptions[option]: if option not in relaxedGrammar: - raise error.PySmiError("Unknown parser relaxation option: %s" % option) + raise error.PySmiError(f"Unknown parser relaxation option: {option}") for func in relaxedGrammar[option]: classAttr[func.__name__] = func diff --git a/pysmi/reader/httpclient.py b/pysmi/reader/httpclient.py index a5afdda..587fb15 100644 --- a/pysmi/reader/httpclient.py +++ b/pysmi/reader/httpclient.py @@ -54,13 +54,7 @@ def __init__(self, url): self.session = session() - self._user_agent = "pysmi-{}; python-{}.{}.{}; {}".format( - pysmi_version, - sys.version_info[0], - sys.version_info[1], - sys.version_info[2], - sys.platform, - ) + self._user_agent = f"pysmi-{pysmi_version}; python-{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}; {sys.platform}" def __str__(self): return self._url @@ -70,7 +64,7 @@ def getData(self, mibname, **options): mibname = decode(mibname) - debug.logger & debug.flagReader and debug.logger("looking for MIB %s" % mibname) + debug.logger & debug.flagReader and debug.logger(f"looking for MIB {mibname}") for mibalias, mibfile in self.getMibVariants(mibname, **options): if self.MIB_MAGIC in self._url: @@ -79,7 +73,7 @@ def getData(self, mibname, **options): url = self._url + mibfile debug.logger & debug.flagReader and debug.logger( - "trying to fetch MIB from %s" % url + f"trying to fetch MIB from {url}" ) try: @@ -92,7 +86,7 @@ def getData(self, mibname, **options): continue debug.logger & debug.flagReader and debug.logger( - "HTTP response %s" % response.status_code + f"HTTP response {response.status_code}" ) if response.status_code == 200: @@ -106,14 +100,12 @@ def getData(self, mibname, **options): except Exception: debug.logger & debug.flagReader and debug.logger( - "malformed HTTP headers: %s" % sys.exc_info()[1] + f"malformed HTTP headers: {sys.exc_info()[1]}" ) mtime = time.time() debug.logger & debug.flagReader and debug.logger( - "fetching source MIB {}, mtime {}".format( - url, response.headers["Last-Modified"] - ) + f"fetching source MIB {url}, mtime {response.headers['Last-Modified']}" ) return MibInfo( @@ -121,5 +113,5 @@ def getData(self, mibname, **options): ), response.content.decode("utf-8") raise error.PySmiReaderFileNotFoundError( - "source MIB %s not found" % mibname, reader=self + f"source MIB {mibname} not found", reader=self ) diff --git a/pysmi/reader/localfile.py b/pysmi/reader/localfile.py index 50b1376..26c5318 100644 --- a/pysmi/reader/localfile.py +++ b/pysmi/reader/localfile.py @@ -103,28 +103,21 @@ def getMibVariants(self, mibname, **options): def getData(self, mibname, **options): debug.logger & debug.flagReader and debug.logger( - "{}looking for MIB {}".format( - self._recursive and "recursively " or "", mibname - ) + f"looking for MIB {mibname}{' recursively' if self._recursive else ''}" ) for path in self.getSubdirs(self._path, self._recursive, self._ignoreErrors): for mibalias, mibfile in self.getMibVariants(mibname, **options): f = os.path.join(decode(path), decode(mibfile)) - debug.logger & debug.flagReader and debug.logger("trying MIB %s" % f) + debug.logger & debug.flagReader and debug.logger(f"trying MIB {f}") if os.path.exists(f) and os.path.isfile(f): try: mtime = os.stat(f)[8] debug.logger & debug.flagReader and debug.logger( - "source MIB {} mtime is {}, fetching data...".format( - f, - time.strftime( - "%a, %d %b %Y %H:%M:%S GMT", time.gmtime(mtime) - ), - ) + f"source MIB {f} mtime is {time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(mtime))}, fetching data..." ) fp = open(f, mode="rb") @@ -132,10 +125,10 @@ def getData(self, mibname, **options): fp.close() if len(mibData) == self.maxMibSize: - raise OSError("MIB %s too large" % f) + raise OSError(f"MIB {f} too large") return MibInfo( - path="file://%s" % f, + path=f"file://{f}", file=mibfile, name=mibalias, mtime=mtime, @@ -152,9 +145,9 @@ def getData(self, mibname, **options): ) raise error.PySmiReaderFileNotModifiedError( - "source MIB %s is older than needed" % f, reader=self + f"source MIB {f} is older than needed", reader=self ) raise error.PySmiReaderFileNotFoundError( - "source MIB %s not found" % mibname, reader=self + f"source MIB {mibname} not found", reader=self ) diff --git a/pysmi/reader/url.py b/pysmi/reader/url.py index ae4eef8..d3f446b 100644 --- a/pysmi/reader/url.py +++ b/pysmi/reader/url.py @@ -39,6 +39,6 @@ def getReadersFromUrls(*sourceUrls, **options): readers.append(HttpReader(sourceUrl).setOptions(**options)) else: - raise error.PySmiError("Unsupported URL scheme %s" % sourceUrl) + raise error.PySmiError(f"Unsupported URL scheme {sourceUrl}") return readers diff --git a/pysmi/reader/zipreader.py b/pysmi/reader/zipreader.py index b25eb26..5af2d87 100644 --- a/pysmi/reader/zipreader.py +++ b/pysmi/reader/zipreader.py @@ -170,11 +170,11 @@ def getData(self, mibname, **options): if not self._members: raise error.PySmiReaderFileNotFoundError( - "source MIB %s not found" % mibname, reader=self + f"source MIB {mibname} not found", reader=self ) for mibalias, mibfile in self.getMibVariants(mibname, **options): - debug.logger & debug.flagReader and debug.logger("trying MIB %s" % mibfile) + debug.logger & debug.flagReader and debug.logger(f"trying MIB {mibfile}") try: refs = self._members[mibfile] @@ -188,12 +188,7 @@ def getData(self, mibname, **options): continue debug.logger & debug.flagReader and debug.logger( - "source MIB {}, mtime {}, read from {}/{}".format( - mibfile, - time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(mtime)), - self._name, - mibfile, - ) + f"source MIB {mibfile}, mtime {time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(mtime))}, read from {self._name}/{mibfile}" ) if len(mibData) == self.maxMibSize: @@ -207,5 +202,5 @@ def getData(self, mibname, **options): ), decode(mibData) raise error.PySmiReaderFileNotFoundError( - "source MIB %s not found" % mibname, reader=self + f"source MIB {mibname} not found", reader=self ) diff --git a/pysmi/scripts/mibcopy.py b/pysmi/scripts/mibcopy.py index 93073af..fa39283 100644 --- a/pysmi/scripts/mibcopy.py +++ b/pysmi/scripts/mibcopy.py @@ -36,12 +36,12 @@ def start(): dryrunFlag = False ignoreErrorsFlag = False - helpMessage = """\ - Usage: {} [--help] + helpMessage = f"""\ + Usage: {sys.argv[0]} [--help] [--version] [--verbose] [--quiet] - [--debug=<{}>] + [--debug=<{"|".join(sorted(debug.flagMap))}>] [--mib-source=] [--cache-directory=] [--ignore-errors] @@ -52,9 +52,7 @@ def start(): Use @mib@ placeholder token in URI to refer directly to the required MIB module when source does not support directory listing (e.g. HTTP). - """.format( - sys.argv[0], "|".join([x for x in sorted(debug.flagMap)]) - ) + """ # TODO(etingof): add the option to copy MIBs into enterprise-indexed subdirs @@ -82,7 +80,7 @@ def start(): for opt in opts: if opt[0] == "-h" or opt[0] == "--help": sys.stderr.write( - """\ + f"""\ Synopsis: SNMP SMI/MIB files copying tool. When given MIB file(s) or directory(ies) on input and a destination directory, the tool parses MIBs to figure out @@ -93,9 +91,8 @@ def start(): Documentation: https://www.pysnmp.com/pysmi - %s + {helpMessage} """ - % helpMessage ) sys.exit(EX_OK) @@ -103,14 +100,12 @@ def start(): from pysmi import __version__ sys.stderr.write( - """\ - SNMP SMI/MIB library version {}, written by Ilya Etingof - Python interpreter: {} + f"""\ + SNMP SMI/MIB library version {__version__}, written by Ilya Etingof + Python interpreter: {sys.version} Software documentation and support at https://www.pysnmp.com/pysmi - {} - """.format( - __version__, sys.version, helpMessage - ) + {helpMessage} + """ ) sys.exit(EX_OK) @@ -140,8 +135,7 @@ def start(): if len(inputMibs) < 2: sys.stderr.write( - "ERROR: MIB source and/or destination arguments not given\r\n%s\r\n" - % helpMessage + f"ERROR: MIB source and/or destination arguments not given{os.linesep}{helpMessage}{os.linesep}" ) sys.exit(EX_USAGE) @@ -149,7 +143,7 @@ def start(): if os.path.exists(dstDirectory) and not os.path.isdir(dstDirectory): sys.stderr.write( - "ERROR: given destination is not a directory\r\n%s\r\n" % helpMessage + f"ERROR: given destination '{dstDirectory}' is not a directory{os.linesep}{helpMessage}{os.linesep}" ) sys.exit(EX_USAGE) @@ -187,7 +181,7 @@ def getMibRevision(mibDir, mibFile): ) except error.PySmiError: - sys.stderr.write("ERROR: %s\r\n" % sys.exc_info()[1]) + sys.stderr.write(f"ERROR: {sys.exc_info()[1]}{os.linesep}") sys.exit(EX_SOFTWARE) for canonicalMibName in processed: @@ -205,7 +199,7 @@ def getMibRevision(mibDir, mibFile): return canonicalMibName, revision raise error.PySmiError( - 'Can\'t read or parse MIB "%s"' % os.path.join(mibDir, mibFile) + f'Can\'t read or parse MIB "{os.path.join(mibDir, mibFile)}"' ) def shortenPath(path, maxLength=45): @@ -220,7 +214,8 @@ def shortenPath(path, maxLength=45): for srcDirectory in inputMibs: if verboseFlag: - sys.stderr.write('Reading "%s"...\r\n' % srcDirectory) + if verboseFlag: + sys.stderr.write(f'Reading "{srcDirectory}"...{os.linesep}') if os.path.isfile(srcDirectory): mibFiles = [ @@ -253,8 +248,7 @@ def shortenPath(path, maxLength=45): if not quietFlag: sys.stderr.write( - "FAILED %s\r\n" - % shortenPath(os.path.join(srcDirectory, mibFile)) + f"FAILED {shortenPath(os.path.join(srcDirectory, mibFile))}{os.linesep}" ) mibsFailed += 1 @@ -271,9 +265,7 @@ def shortenPath(path, maxLength=45): except error.PySmiError as ex: if verboseFlag: sys.stderr.write( - 'MIB "%s" is not available at the ' - 'destination directory "%s": %s\r\n' - % (os.path.join(srcDirectory, mibFile), dstDirectory, ex) + f'MIB "{os.path.join(srcDirectory, mibFile)}" is not available at the destination directory "{dstDirectory}": {ex}{os.linesep}' ) dstMibRevision = datetime.fromtimestamp(0) @@ -283,18 +275,11 @@ def shortenPath(path, maxLength=45): if dstMibRevision >= srcMibRevision: if verboseFlag: sys.stderr.write( - 'Destination MIB "%s" has the same or newer revision as the ' - 'source MIB "%s"\r\n' - % ( - os.path.join(dstDirectory, mibName), - os.path.join(srcDirectory, mibFile), - ) + f'Destination MIB "{os.path.join(dstDirectory, mibName)}" has the same or newer revision as the source MIB "{os.path.join(srcDirectory, mibFile)}"{os.linesep}' ) if not quietFlag: sys.stderr.write( - "NOT COPIED {} ({})\r\n".format( - shortenPath(os.path.join(srcDirectory, mibFile)), mibName - ) + f"NOT COPIED {shortenPath(os.path.join(srcDirectory, mibFile))} ({mibName}){os.linesep}" ) continue @@ -302,14 +287,10 @@ def shortenPath(path, maxLength=45): mibsRevisions[mibName] = srcMibRevision if verboseFlag: - sys.stderr.write( - 'Copying "{}" (revision "{}") -> "{}" (revision "{}")\r\n'.format( - os.path.join(srcDirectory, mibFile), - srcMibRevision, - os.path.join(dstDirectory, mibName), - dstMibRevision, + if verboseFlag: + sys.stderr.write( + f'Copying "{os.path.join(srcDirectory, mibFile)}" (revision "{srcMibRevision}") -> "{os.path.join(dstDirectory, mibName)}" (revision "{dstMibRevision}"){os.linesep}' ) - ) try: shutil.copy( @@ -320,19 +301,12 @@ def shortenPath(path, maxLength=45): except Exception as ex: if verboseFlag: sys.stderr.write( - 'Failed to copy MIB "{}" -> "{}" ({}): "{}"\r\n'.format( - os.path.join(srcDirectory, mibFile), - os.path.join(dstDirectory, mibName), - mibName, - ex, - ) + f'Failed to copy MIB "{os.path.join(srcDirectory, mibFile)}" -> "{os.path.join(dstDirectory, mibName)}" ({mibName}): "{ex}"{os.linesep}' ) if not quietFlag: sys.stderr.write( - "FAILED {} ({})\r\n".format( - shortenPath(os.path.join(srcDirectory, mibFile)), mibName - ) + f"FAILED {shortenPath(os.path.join(srcDirectory, mibFile))} ({mibName}){os.linesep}" ) mibsFailed += 1 @@ -340,9 +314,7 @@ def shortenPath(path, maxLength=45): else: if not quietFlag: sys.stderr.write( - "COPIED {} ({})\r\n".format( - shortenPath(os.path.join(srcDirectory, mibFile)), mibName - ) + f"COPIED {shortenPath(os.path.join(srcDirectory, mibFile))} ({mibName}){os.linesep}" ) mibsCopied += 1 diff --git a/pysmi/scripts/mibdump.py b/pysmi/scripts/mibdump.py index c8b678a..ad3c903 100644 --- a/pysmi/scripts/mibdump.py +++ b/pysmi/scripts/mibdump.py @@ -57,12 +57,12 @@ def start(): buildIndexFlag = False writeMibsFlag = True - helpMessage = """\ - Usage: {} [--help] + helpMessage = f"""\ + Usage: {sys.argv[0]} [--help] [--version] [--quiet] [--strict] - [--debug=<{}>] + [--debug=<{"|".join(sorted(debug.flagMap))}>] [--mib-source=] [--mib-searcher=] [--mib-stub=] @@ -87,9 +87,8 @@ def start(): Use @mib@ placeholder token in URI to refer directly to the required MIB module when source does not support directory listing (e.g. HTTP). - FORMAT - pysnmp, json, null""".format( - sys.argv[0], "|".join([x for x in sorted(debug.flagMap)]) - ) + FORMAT - pysnmp, json, null""" + try: opts, inputMibs = getopt.getopt( @@ -131,14 +130,13 @@ def start(): for opt in opts: if opt[0] == "-h" or opt[0] == "--help": sys.stderr.write( - """\ + f"""\ Synopsis: SNMP SMI/MIB files conversion tool Documentation: https://www.pysnmp.com/pysmi - %s + {helpMessage} """ - % helpMessage ) sys.exit(EX_OK) @@ -146,14 +144,12 @@ def start(): from pysmi import __version__ sys.stderr.write( - """\ - SNMP SMI/MIB library version {}, written by Ilya Etingof - Python interpreter: {} + f"""\ + SNMP SMI/MIB library version {__version__}, written by Ilya Etingof + Python interpreter: {sys.version} Software documentation and support at https://www.pysnmp.com/pysmi - {} - """.format( - __version__, sys.version, helpMessage - ) + {helpMessage} + """ ) sys.exit(EX_OK) @@ -199,8 +195,7 @@ def start(): except ValueError: sys.stderr.write( - "ERROR: known Python optimization levels: -1, 0, 1, 2\r\n%s\r\n" - % helpMessage + f"ERROR: known Python optimization levels: -1, 0, 1, 2{os.linesep}{helpMessage}{os.linesep}" ) sys.exit(EX_USAGE) @@ -250,7 +245,7 @@ def start(): if not inputMibs: sys.stderr.write( - "ERROR: MIB modules names not specified\r\n%s\r\n" % helpMessage + f"ERROR: MIB module names not specified{os.linesep}{helpMessage}{os.linesep}" ) sys.exit(EX_USAGE) @@ -380,45 +375,26 @@ def start(): if verboseFlag: sys.stderr.write( - """Source MIB repositories: {} -Borrow missing/failed MIBs from: {} -Existing/compiled MIB locations: {} -Compiled MIBs destination directory: {} -MIBs excluded from code generation: {} -MIBs to compile: {} -Destination format: {} -Parser grammar cache directory: {} -Also compile all relevant MIBs: {} -Rebuild MIBs regardless of age: {} -Dry run mode: {} -Create/update MIBs: {} -Byte-compile Python modules: {} (optimization level {}) -Ignore compilation errors: {} -Generate OID->MIB index: {} -Generate texts in MIBs: {} -Keep original texts layout: {} -Try various file names while searching for MIB module: {} -""".format( - ", ".join(mibSources), - ", ".join([x[0] for x in mibBorrowers if x[1] == genMibTextsFlag]), - ", ".join(mibSearchers), - dstDirectory, - ", ".join(sorted(mibStubs)), - ", ".join(inputMibs), - dstFormat, - cacheDirectory or "not used", - nodepsFlag and "no" or "yes", - rebuildFlag and "yes" or "no", - dryrunFlag and "yes" or "no", - writeMibsFlag and "yes" or "no", - dstFormat == "pysnmp" and pyCompileFlag and "yes" or "no", - dstFormat == "pysnmp" and pyOptimizationLevel and "yes" or "no", - ignoreErrorsFlag and "yes" or "no", - buildIndexFlag and "yes" or "no", - genMibTextsFlag and "yes" or "no", - keepTextsLayout and "yes" or "no", - doFuzzyMatchingFlag and "yes" or "no", - ) + f"""\ +Source MIB repositories: {', '.join(mibSources)} +Borrow missing/failed MIBs from: {', '.join([x[0] for x in mibBorrowers if x[1] == genMibTextsFlag])} +Existing/compiled MIB locations: {', '.join(mibSearchers)} +Compiled MIBs destination directory: {dstDirectory} +MIBs excluded from code generation: {', '.join(sorted(mibStubs))} +MIBs to compile: {', '.join(inputMibs)} +Destination format: {dstFormat} +Parser grammar cache directory: {cacheDirectory or "not used"} +Also compile all relevant MIBs: {"no" if nodepsFlag else "yes"} +Rebuild MIBs regardless of age: {"yes" if rebuildFlag else "no"} +Dry run mode: {"yes" if dryrunFlag else "no"} +Create/update MIBs: {"yes" if writeMibsFlag else "no"} +Byte-compile Python modules: {"yes" if dstFormat == "pysnmp" and pyCompileFlag else "no"} (optimization level {"yes" if dstFormat == "pysnmp" and pyOptimizationLevel else "no"}) +Ignore compilation errors: {"yes" if ignoreErrorsFlag else "no"} +Generate OID->MIB index: {"yes" if buildIndexFlag else "no"} +Generate texts in MIBs: {"yes" if genMibTextsFlag else "no"} +Keep original texts layout: {"yes" if keepTextsLayout else "no"} +Try various file names while searching for MIB module: {"yes" if doFuzzyMatchingFlag else "no"} +""" ) # Initialize compiler infrastructure @@ -458,77 +434,40 @@ def start(): mibCompiler.buildIndex(safe, dryRun=dryrunFlag, ignoreErrors=True) except error.PySmiError: - sys.stderr.write("ERROR: %s\r\n" % sys.exc_info()[1]) + sys.stderr.write(f"ERROR: {sys.exc_info()[1]}{os.linesep}") sys.exit(EX_SOFTWARE) else: + sorted_files = sorted(processed) + compiled = [x for x in sorted_files if processed[x] == "compiled"] + borrowed = [x for x in sorted_files if processed[x] == 'borrowed'] + untouched = [x for x in sorted_files if processed[x] == 'untouched'] + missing = [x for x in sorted_files if processed[x] == 'missing'] + unprocessed = [x for x in sorted_files if processed[x] == 'unprocessed'] + failed = [x for x in sorted_files if processed[x] == 'failed'] if verboseFlag: sys.stdout.write( - "{}reated/updated MIBs: {}\r\n".format( - dryrunFlag and "Would be c" or "C", - ", ".join( - [ - "{}{}".format( - x, - x != processed[x].alias - and " (%s)" % processed[x].alias - or "", - ) - for x in sorted(processed) - if processed[x] == "compiled" - ] - ), - ) + f"{'Would be c' if dryrunFlag else 'C'}reated/updated MIBs: {', '.join([f'{x}{'' if x == processed[x].alias else f' ({processed[x].alias})'}' for x in compiled])}{os.linesep}" ) sys.stdout.write( - "Pre-compiled MIBs {}borrowed: {}\r\n".format( - dryrunFlag and "Would be " or "", - ", ".join( - [ - f"{x} ({processed[x].path})" - for x in sorted(processed) - if processed[x] == "borrowed" - ] - ), - ) + f"Pre-compiled MIBs {'Would be ' if dryrunFlag else ''}borrowed: " + f"{', '.join([f'{x} ({processed[x].path})' for x in borrowed])}{os.linesep}" ) sys.stdout.write( - "Up to date MIBs: %s\r\n" - % ", ".join( - ["%s" % x for x in sorted(processed) if processed[x] == "untouched"] - ) - ) + f"Up to date MIBs: {', '.join(x for x in untouched)}{os.linesep}") sys.stderr.write( - "Missing source MIBs: %s\n" - % "\n ".join( - ["%s" % x for x in sorted(processed) if processed[x] == "missing"] - ) - ) - + f"Missing source MIBs: {f'{os.linesep} '.join(x for x in missing)}{os.linesep}") sys.stderr.write( - "Ignored MIBs: %s\r\n" - % ", ".join( - [ - "%s" % x - for x in sorted(processed) - if processed[x] == "unprocessed" - ] - ) - ) + f"Ignored MIBs: {', '.join(x for x in unprocessed)}\n") sys.stderr.write( - "Failed MIBs: %s\n" - % "\n ".join( - [ - f"{x} ({processed[x].error})" - for x in sorted(processed) - if processed[x] == "failed" - ] - ) + f"Failed MIBs: " + f"{f'{os.linesep} '.join([f"{x} ({processed[x].error})" for x in failed])}{os.linesep}" ) + exitCode = EX_OK if any(x for x in processed.values() if x == "missing"): diff --git a/pysmi/searcher/anyfile.py b/pysmi/searcher/anyfile.py index 7825156..d20a6cd 100644 --- a/pysmi/searcher/anyfile.py +++ b/pysmi/searcher/anyfile.py @@ -32,7 +32,7 @@ def __str__(self): def fileExists(self, mibname, mtime, rebuild=False): if rebuild: debug.logger & debug.flagSearcher and debug.logger( - "pretend %s is very old" % mibname + f"pretend {mibname} is very old" ) return @@ -43,7 +43,7 @@ def fileExists(self, mibname, mtime, rebuild=False): f = basename + sfx if not os.path.exists(f) or not os.path.isfile(f): debug.logger & debug.flagSearcher and debug.logger( - "%s not present or not a file" % f + f"{f} not present or not a file" ) continue @@ -57,14 +57,12 @@ def fileExists(self, mibname, mtime, rebuild=False): ) debug.logger & debug.flagSearcher and debug.logger( - "found {}, mtime {}".format( - f, time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(fileTime)) - ) + f"found {f}, mtime {time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(fileTime))}" ) if fileTime >= mtime: raise error.PySmiFileNotModifiedError() raise error.PySmiFileNotFoundError( - "no compiled file %s found" % mibname, searcher=self + f"no compiled file {mibname} found", searcher=self ) diff --git a/pysmi/searcher/pyfile.py b/pysmi/searcher/pyfile.py index 9b0cf10..d499c81 100644 --- a/pysmi/searcher/pyfile.py +++ b/pysmi/searcher/pyfile.py @@ -52,7 +52,7 @@ def __str__(self): def fileExists(self, mibname, mtime, rebuild=False): if rebuild: debug.logger & debug.flagSearcher and debug.logger( - "pretend %s is very old" % mibname + f"pretend {mibname} is very old" ) return @@ -64,7 +64,7 @@ def fileExists(self, mibname, mtime, rebuild=False): if not os.path.exists(f) or not os.path.isfile(f): debug.logger & debug.flagSearcher and debug.logger( - "%s not present or not a file" % f + f"{f} not present or not a file" ) continue @@ -82,23 +82,18 @@ def fileExists(self, mibname, mtime, rebuild=False): pyData = pyData[4:] pyTime = struct.unpack("= mtime: raise error.PySmiFileNotModifiedError() else: raise error.PySmiFileNotFoundError( - "older file %s exists" % mibname, searcher=self + f"older file {mibname} exists", searcher=self ) else: - debug.logger & debug.flagSearcher and debug.logger( - "bad magic in %s" % f - ) + debug.logger & debug.flagSearcher and debug.logger(f"bad magic in {f}") continue for pySfx in SOURCE_SUFFIXES: @@ -106,7 +101,7 @@ def fileExists(self, mibname, mtime, rebuild=False): if not os.path.exists(f) or not os.path.isfile(f): debug.logger & debug.flagSearcher and debug.logger( - "%s not present or not a file" % f + f"{f} not present or not a file" ) continue @@ -120,14 +115,12 @@ def fileExists(self, mibname, mtime, rebuild=False): ) debug.logger & debug.flagSearcher and debug.logger( - "found {}, mtime {}".format( - f, time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(pyTime)) - ) + f"found {f}, mtime {time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(pyTime))}" ) if pyTime >= mtime: raise error.PySmiFileNotModifiedError() raise error.PySmiFileNotFoundError( - "no compiled file %s found" % mibname, searcher=self + f"no compiled file {mibname} found", searcher=self ) diff --git a/pysmi/searcher/pypackage.py b/pysmi/searcher/pypackage.py index 56c2dc0..429ee56 100644 --- a/pysmi/searcher/pypackage.py +++ b/pysmi/searcher/pypackage.py @@ -72,7 +72,7 @@ def _parseDosTime(dosdate, dostime): def fileExists(self, mibname, mtime, rebuild=False): if rebuild: debug.logger & debug.flagSearcher and debug.logger( - "pretend %s is very old" % mibname + f"pretend {mibname} is very old" ) return @@ -90,7 +90,7 @@ def fileExists(self, mibname, mtime, rebuild=False): elif hasattr(p, "__file__"): debug.logger & debug.flagSearcher and debug.logger( - "%s is not an egg, trying it as a package directory" % self._package + f"{self._package} is not an egg, trying it as a package directory" ) return PyFileSearcher(os.path.split(p.__file__)[0]).fileExists( mibname, mtime, rebuild=rebuild @@ -98,12 +98,12 @@ def fileExists(self, mibname, mtime, rebuild=False): else: raise error.PySmiFileNotFoundError( - "%s is neither importable nor a file" % self._package, searcher=self + f"{self._package} is neither importable nor a file", searcher=self ) except ImportError: raise error.PySmiFileNotFoundError( - "%s is not importable, trying as a path" % self._package, searcher=self + f"{self._package} is not importable, trying as a path", searcher=self ) for pySfx in BYTECODE_SUFFIXES: @@ -120,22 +120,17 @@ def fileExists(self, mibname, mtime, rebuild=False): pyData = pyData[4:] pyTime = struct.unpack("= mtime: raise error.PySmiFileNotModifiedError() else: raise error.PySmiFileNotFoundError( - "older file %s exists" % mibname, searcher=self + f"older file {mibname} exists", searcher=self ) else: - debug.logger & debug.flagSearcher and debug.logger( - "bad magic in %s" % f - ) + debug.logger & debug.flagSearcher and debug.logger(f"bad magic in {f}") continue for pySfx in SOURCE_SUFFIXES: @@ -152,15 +147,13 @@ def fileExists(self, mibname, mtime, rebuild=False): ) debug.logger & debug.flagSearcher and debug.logger( - "found {}, mtime {}".format( - f, time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(pyTime)) - ) + f"found {f}, mtime {time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(pyTime))}" ) if pyTime >= mtime: raise error.PySmiFileNotModifiedError() else: raise error.PySmiFileNotFoundError( - "older file %s exists" % mibname, searcher=self + f"older file {mibname} exists", searcher=self ) - raise error.PySmiFileNotFoundError("no file %s found" % mibname, searcher=self) + raise error.PySmiFileNotFoundError(f"no file {mibname} found", searcher=self) diff --git a/pysmi/searcher/stub.py b/pysmi/searcher/stub.py index 5e3d9ed..1719e89 100644 --- a/pysmi/searcher/stub.py +++ b/pysmi/searcher/stub.py @@ -22,23 +22,19 @@ def __init__(self, *mibnames): self._mibnames = mibnames def __str__(self): - return "%s" % self.__class__.__name__ + return self.__class__.__name__ def fileExists(self, mibname, mtime, rebuild=False): if mibname in self._mibnames: debug.logger & debug.flagSearcher and debug.logger( - "pretend compiled %s exists and is very new" % mibname + f"pretend compiled {mibname} exists and is very new" ) raise error.PySmiFileNotModifiedError( - "compiled file {} is among {}".format( - mibname, ", ".join(self._mibnames) - ), + f"compiled file {mibname} is among {', '.join(self._mibnames)}", searcher=self, ) raise error.PySmiFileNotFoundError( - "no compiled file {} found among {}".format( - mibname, ", ".join(self._mibnames) - ), + f"no compiled file {mibname} found among {', '.join(self._mibnames)}", searcher=self, ) diff --git a/pysmi/writer/callback.py b/pysmi/writer/callback.py index 2e13610..78a84bb 100644 --- a/pysmi/writer/callback.py +++ b/pysmi/writer/callback.py @@ -49,7 +49,7 @@ def putData(self, mibname, data, comments=(), dryRun=False): ) debug.logger & debug.flagWriter and debug.logger( - "user callback for %s succeeded" % mibname + f"user callback for {mibname} succeeded" ) def getData(self, filename): diff --git a/pysmi/writer/localfile.py b/pysmi/writer/localfile.py index 287a25c..63bf5e9 100644 --- a/pysmi/writer/localfile.py +++ b/pysmi/writer/localfile.py @@ -65,7 +65,7 @@ def putData(self, mibname, data, comments=(), dryRun=False): ) if comments: - data = "#\n" + "".join(["# %s\n" % x for x in comments]) + "#\n" + data + data = f"#{os.linesep}{os.linesep.join([f'# {x}' for x in comments])}{os.linesep}#{os.linesep}{data}" filename = os.path.join(self._path, decode(mibname)) + self.suffix diff --git a/pysmi/writer/pyfile.py b/pysmi/writer/pyfile.py index e79cae7..f7c1b52 100644 --- a/pysmi/writer/pyfile.py +++ b/pysmi/writer/pyfile.py @@ -66,7 +66,7 @@ def putData(self, mibname, data, comments=(), dryRun=False): ) if comments: - data = "#\n" + "".join(["# %s\n" % x for x in comments]) + "#\n" + data + data = f"#{os.linesep}{os.linesep.join([f'# {x}' for x in comments])}{os.linesep}#{os.linesep}{data}" pyfile = os.path.join(self._path, decode(mibname)) pyfile += SOURCE_SUFFIXES[0] @@ -88,7 +88,7 @@ def putData(self, mibname, data, comments=(), dryRun=False): f"failure writing file {pyfile}: {exc[1]}", file=pyfile, writer=self ) - debug.logger & debug.flagWriter and debug.logger("created file %s" % pyfile) + debug.logger & debug.flagWriter and debug.logger(f"created file {pyfile}") if self.pyCompile: try: @@ -109,7 +109,7 @@ def putData(self, mibname, data, comments=(), dryRun=False): writer=self, ) - debug.logger & debug.flagWriter and debug.logger("%s stored" % mibname) + debug.logger & debug.flagWriter and debug.logger(f"{mibname} stored") def getData(self, filename): return "" diff --git a/tests/test_typedeclaration_smiv1_pysnmp.py b/tests/test_typedeclaration_smiv1_pysnmp.py index 9090fdf..74fd0ce 100644 --- a/tests/test_typedeclaration_smiv1_pysnmp.py +++ b/tests/test_typedeclaration_smiv1_pysnmp.py @@ -64,7 +64,7 @@ def setUp(self): exec(codeobj, self.ctx, self.ctx) def protoTestSymbol(self, symbol, klass): - self.assertTrue(symbol in self.ctx, "symbol %s not present" % symbol) + self.assertTrue(symbol in self.ctx, f"Symbol {symbol} not present") def protoTestClass(self, symbol, klass): self.assertEqual( diff --git a/tests/test_typedeclaration_smiv2_pysnmp.py b/tests/test_typedeclaration_smiv2_pysnmp.py index 839223a..5851d54 100644 --- a/tests/test_typedeclaration_smiv2_pysnmp.py +++ b/tests/test_typedeclaration_smiv2_pysnmp.py @@ -102,7 +102,7 @@ def setUp(self): exec(codeobj, self.ctx, self.ctx) def protoTestSymbol(self, symbol, klass): - self.assertTrue(symbol in self.ctx, "symbol %s not present" % symbol) + self.assertTrue(symbol in self.ctx, f"symbol {symbol} not present") def protoTestClass(self, symbol, klass): self.assertEqual(