util package¶
The util package: general-purpose building blocks for Python applications – persistence, attributes with inheritance, commands with undo and a command-line parser, the observer pattern, preferences, and some Tk widgets (a terminal, an attribute editor, dialogs, tooltips). It came out of Semantic Nets, but doesn’t depend on it.
This module sets up logging. Modules get their loggers with
util.getLogger(__name__): an application can supply its own getLogger()
in its top-level package, which is then used instead (see getLogger()), and
set up the log file with setupLogger().
- util._loggingSetUp: bool = False¶
Whether setupLogger() has been called (by the application, or by getLogger() for want of it).
- class util.Logger(name, level=0)¶
Bases:
LoggerA logging.Logger with a print() method too (see util.getLogger()).
- print(*args, **kwargs)¶
Intended to mimic the print system command but allowing for redirection and multiple destinations if necessary.
- Parameters:
args
kwargs
- util.getLogger(name: str)¶
Create or find a Logger for name. This should be called as util.getLogger(__name__).
- Parameters:
name (str)
- Returns:
- Return type:
- util.setupLogger(loggerClass: type | None = None, logFileName: str | None = None)¶
Set up the logger to log to a log file and to stderr.
- Parameters:
loggerClass (type(logging.Logger)|None) – A logging.Logger subtype to set the loggerClass to.
logFileName (str|None) – The name of the file to log to. By default it will be the stem (filename only) of current executable, and it will be in the current directory. If it doesn’t have a file extension, “.log” will be appended. A relative name is put in the user’s log folder instead (eg: ~/Library/Logs/<program>/: see util.platformSupport.logFolder()) when the program is packaged (eg: a .app) or the current directory can’t be written.
- util._freshLogFile(logFileName: str) str¶
- Returns:
logFileName, emptied (the last run’s log is removed); or, if it can’t be removed because another copy of the program has it open (as on Windows, where an open file can’t be removed), the first of “<name>-2.log”, “<name>-3.log”, … that can.
- class util.DynamicStderrHandler(*args: object, **kwargs: object)¶
Bases:
StreamHandlerA StreamHandler that always writes to the CURRENT sys.stderr at emit time, rather than whatever sys.stderr was when this handler was constructed.
Useful when sys.stderr is reassigned later (e.g. redirected into a GUI terminal widget or a LoggerWriter) and you want log output to follow it.
- __init__(*args: object, **kwargs: object) None¶
- Parameters:
args (object)
kwargs (object)
- property stream: object¶
Always return the current sys.stderr, not a frozen reference.
- Returns:
The live sys.stderr object.
- Return type:
object
- util._getTopLevelPackageName() str | None¶
Determine the NAME of __main__’s top-level enclosing package, purely by inspecting sys.modules and walking the file system – this never imports anything as a side effect.
This used to also resolve (and, if necessary, import) the module object itself, but that’s exactly what caused a nasty bootstrapping hazard: this gets called (via getLogger()) from module-level code all over pythonUtils, e.g. util.persistence.serialize calls
util.getLogger(__name__)while IT is still being imported, and if the app’s own top-level package (e.g. “sn”) is the thing needing pythonUtils to finish loading in the first place, forcing an import of “sn” right here re-enters that same still-in-progress import chain and blows up with a “partially initialized module” ImportError. Callers now do their ownsys.modules.get(name)lookup (see getLogger()) so a not-yet-imported top-level package is simply reported as “not available yet” rather than force-imported.- Returns:
The top-level package’s name, or None if __main__ was run as a standalone script or from an interactive session with no enclosing package.
- Return type:
str|None
- util._getLogger(name: str) Logger¶
Return a properly typed SNLogger for the molule who’s __name__ is given in name. This may be either created of just returned, depending on if it exists already.
- Parameters:
name (str) – Always call this with the __name__ variable for the file.
- Returns:
The properly typed SNLogger for created.
- Return type:
SNLogger
Subpackages¶
- util.persistence package
- Submodules
- util.persistence.pRef module
- util.persistence.serialize module
VERSIONHEADBODYOLD_HEADEROLD_ROOTHEAD_FORMATHEAD_FORMAT_VERSIONHEAD_SERIALIZATION_VERSIONHEAD_APPLICATIONHEAD_APPLICATION_VERSIONHEAD_TYPEHEAD_SAVEDHeadValueisHeadValue()SerializablestrdictInstantiationInfogetInstantiationInfo()ParamInfoPropertyInfoDEFAULT_STRATEGYSerializationStrategy_Reference
- util.persistence.serializeJSON module
- util.persistence.serializePlist module
- util.persistence.serializeXML module
- util.persistence.serializeXML2 module
- util.persistence.serializeXML3 module
- Submodules
Submodules¶
- util.abstractGraph module
- util.actionDialog module
- util.attribute module
RestrictionTypesRestrictionTypes.UNRESTRICTEDRestrictionTypes.NOINHERITRestrictionTypes.NOOVERRIDERestrictionTypes.ILLEGALRestrictionTypes.PRIVATERestrictionTypes._generate_next_value_()RestrictionTypes._boundary_RestrictionTypes._flag_mask_RestrictionTypes._singles_mask_RestrictionTypes._all_bits_RestrictionTypes._inverted_
restrictionTypesToString()restrictionTypesFromString()RestrictionVAR_DEFAULTEDVARCONST_TYPEOVERRIDELOCALTYPEONLYUNINHERITEDTYPENAMECONSTNoValueisValidType()FALSE_STRINGScoerceValue()typeAsString()typeAsCanonical()AttributeAttributedObjectAttributedObject.getInstantiationInfo()AttributedObject.__init__()AttributedObject.setDirty()AttributedObject.isDirty()AttributedObject.get()AttributedObject.getLocal()AttributedObject.getLocalAttr()AttributedObject.getInh()AttributedObject.getInhAttr()AttributedObject.getAttr()AttributedObject.__getitem__()AttributedObject.__setitem__()AttributedObject.keys()AttributedObject.values()AttributedObject.items()AttributedObject.setAttr()AttributedObject.getSupers()AttributedObject.isIndividual()AttributedObject.isType()AttributedObject.isValueEditable()AttributedObject.isTypeEditable()AttributedObject.isQualifierEditable()AttributedObject._validateOverride()AttributedObject._getRestriction()AttributedObject._getSuperAttr()
- util.attributeEditor module
GROUP_SEPARATORGROUP_BACKGROUNDTREE_INDENTisHiddenKey()treeOrder()editAttrsBox()applyEditAttrsBox()_updateWith()_keyedMessage()getEditedAttrsCommandObj()clearGrid()ChangeDescrSYS_ATTRIBUTESItemMakerListEditorListEditor.MAX_HEIGHTListEditor.__init__()ListEditor.stateListEditor.buttonsListEditor._height()ListEditor.getList()ListEditor.setList()ListEditor._selected()ListEditor._select()ListEditor._updateButtons()ListEditor.add()ListEditor.remove()ListEditor.move()ListEditor.editSelected()ListEditor.config()ListEditor.configure()
ColorEditorAttrEditorAttrEditor.collapsedGroupsAttrEditor.HIDEABLE_COLUMNSAttrEditor.__init__()AttrEditor.listItemMakersAttrEditor.hideColumnsAttrEditor.displayValuesAttrEditor.attrsAttrEditor.varsAttrEditor.disabledAttrEditor.rowsAttrEditor.editKeyAttrEditor.editWidgetAttrEditor.noteEditsAttrEditor.treeModeAttrEditor._labelsAttrEditor._groupSpansAttrEditor._groupHeadersAttrEditor._hiddenWidgetsAttrEditor.rEditorsAttrEditor.rMessageAttrEditor.rEnterAttrEditor.rButtons1AttrEditor.rButtons2AttrEditor.rowsPerEntryAttrEditor.EntryOffsetAttrEditor.cStatusAttrEditor.cLabelAttrEditor.cEditAttrEditor.cKindAttrEditor.cNoteAttrEditor.cDelAttrEditor.cspanAttrEditor.outerSpanAttrEditor.show()AttrEditor._validateUpdates()AttrEditor._onReturn()AttrEditor._placeOverParent()AttrEditor.dismiss()AttrEditor.addNewAttribute()AttrEditor._addNewAttribute2()AttrEditor._showEntry()AttrEditor.deleteAttr()AttrEditor.typeInconsistent()AttrEditor.resetKind()AttrEditor.editTypeAnswer()AttrEditor.editType()AttrEditor.hasChanged()AttrEditor._saveKey()AttrEditor.save()AttrEditor.getEditorForType()AttrEditor.makeNewEntry()AttrEditor.makeGroupHeader()AttrEditor.toggleGroup()AttrEditor._noteFor()AttrEditor.makeNoteButton()AttrEditor.editNote()AttrEditor.makeTitle()AttrEditor.addTooltip()AttrEditor._applyHiddenColumns()AttrEditor.makeHeader()AttrEditor.makeEditor()AttrEditor.makeButton()AttrEditor.makeLabel()AttrEditor.makeKind()AttrEditor.setStatus()AttrEditor.setMessage()AttrEditor.clearMessage()AttrEditor.ask()AttrEditor.checkInt()AttrEditor.checkFloat()AttrEditor.conf()
HierarchicalAttrEditorHierarchicalAttrEditor.__init__()HierarchicalAttrEditor.assertedKeysHierarchicalAttrEditor.makeNewEntry()HierarchicalAttrEditor.assertAttr()HierarchicalAttrEditor.makeHeader()HierarchicalAttrEditor.makeQuals()HierarchicalAttrEditor.hasChanged()HierarchicalAttrEditor._effectiveRestriction()HierarchicalAttrEditor._restrictionChanged()HierarchicalAttrEditor._saveKey()
_convertValue()_defaultValue()
- util.command module
- util.commandParser module
AbbrevSubParsersAction_AbbrevChoicesArgumentParserfunNameToCommandName()commandNameToFunName()ParsableSubParsableCommandGeneratorNonMutatingCommandGeneratorGenFromFunctionMutatingCommandGeneratorGenFromCommandRedoCommandNoValueIntermediateCommandWordTopCommandParserTopCommandParser.__init__()TopCommandParser.descriptionTopCommandParser.doListTopCommandParser.defaultsTopCommandParser.decodersTopCommandParser.debugTopCommandParser.argsTopCommandParser.currentContextClassTopCommandParser.addCommand()TopCommandParser._makeParser()TopCommandParser._strToComList()TopCommandParser._comListToStr()TopCommandParser.parseLine()TopCommandParser.lastArgs()TopCommandParser.parse()TopCommandParser.loadCommands()TopCommandParser._abc_impl
CommandContextCommandContext.commandSynonymsCommandContext.optionSynonymsCommandContext.commandHelpCommandContext.__init__()CommandContext.parserCommandContext.doListCommandContext.defaultsCommandContext.decodersCommandContext._captureCommandContext._defineDecoders()CommandContext._setCapture()CommandContext.help()CommandContext.debug()CommandContext.undo()CommandContext.redo()CommandContext.default()CommandContext._Default
CompositeCommandCompositeCommandMgrfixKwargs()
- util.dirtyable module
- util.errorReportingObject module
ErrorReportingObjectErrorReportingObject.__init__()ErrorReportingObject.assertToStatusReport()ErrorReportingObject.validate()ErrorReportingObject.statusReport()ErrorReportingObject.clearStatusReport()ErrorReportingObject.showErrorActionDialog()ErrorReportingObject.status()ErrorReportingObject._STATUSErrorReportingObject.statsInt()
- util.observer module
enabledalwaysLaterSubjectObserver
- util.platformSupport module
- util.prefs module
- util.rtValuesDialog module
ParamSliderInfoRTValueDialogRTValueDialog.COL_NAMERTValueDialog.COL_VALUERTValueDialog.COL_VAL_DISPRTValueDialog.COL_DEFRTValueDialog.__init__()RTValueDialog.pairsRTValueDialog.show()RTValueDialog.on_dismiss()RTValueDialog.makeEntries()RTValueDialog.appendSlider()RTValueDialog.sliderCallbackHandler()RTValueDialog.__setitem__()RTValueDialog.__getitem__()
- util.singleInstance module
- util.terminal module
PromptTypeOnLineTypeResultToStringFunTypeAbstractTerminalAbstractTerminal.__init__()AbstractTerminal.onLineAbstractTerminal._promptAbstractTerminal.resultToStringFunAbstractTerminal.oldOutAbstractTerminal.oldErrAbstractTerminal.oldInputAbstractTerminal.lastExecutionResultAbstractTerminal.promptAbstractTerminal.input()AbstractTerminal.printLine()
PlainTextTerminalLineBufferedStreamLineFilteringStreamwriteToRealConsole()TerminalRegistryTerminalRegistry.__init__()TerminalRegistry._byThreadTerminalRegistry._focusedMainThreadTargetTerminalRegistry._windowsTerminalRegistry.registerWindow()TerminalRegistry.unregisterWindow()TerminalRegistry.bindThreadToTerminal()TerminalRegistry.unbindThread()TerminalRegistry.resolveTerminal()TerminalRegistry._resolveActiveWindowTerminal()TerminalRegistry.onFocusIn()TerminalRegistry.onFocusOut()
_exists()LineBufferedRoutingStreamTerminalLogHandlerinstallGlobalIORouting()inputAsync()TerminalWidgetTerminalWidget.__init__()TerminalWidget.registryTerminalWidget.historyTerminalWidget.historyIndexTerminalWidget.styleTagsTerminalWidget.adHocTagCacheTerminalWidget._workerThreadTerminalWidget._replyQueueTerminalWidget._awaitingReplyTerminalWidget.queryFlashColorTerminalWidget._flashJobTerminalWidget._lastErrorTimeTerminalWidget._atLineStart()TerminalWidget._writePrompt()TerminalWidget._currentLine()TerminalWidget._replaceCurrentLine()TerminalWidget._handleReturn()TerminalWidget._runCommand()TerminalWidget._finishCommand()TerminalWidget.input()TerminalWidget.inputAsync()TerminalWidget._showInputPrompt()TerminalWidget._startQueryFlash()TerminalWidget.flash()TerminalWidget._noteErrorLine()TerminalWidget._flashTick()TerminalWidget._stopQueryFlash()TerminalWidget.destroy()TerminalWidget._handleCtrlD()TerminalWidget._handleUp()TerminalWidget._handleDown()TerminalWidget._handleBackspace()TerminalWidget._guardEditableRegion()TerminalWidget.registerStyle()TerminalWidget._getAdHocTag()TerminalWidget.printLine()TerminalWidget.wrap()
_EofSentinel
- util.tooltip module
findCanvas()CreateToolTipCreateToolTip.__init__()CreateToolTip.delete()CreateToolTip.enter()CreateToolTip.leave()CreateToolTip.schedule()CreateToolTip.unschedule()CreateToolTip.showtip()CreateToolTip.WATCH_INTERVALCreateToolTip.appActive()CreateToolTip.pointerOver()CreateToolTip.stillWanted()CreateToolTip.watch()CreateToolTip.hidetip()
- util.urlDialog module
- util.utils module
makeParserFromFunc()resolveAliases()splitOnSeparator()quoteIfNecessary()_CMD_MASK_ALT_MASKs_CMD()s_SHIFT()s_CTL()s_ALT()s_OPT()strToBool()WINDOWSisWindowsPath()openFile()urlPath()pathURL()isValidURL()REMOTE_TIMEOUTwebCacheFoldercachePath()cachedCopy()OfflineWarningfetchURL()urlExists()canWriteUrl()fixURL()fileToUrl()urlToFile()openUrl()addDefaultExtToURL()getNameAndExtFromURL()changeUrlExtension()makeConcrete()getFullClassName()getClass()_classesByPathgetFullyQualifiedClass()_findFullyQualifiedClass()getClassFromFullyQualifiedName()findSubclasses()_originOf()findConcreteSubclasses()importSubmodules()getCallerIdInfoStr()extendsDoc()delOne()grouped()removeDuplicates()removeDuplicatesInPlace()flattenPairs()treeFlatten()treeSplit()ExtendedEnumMetaExtendedFlagplay()xmlEscape()xmlUnescape()xmlToStringIndented()PointIndiciPointpointInRect()shiftRectToPoint()overlaps()pointInPoly()midpoint()expandRect()normalizeRect()iterableToList()getSubMenu()getToplevelWindows()getMenuBar()_findEntry()_separatedItems_separate()_lastItemskeepLast()_endIndex()addToMenuBar()addCheckToMenuBar()removeFromMenuBar()isGuiAvailable()askViaTk()askViaTerminal()askYesNo()askUser()VerticalScrolledFramewheelSteps()wheelEvents()bindRightMouse()tag_bindRightMouse()tag_unbindRightMouse()eventEqual()dialogOwner()ownDialog()showExceptionDialog()allSubclasses()allConcreteSubclasses()Categories
- util.validatedList module