idf_monitor.py 23 KB

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