pySim.log: apply cmd2 colors through _style()

The color scheme takes either
- a raw escape sequence like "\033[33m" (pySim-read,
pySim-prog, contrib/csv-to-pgsql.py)
- a cmd2 color object (pySim-shell)

Color of cmd2 >= 3.0.0 is a StrEnum, which led to
pySim-shell warnings like

  yellowWARNING: EF.DIR seems to be empty!

with a stray reset at the end.

Fixed by exclusing Enum from the raw sequence branch.

Change-Id: I8bae9fc3c54f1dab481d743d3b68e32e9d09267a
This commit is contained in:
Eric Wild
2026-09-23 17:51:04 +02:00
parent aeba4004de
commit 2b7abdcf96
2 changed files with 24 additions and 1 deletions
+2 -1
View File
@@ -24,6 +24,7 @@
# #
import logging import logging
import enum
import cmd2 import cmd2
from packaging import version from packaging import version
@@ -126,7 +127,7 @@ class PySimLogger:
formatted_message = logging.Formatter.format(PySimLogger.__formatter, record) formatted_message = logging.Formatter.format(PySimLogger.__formatter, record)
color = PySimLogger.colors.get(record.levelno) color = PySimLogger.colors.get(record.levelno)
if color: if color:
if isinstance(color, str): if isinstance(color, str) and not isinstance(color, enum.Enum):
PySimLogger.print_callback(color + formatted_message + "\033[0m") PySimLogger.print_callback(color + formatted_message + "\033[0m")
else: else:
PySimLogger.print_callback(_style(formatted_message, fg = color)) PySimLogger.print_callback(_style(formatted_message, fg = color))
+22
View File
@@ -20,11 +20,20 @@
import unittest import unittest
import logging import logging
import cmd2
from packaging import version
from pySim.log import PySimLogger from pySim.log import PySimLogger
import io import io
import sys import sys
from inspect import currentframe, getframeinfo from inspect import currentframe, getframeinfo
if version.parse(cmd2.__version__) >= version.parse("3.0.0"):
from cmd2 import Color # pylint: disable=no-name-in-module
YELLOW = Color.YELLOW
else: # cmd2>=2.6.2
from cmd2 import Fg # pylint: disable=no-name-in-module
YELLOW = Fg.YELLOW
log = PySimLogger.get(__name__) log = PySimLogger.get(__name__)
TEST_MSG_DEBUG = "this is a debug message" TEST_MSG_DEBUG = "this is a debug message"
@@ -128,5 +137,18 @@ class PySimLogger_Test(unittest.TestCase):
expected_message = "CRITICAL: " + TEST_MSG_CRITICAL expected_message = "CRITICAL: " + TEST_MSG_CRITICAL
log.critical(TEST_MSG_CRITICAL) log.critical(TEST_MSG_CRITICAL)
def test_05_color(self):
# A color is either
# - raw escape sequence
# - cmd2 color object
global expected_message
expected_message = "\033[33mWARNING: " + TEST_MSG_WARNING + "\033[0m"
PySimLogger.setup(self._test_print_callback, {logging.WARN: "\033[33m"})
log.warning(TEST_MSG_WARNING)
PySimLogger.setup(self._test_print_callback, {logging.WARN: YELLOW})
log.warning(TEST_MSG_WARNING) # don't leak cmd2 Color StrEnum
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()