idf_monitor.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. #!/usr/bin/env python
  2. #
  3. # esp-idf serial output monitor tool. Does some helpful things:
  4. # - Looks up hex addresses in ELF file with addr2line
  5. # - Reset ESP32 via serial RTS line (Ctrl-T Ctrl-R)
  6. # - Run "make (or idf.py) flash" (Ctrl-T Ctrl-F)
  7. # - Run "make (or idf.py) app-flash" (Ctrl-T Ctrl-A)
  8. # - If gdbstub output is detected, gdb is automatically loaded
  9. #
  10. # Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. #
  24. # Contains elements taken from miniterm "Very simple serial terminal" which
  25. # is part of pySerial. https://github.com/pyserial/pyserial
  26. # (C)2002-2015 Chris Liechti <cliechti@gmx.net>
  27. #
  28. # Originally released under BSD-3-Clause license.
  29. #
  30. from __future__ import print_function, division
  31. import subprocess
  32. import argparse
  33. import codecs
  34. import re
  35. import os
  36. try:
  37. import queue
  38. except ImportError:
  39. import Queue as queue
  40. import shlex
  41. import time
  42. import sys
  43. import serial
  44. import serial.tools.miniterm as miniterm
  45. import threading
  46. import ctypes
  47. import types
  48. from distutils.version import StrictVersion
  49. key_description = miniterm.key_description
  50. # Control-key characters
  51. CTRL_A = '\x01'
  52. CTRL_B = '\x02'
  53. CTRL_F = '\x06'
  54. CTRL_H = '\x08'
  55. CTRL_R = '\x12'
  56. CTRL_T = '\x14'
  57. CTRL_Y = '\x19'
  58. CTRL_P = '\x10'
  59. CTRL_RBRACKET = '\x1d' # Ctrl+]
  60. # ANSI terminal codes
  61. ANSI_RED = '\033[1;31m'
  62. ANSI_YELLOW = '\033[0;33m'
  63. ANSI_NORMAL = '\033[0m'
  64. def color_print(message, color):
  65. """ Print a message to stderr with colored highlighting """
  66. sys.stderr.write("%s%s%s\n" % (color, message, ANSI_NORMAL))
  67. def yellow_print(message):
  68. color_print(message, ANSI_YELLOW)
  69. def red_print(message):
  70. color_print(message, ANSI_RED)
  71. __version__ = "1.0"
  72. # Tags for tuples in queues
  73. TAG_KEY = 0
  74. TAG_SERIAL = 1
  75. # regex matches an potential PC value (0x4xxxxxxx)
  76. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  77. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  78. class StoppableThread(object):
  79. """
  80. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  81. cancellation method.
  82. Can be started and stopped multiple times.
  83. Isn't an instance of type Thread because Python Thread objects can only be run once
  84. """
  85. def __init__(self):
  86. self._thread = None
  87. @property
  88. def alive(self):
  89. """
  90. Is 'alive' whenever the internal thread object exists
  91. """
  92. return self._thread is not None
  93. def start(self):
  94. if self._thread is None:
  95. self._thread = threading.Thread(target=self._run_outer)
  96. self._thread.start()
  97. def _cancel(self):
  98. pass # override to provide cancellation functionality
  99. def run(self):
  100. pass # override for the main thread behaviour
  101. def _run_outer(self):
  102. try:
  103. self.run()
  104. finally:
  105. self._thread = None
  106. def stop(self):
  107. if self._thread is not None:
  108. old_thread = self._thread
  109. self._thread = None
  110. self._cancel()
  111. old_thread.join()
  112. class ConsoleReader(StoppableThread):
  113. """ Read input keys from the console and push them to the queue,
  114. until stopped.
  115. """
  116. def __init__(self, console, event_queue):
  117. super(ConsoleReader, self).__init__()
  118. self.console = console
  119. self.event_queue = event_queue
  120. def run(self):
  121. self.console.setup()
  122. try:
  123. while self.alive:
  124. try:
  125. if os.name == 'nt':
  126. # Windows kludge: because the console.cancel() method doesn't
  127. # seem to work to unblock getkey() on the Windows implementation.
  128. #
  129. # So we only call getkey() if we know there's a key waiting for us.
  130. import msvcrt
  131. while not msvcrt.kbhit() and self.alive:
  132. time.sleep(0.1)
  133. if not self.alive:
  134. break
  135. c = self.console.getkey()
  136. except KeyboardInterrupt:
  137. c = '\x03'
  138. if c is not None:
  139. self.event_queue.put((TAG_KEY, c), False)
  140. finally:
  141. self.console.cleanup()
  142. def _cancel(self):
  143. if os.name == 'posix':
  144. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  145. # older pyserial (3.1+) has cancellation implemented via 'select',
  146. # which does not work when console sends an escape sequence response
  147. #
  148. # even older pyserial (<3.1) does not have this method
  149. #
  150. # on Windows there is a different (also hacky) fix, applied above.
  151. #
  152. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  153. # TODO: introduce some workaround to make it work there.
  154. import fcntl, termios
  155. fcntl.ioctl(self.console.fd, termios.TIOCSTI, b'\0')
  156. class SerialReader(StoppableThread):
  157. """ Read serial data from the serial port and push to the
  158. event queue, until stopped.
  159. """
  160. def __init__(self, serial, event_queue):
  161. super(SerialReader, self).__init__()
  162. self.baud = serial.baudrate
  163. self.serial = serial
  164. self.event_queue = event_queue
  165. if not hasattr(self.serial, 'cancel_read'):
  166. # enable timeout for checking alive flag,
  167. # if cancel_read not available
  168. self.serial.timeout = 0.25
  169. def run(self):
  170. if not self.serial.is_open:
  171. self.serial.baudrate = self.baud
  172. self.serial.rts = True # Force an RTS reset on open
  173. self.serial.open()
  174. self.serial.rts = False
  175. try:
  176. while self.alive:
  177. data = self.serial.read(self.serial.in_waiting or 1)
  178. if len(data):
  179. self.event_queue.put((TAG_SERIAL, data), False)
  180. finally:
  181. self.serial.close()
  182. def _cancel(self):
  183. if hasattr(self.serial, 'cancel_read'):
  184. try:
  185. self.serial.cancel_read()
  186. except:
  187. pass
  188. class Monitor(object):
  189. """
  190. Monitor application main class.
  191. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  192. purpose.
  193. Main difference is that all event processing happens in the main thread, not the worker threads.
  194. """
  195. def __init__(self, serial_instance, elf_file, make="make", toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF"):
  196. super(Monitor, self).__init__()
  197. self.event_queue = queue.Queue()
  198. self.console = miniterm.Console()
  199. if os.name == 'nt':
  200. sys.stderr = ANSIColorConverter(sys.stderr)
  201. self.console.output = ANSIColorConverter(self.console.output)
  202. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  203. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  204. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  205. def getkey_patched(self):
  206. c = self.enc_stdin.read(1)
  207. if c == unichr(0x7f):
  208. c = unichr(8) # map the BS key (which yields DEL) to backspace
  209. return c
  210. self.console.getkey = types.MethodType(getkey_patched, self.console)
  211. self.serial = serial_instance
  212. self.console_reader = ConsoleReader(self.console, self.event_queue)
  213. self.serial_reader = SerialReader(self.serial, self.event_queue)
  214. self.elf_file = elf_file
  215. if not os.path.exists(make):
  216. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  217. else:
  218. self.make = make
  219. self.toolchain_prefix = toolchain_prefix
  220. self.menu_key = CTRL_T
  221. self.exit_key = CTRL_RBRACKET
  222. self.translate_eol = {
  223. "CRLF": lambda c: c.replace(b"\n", b"\r\n"),
  224. "CR": lambda c: c.replace(b"\n", b"\r"),
  225. "LF": lambda c: c.replace(b"\r", b"\n"),
  226. }[eol]
  227. # internal state
  228. self._pressed_menu_key = False
  229. self._read_line = b""
  230. self._gdb_buffer = b""
  231. self._output_enabled = True
  232. def main_loop(self):
  233. self.console_reader.start()
  234. self.serial_reader.start()
  235. try:
  236. while self.console_reader.alive and self.serial_reader.alive:
  237. (event_tag, data) = self.event_queue.get()
  238. if event_tag == TAG_KEY:
  239. self.handle_key(data)
  240. elif event_tag == TAG_SERIAL:
  241. self.handle_serial_input(data)
  242. else:
  243. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  244. finally:
  245. try:
  246. self.console_reader.stop()
  247. self.serial_reader.stop()
  248. except:
  249. pass
  250. sys.stderr.write(ANSI_NORMAL + "\n")
  251. def handle_key(self, key):
  252. if self._pressed_menu_key:
  253. self.handle_menu_key(key)
  254. self._pressed_menu_key = False
  255. elif key == self.menu_key:
  256. self._pressed_menu_key = True
  257. elif key == self.exit_key:
  258. self.console_reader.stop()
  259. self.serial_reader.stop()
  260. else:
  261. try:
  262. key = self.translate_eol(key)
  263. self.serial.write(codecs.encode(key))
  264. except serial.SerialException:
  265. pass # this shouldn't happen, but sometimes port has closed in serial thread
  266. except UnicodeEncodeError:
  267. pass # this can happen if a non-ascii character was passed, ignoring
  268. def handle_serial_input(self, data):
  269. # this may need to be made more efficient, as it pushes out a byte
  270. # at a time to the console
  271. for b in data:
  272. if self._output_enabled:
  273. self.console.write_bytes(b)
  274. if b == b'\n': # end of line
  275. self.handle_serial_input_line(self._read_line.strip())
  276. self._read_line = b""
  277. else:
  278. self._read_line += b
  279. self.check_gdbstub_trigger(b)
  280. def handle_serial_input_line(self, line):
  281. for m in re.finditer(MATCH_PCADDR, line):
  282. self.lookup_pc_address(m.group())
  283. def handle_menu_key(self, c):
  284. if c == self.exit_key or c == self.menu_key: # send verbatim
  285. self.serial.write(codecs.encode(c))
  286. elif c in [ CTRL_H, 'h', 'H', '?' ]:
  287. red_print(self.get_help_text())
  288. elif c == CTRL_R: # Reset device via RTS
  289. self.serial.setRTS(True)
  290. time.sleep(0.2)
  291. self.serial.setRTS(False)
  292. self.output_enable(True)
  293. elif c == CTRL_F: # Recompile & upload
  294. self.run_make("flash")
  295. elif c == CTRL_A: # Recompile & upload app only
  296. self.run_make("app-flash")
  297. elif c == CTRL_Y: # Toggle output display
  298. self.output_toggle()
  299. elif c == CTRL_P:
  300. yellow_print("Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart")
  301. # to fast trigger pause without press menu key
  302. self.serial.setDTR(False) # IO0=HIGH
  303. self.serial.setRTS(True) # EN=LOW, chip in reset
  304. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  305. self.serial.setDTR(True) # IO0=LOW
  306. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  307. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  308. self.serial.setDTR(False) # IO0=HIGH, done
  309. else:
  310. red_print('--- unknown menu character {} --'.format(key_description(c)))
  311. def get_help_text(self):
  312. return """
  313. --- idf_monitor ({version}) - ESP-IDF monitor tool
  314. --- based on miniterm from pySerial
  315. ---
  316. --- {exit:8} Exit program
  317. --- {menu:8} Menu escape key, followed by:
  318. --- Menu keys:
  319. --- {menu:7} Send the menu character itself to remote
  320. --- {exit:7} Send the exit character itself to remote
  321. --- {reset:7} Reset target board via RTS line
  322. --- {makecmd:7} Build & flash project
  323. --- {appmake:7} Build & flash app only
  324. --- {output:7} Toggle output display
  325. --- {pause:7} Reset target into bootloader to pause app via RTS line
  326. """.format(version=__version__,
  327. exit=key_description(self.exit_key),
  328. menu=key_description(self.menu_key),
  329. reset=key_description(CTRL_R),
  330. makecmd=key_description(CTRL_F),
  331. appmake=key_description(CTRL_A),
  332. output=key_description(CTRL_Y),
  333. pause=key_description(CTRL_P) )
  334. def __enter__(self):
  335. """ Use 'with self' to temporarily disable monitoring behaviour """
  336. self.serial_reader.stop()
  337. self.console_reader.stop()
  338. def __exit__(self, *args, **kwargs):
  339. """ Use 'with self' to temporarily disable monitoring behaviour """
  340. self.console_reader.start()
  341. self.serial_reader.start()
  342. def prompt_next_action(self, reason):
  343. self.console.setup() # set up console to trap input characters
  344. try:
  345. red_print("""
  346. --- {}
  347. --- Press {} to exit monitor.
  348. --- Press {} to build & flash project.
  349. --- Press {} to build & flash app.
  350. --- Press any other key to resume monitor (resets target).""".format(reason,
  351. key_description(self.exit_key),
  352. key_description(CTRL_F),
  353. key_description(CTRL_A) ))
  354. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  355. while k == CTRL_T:
  356. k = self.console.getkey()
  357. finally:
  358. self.console.cleanup()
  359. if k == self.exit_key:
  360. self.event_queue.put((TAG_KEY, k))
  361. elif k in [ CTRL_F, CTRL_A ]:
  362. self.event_queue.put((TAG_KEY, self.menu_key))
  363. self.event_queue.put((TAG_KEY, k))
  364. def run_make(self, target):
  365. with self:
  366. if isinstance(self.make, list):
  367. popen_args = self.make + [ target ]
  368. else:
  369. popen_args = [ self.make, target ]
  370. yellow_print("Running %s..." % " ".join(popen_args))
  371. p = subprocess.Popen(popen_args)
  372. try:
  373. p.wait()
  374. except KeyboardInterrupt:
  375. p.wait()
  376. if p.returncode != 0:
  377. self.prompt_next_action("Build failed")
  378. else:
  379. self.output_enable(True)
  380. def lookup_pc_address(self, pc_addr):
  381. translation = subprocess.check_output(
  382. ["%saddr2line" % self.toolchain_prefix,
  383. "-pfiaC", "-e", self.elf_file, pc_addr],
  384. cwd=".")
  385. if not "?? ??:0" in translation:
  386. yellow_print(translation)
  387. def check_gdbstub_trigger(self, c):
  388. self._gdb_buffer = self._gdb_buffer[-6:] + c # keep the last 7 characters seen
  389. m = re.match(b"\\$(T..)#(..)", self._gdb_buffer) # look for a gdb "reason" for a break
  390. if m is not None:
  391. try:
  392. chsum = sum(ord(p) for p in m.group(1)) & 0xFF
  393. calc_chsum = int(m.group(2), 16)
  394. except ValueError:
  395. return # payload wasn't valid hex digits
  396. if chsum == calc_chsum:
  397. self.run_gdb()
  398. else:
  399. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  400. def run_gdb(self):
  401. with self: # disable console control
  402. sys.stderr.write(ANSI_NORMAL)
  403. try:
  404. process = subprocess.Popen(["%sgdb" % self.toolchain_prefix,
  405. "-ex", "set serial baud %d" % self.serial.baudrate,
  406. "-ex", "target remote %s" % self.serial.port,
  407. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  408. self.elf_file], cwd=".")
  409. process.wait()
  410. except KeyboardInterrupt:
  411. pass # happens on Windows, maybe other OSes
  412. finally:
  413. try:
  414. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  415. process.terminate()
  416. except:
  417. pass
  418. try:
  419. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  420. subprocess.call(["stty", "sane"])
  421. except:
  422. pass # don't care if there's no stty, we tried...
  423. self.prompt_next_action("gdb exited")
  424. def output_enable(self, enable):
  425. self._output_enabled = enable
  426. def output_toggle(self):
  427. self._output_enabled = not self._output_enabled
  428. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  429. def main():
  430. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  431. parser.add_argument(
  432. '--port', '-p',
  433. help='Serial port device',
  434. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  435. )
  436. parser.add_argument(
  437. '--baud', '-b',
  438. help='Serial port baud rate',
  439. type=int,
  440. default=os.environ.get('MONITOR_BAUD', 115200))
  441. parser.add_argument(
  442. '--make', '-m',
  443. help='Command to run make',
  444. type=str, default='make')
  445. parser.add_argument(
  446. '--toolchain-prefix',
  447. help="Triplet prefix to add before cross-toolchain names",
  448. default=DEFAULT_TOOLCHAIN_PREFIX)
  449. parser.add_argument(
  450. "--eol",
  451. choices=['CR', 'LF', 'CRLF'],
  452. type=lambda c: c.upper(),
  453. help="End of line to use when sending to the serial port",
  454. default='CR')
  455. parser.add_argument(
  456. 'elf_file', help='ELF file of application',
  457. type=argparse.FileType('rb'))
  458. args = parser.parse_args()
  459. if args.port.startswith("/dev/tty."):
  460. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  461. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  462. yellow_print("--- Using %s instead..." % args.port)
  463. serial_instance = serial.serial_for_url(args.port, args.baud,
  464. do_not_open=True)
  465. serial_instance.dtr = False
  466. serial_instance.rts = False
  467. args.elf_file.close() # don't need this as a file
  468. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  469. # parent make is only running 1 job (monitor), so we can re-spawn
  470. # all of the child makes we need (the -j argument remains part of
  471. # MAKEFLAGS)
  472. try:
  473. makeflags = os.environ["MAKEFLAGS"]
  474. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  475. os.environ["MAKEFLAGS"] = makeflags
  476. except KeyError:
  477. pass # not running a make jobserver
  478. monitor = Monitor(serial_instance, args.elf_file.name, args.make, args.toolchain_prefix, args.eol)
  479. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  480. p=serial_instance))
  481. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  482. key_description(monitor.exit_key),
  483. key_description(monitor.menu_key),
  484. key_description(monitor.menu_key),
  485. key_description(CTRL_H)))
  486. monitor.main_loop()
  487. if os.name == 'nt':
  488. # Windows console stuff
  489. STD_OUTPUT_HANDLE = -11
  490. STD_ERROR_HANDLE = -12
  491. # wincon.h values
  492. FOREGROUND_INTENSITY = 8
  493. FOREGROUND_GREY = 7
  494. # matches the ANSI color change sequences that IDF sends
  495. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  496. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  497. ANSI_TO_WINDOWS_COLOR = [ 0, 4, 2, 6, 1, 5, 3, 7 ]
  498. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  499. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  500. class ANSIColorConverter(object):
  501. """Class to wrap a file-like output stream, intercept ANSI color codes,
  502. and convert them into calls to Windows SetConsoleTextAttribute.
  503. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  504. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  505. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  506. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  507. """
  508. def __init__(self, output):
  509. self.output = output
  510. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  511. self.matched = b''
  512. def _output_write(self, data):
  513. try:
  514. self.output.write(data)
  515. except IOError:
  516. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  517. # an exception (however, the character is still written to the screen)
  518. # Ref https://github.com/espressif/esp-idf/issues/1136
  519. pass
  520. def write(self, data):
  521. for b in data:
  522. l = len(self.matched)
  523. if b == '\033': # ESC
  524. self.matched = b
  525. elif (l == 1 and b == '[') or (1 < l < 7):
  526. self.matched += b
  527. if self.matched == ANSI_NORMAL: # reset console
  528. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  529. self.matched = b''
  530. elif len(self.matched) == 7: # could be an ANSI sequence
  531. m = re.match(RE_ANSI_COLOR, self.matched)
  532. if m is not None:
  533. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  534. if m.group(1) == b'1':
  535. color |= FOREGROUND_INTENSITY
  536. SetConsoleTextAttribute(self.handle, color)
  537. else:
  538. self._output_write(self.matched) # not an ANSI color code, display verbatim
  539. self.matched = b''
  540. else:
  541. self._output_write(b)
  542. self.matched = b''
  543. def flush(self):
  544. self.output.flush()
  545. if __name__ == "__main__":
  546. main()