|
8 | 8 | """ |
9 | 9 |
|
10 | 10 | import argparse |
| 11 | +from collections import namedtuple |
| 12 | +import sys |
11 | 13 | from typing import List, Tuple |
| 14 | + |
| 15 | +# Python 3.4 require contextlib2 for temporarily redirecting stderr and stdout |
| 16 | +if sys.version_info < (3, 5): |
| 17 | + from contextlib2 import redirect_stdout, redirect_stderr |
| 18 | +else: |
| 19 | + from contextlib import redirect_stdout, redirect_stderr |
| 20 | + |
12 | 21 | from .argparse_completer import _RangeAction |
13 | 22 |
|
14 | 23 |
|
| 24 | +CommandResult = namedtuple('FunctionResult', 'stdout stderr data') |
| 25 | + |
| 26 | + |
| 27 | +class CopyStream(object): |
| 28 | + """ Toy class for replacing self.stdout in cmd2.Cmd instances for unit testing. """ |
| 29 | + def __init__(self, innerStream): |
| 30 | + self.buffer = '' |
| 31 | + self.innerStream = innerStream |
| 32 | + |
| 33 | + def write(self, s): |
| 34 | + self.buffer += s |
| 35 | + self.innerStream.write(s) |
| 36 | + |
| 37 | + def read(self): |
| 38 | + raise NotImplementedError |
| 39 | + |
| 40 | + def clear(self): |
| 41 | + self.buffer = '' |
| 42 | + self.innerStream.clear() |
| 43 | + |
| 44 | + |
15 | 45 | class ArgparseFunctor: |
16 | 46 | """ |
17 | 47 | Encapsulates translating python object traversal |
@@ -178,8 +208,13 @@ def traverse_parser(parser): |
178 | 208 |
|
179 | 209 | # print('Command: {}'.format(cmd_str[0])) |
180 | 210 |
|
181 | | - func(cmd_str[0]) |
182 | | - return self._cmd2_app._last_result |
| 211 | + copyStdOut = CopyStream(sys.stdout) |
| 212 | + copyStdErr = CopyStream(sys.stderr) |
| 213 | + with redirect_stdout(copyStdOut): |
| 214 | + with redirect_stderr(copyStdErr): |
| 215 | + func(cmd_str[0]) |
| 216 | + result = CommandResult(stdout=copyStdOut.buffer, stderr=copyStdErr.buffer, data=self._cmd2_app._last_result) |
| 217 | + return result |
183 | 218 |
|
184 | 219 |
|
185 | 220 | class PyscriptBridge(object): |
|
0 commit comments