Override ArgumentParser methods that use sys.stdout/sys.stderr directly. This is needed because hijacking sys.std* is not thread-safe, yet output must be captured to properly support mypy.api.run.
| 398 | |
| 399 | |
| 400 | class CapturableArgumentParser(argparse.ArgumentParser): |
| 401 | """Override ArgumentParser methods that use sys.stdout/sys.stderr directly. |
| 402 | |
| 403 | This is needed because hijacking sys.std* is not thread-safe, |
| 404 | yet output must be captured to properly support mypy.api.run. |
| 405 | """ |
| 406 | |
| 407 | def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 408 | self.stdout = kwargs.pop("stdout", sys.stdout) |
| 409 | self.stderr = kwargs.pop("stderr", sys.stderr) |
| 410 | super().__init__(*args, **kwargs) |
| 411 | |
| 412 | # ===================== |
| 413 | # Help-printing methods |
| 414 | # ===================== |
| 415 | def print_usage(self, file: SupportsWrite[str] | None = None) -> None: |
| 416 | if file is None: |
| 417 | file = self.stdout |
| 418 | self._print_message(self.format_usage(), file) |
| 419 | |
| 420 | def print_help(self, file: SupportsWrite[str] | None = None) -> None: |
| 421 | if file is None: |
| 422 | file = self.stdout |
| 423 | self._print_message(self.format_help(), file) |
| 424 | |
| 425 | def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: |
| 426 | if message: |
| 427 | if file is None: |
| 428 | file = self.stderr |
| 429 | file.write(message) |
| 430 | |
| 431 | # =============== |
| 432 | # Exiting methods |
| 433 | # =============== |
| 434 | def exit(self, status: int = 0, message: str | None = None) -> NoReturn: |
| 435 | if message: |
| 436 | self._print_message(message, self.stderr) |
| 437 | sys.exit(status) |
| 438 | |
| 439 | def error(self, message: str) -> NoReturn: |
| 440 | """error(message: string) |
| 441 | |
| 442 | Prints a usage message incorporating the message to stderr and |
| 443 | exits. |
| 444 | |
| 445 | If you override this in a subclass, it should not return -- it |
| 446 | should either exit or raise an exception. |
| 447 | """ |
| 448 | self.print_usage(self.stderr) |
| 449 | args = {"prog": self.prog, "message": message} |
| 450 | self.exit(2, gettext("%(prog)s: error: %(message)s\n") % args) |
| 451 | |
| 452 | |
| 453 | class CapturableVersionAction(argparse.Action): |
no outgoing calls
no test coverage detected
searching dependent graphs…