Skip to content

Commit 6e56ad2

Browse files
committed
Pyscript now saves command output during the same period that redirection does
1 parent f5c904c commit 6e56ad2

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

cmd2/cmd2.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1718,6 +1718,11 @@ def onecmd_plus_hooks(self, line: str) -> bool:
17181718
try:
17191719
# Get sigint protection while we set up redirection
17201720
with self.sigint_protection:
1721+
if self._in_py:
1722+
# Start saving the command's output at this point to match what redirection captures
1723+
self.stdout.pause_storage = False
1724+
sys.stderr.pause_storage = False
1725+
17211726
redir_error, saved_state = self._redirect_output(statement)
17221727
self.cur_pipe_proc_reader = saved_state.pipe_proc_reader
17231728

@@ -1763,6 +1768,11 @@ def onecmd_plus_hooks(self, line: str) -> bool:
17631768
if not already_redirecting:
17641769
self.redirecting = False
17651770

1771+
if self._in_py:
1772+
# Stop saving command's output before command finalization hooks run
1773+
self.stdout.pause_storage = True
1774+
sys.stderr.pause_storage = True
1775+
17661776
except EmptyStatement:
17671777
# don't do anything, but do allow command finalization hooks to run
17681778
pass
@@ -3026,7 +3036,6 @@ def do_py(self, args: argparse.Namespace) -> bool:
30263036
if self._in_py:
30273037
err = "Recursively entering interactive Python consoles is not allowed."
30283038
self.perror(err, traceback_war=False)
3029-
self._last_result = CommandResult('', err)
30303039
return False
30313040

30323041
try:

cmd2/pyscript_bridge.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ def __call__(self, command: str, echo: Optional[bool] = None) -> CommandResult:
9292
# This will be used to capture sys.stderr
9393
copy_stderr = StdSim(sys.stderr, echo)
9494

95+
# Pause the storing of any output until onecmd_plus_hooks enables it
96+
copy_cmd_stdout.pause_storage = True
97+
copy_stderr.pause_storage = True
98+
9599
self._cmd2_app._last_result = None
96100

97101
try:

tests/test_cmd2.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -268,9 +268,8 @@ def test_recursive_pyscript_not_allowed(base_app, request):
268268
python_script = os.path.join(test_dir, 'scripts', 'recursive.py')
269269
expected = 'Recursively entering interactive Python consoles is not allowed.'
270270

271-
run_cmd(base_app, "pyscript {}".format(python_script))
272-
err = base_app._last_result.stderr
273-
assert err == expected
271+
out, err = run_cmd(base_app, "pyscript {}".format(python_script))
272+
assert err[0] == expected
274273

275274
def test_pyscript_with_nonexist_file(base_app):
276275
python_script = 'does_not_exist.py'

0 commit comments

Comments
 (0)