Provides a Python API wrapper for application commands. :param cmd2_app: app being controlled by this PyBridge. :param add_to_history: If True, then add all commands run by this PyBridge to history. Defaults to True.
| 72 | |
| 73 | |
| 74 | class PyBridge: |
| 75 | """Provides a Python API wrapper for application commands. |
| 76 | |
| 77 | :param cmd2_app: app being controlled by this PyBridge. |
| 78 | :param add_to_history: If True, then add all commands run by this PyBridge to history. |
| 79 | Defaults to True. |
| 80 | """ |
| 81 | |
| 82 | def __init__(self, cmd2_app: "Cmd", *, add_to_history: bool = True) -> None: |
| 83 | """Initialize PyBridge instances.""" |
| 84 | self._cmd2_app = cmd2_app |
| 85 | self._add_to_history = add_to_history |
| 86 | self.cmd_echo = False |
| 87 | |
| 88 | # Tells if any of the commands run via __call__ returned True for stop |
| 89 | self.stop = False |
| 90 | |
| 91 | def __dir__(self) -> list[str]: |
| 92 | """Return a custom set of attribute names.""" |
| 93 | attributes: list[str] = [] |
| 94 | attributes.insert(0, "cmd_echo") |
| 95 | return attributes |
| 96 | |
| 97 | def __call__(self, command: str, *, echo: bool | None = None) -> CommandResult: |
| 98 | """Provide functionality to call application commands by calling PyBridge. |
| 99 | |
| 100 | ex: app('help') |
| 101 | :param command: command line being run |
| 102 | :param echo: If provided, this temporarily overrides the value of self.cmd_echo |
| 103 | while the command runs. If True, output will be echoed to _cmd2_app.stdout |
| 104 | and sys.stderr. (Defaults to None) |
| 105 | """ |
| 106 | if echo is None: |
| 107 | echo = self.cmd_echo |
| 108 | |
| 109 | # This will be used to capture _cmd2_app.stdout |
| 110 | copy_cmd_stdout = StdSim(cast(TextIO | StdSim, self._cmd2_app.stdout), echo=echo) |
| 111 | |
| 112 | # Pause the storing of stdout until onecmd_plus_hooks enables it |
| 113 | copy_cmd_stdout.pause_storage = True |
| 114 | |
| 115 | # This will be used to capture sys.stderr |
| 116 | copy_stderr = StdSim(sys.stderr, echo=echo) |
| 117 | |
| 118 | self._cmd2_app.last_result = None |
| 119 | |
| 120 | stop = False |
| 121 | try: |
| 122 | self._cmd2_app.stdout = cast(TextIO, copy_cmd_stdout) |
| 123 | |
| 124 | with redirect_stderr(cast(IO[str], copy_stderr)): |
| 125 | stop = self._cmd2_app.onecmd_plus_hooks( |
| 126 | command, |
| 127 | add_to_history=self._add_to_history, |
| 128 | py_bridge_call=True, |
| 129 | ) |
| 130 | finally: |
| 131 | with self._cmd2_app.sigint_protection: |
no outgoing calls
searching dependent graphs…