Skip to content

Commit 41d3c66

Browse files
authored
Merge pull request #782 from python-cmd2/in_script
Added in_script() and in_pyscript() to cmd2.Cmd class
2 parents b72edb0 + 265e598 commit 41d3c66

File tree

3 files changed

+37
-8
lines changed

3 files changed

+37
-8
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
If these functions have an argument called `arg_tokens`, then AutoCompleter will automatically pass this
1111
dictionary to them.
1212
* Added CompletionError class that can be raised during argparse-based tab completion and printed to the user
13+
* Added the following convenience methods
14+
- `Cmd.in_script()` - return whether a text script is running
15+
- `Cmd.in_pyscript()` - return whether a pyscript is running
1316

1417
## 0.9.16 (August 7, 2019)
1518
* Bug Fixes

cmd2/cmd2.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -626,11 +626,6 @@ def visible_prompt(self) -> str:
626626
"""
627627
return ansi.strip_ansi(self.prompt)
628628

629-
@property
630-
def aliases(self) -> Dict[str, str]:
631-
"""Read-only property to access the aliases stored in the StatementParser."""
632-
return self.statement_parser.aliases
633-
634629
def poutput(self, msg: Any, *, end: str = '\n') -> None:
635630
"""Print message to self.stdout and appends a newline by default
636631
@@ -744,7 +739,7 @@ def ppaged(self, msg: str, end: str = '\n', chop: bool = False) -> None:
744739

745740
# Don't attempt to use a pager that can block if redirecting or running a script (either text or Python)
746741
# Also only attempt to use a pager if actually running in a real fully functional terminal
747-
if functional_terminal and not self._redirecting and not self._in_py and not self._script_dir:
742+
if functional_terminal and not self._redirecting and not self.in_pyscript() and not self.in_script():
748743
if ansi.allow_ansi.lower() == ansi.ANSI_NEVER.lower():
749744
msg_str = ansi.strip_ansi(msg_str)
750745

@@ -1606,6 +1601,19 @@ def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int,
16061601
tokens_to_parse = raw_tokens if preserve_quotes else tokens
16071602
return completer.complete_command(tokens_to_parse, text, line, begidx, endidx)
16081603

1604+
def in_script(self) -> bool:
1605+
"""Return whether a text script is running"""
1606+
return self._current_script_dir is not None
1607+
1608+
def in_pyscript(self) -> bool:
1609+
"""Return whether a pyscript is running"""
1610+
return self._in_py
1611+
1612+
@property
1613+
def aliases(self) -> Dict[str, str]:
1614+
"""Read-only property to access the aliases stored in the StatementParser"""
1615+
return self.statement_parser.aliases
1616+
16091617
def get_names(self):
16101618
"""Return an alphabetized list of names comprising the attributes of the cmd2 class instance."""
16111619
return dir(self)
@@ -3228,7 +3236,7 @@ def do_py(self, args: argparse.Namespace) -> Optional[bool]:
32283236
:return: True if running of commands should stop
32293237
"""
32303238
from .py_bridge import PyBridge
3231-
if self._in_py:
3239+
if self.in_pyscript():
32323240
err = "Recursively entering interactive Python consoles is not allowed."
32333241
self.perror(err)
32343242
return

tests/test_cmd2.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from unittest import mock
2121

2222
import cmd2
23-
from cmd2 import ansi, clipboard, constants, utils
23+
from cmd2 import ansi, clipboard, constants, plugin, utils
2424
from .conftest import run_cmd, normalize, verify_help_text, HELP_HISTORY
2525
from .conftest import SHORTCUTS_TXT, SHOW_TXT, SHOW_LONG, complete_tester
2626

@@ -461,6 +461,24 @@ def test_relative_run_script_requires_an_argument(base_app):
461461
out, err = run_cmd(base_app, '_relative_run_script')
462462
assert 'Error: the following arguments' in err[1]
463463

464+
def test_in_script(request):
465+
class HookApp(cmd2.Cmd):
466+
def __init__(self, *args, **kwargs):
467+
super().__init__(*args, **kwargs)
468+
self.register_cmdfinalization_hook(self.hook)
469+
470+
def hook(self: cmd2.Cmd, data: plugin.CommandFinalizationData) -> plugin.CommandFinalizationData:
471+
if self.in_script():
472+
self.poutput("WE ARE IN SCRIPT")
473+
return data
474+
475+
hook_app = HookApp()
476+
test_dir = os.path.dirname(request.module.__file__)
477+
filename = os.path.join(test_dir, 'script.txt')
478+
out, err = run_cmd(hook_app, 'run_script {}'.format(filename))
479+
480+
assert "WE ARE IN SCRIPT" in out[-1]
481+
464482
def test_output_redirection(base_app):
465483
fd, filename = tempfile.mkstemp(prefix='cmd2_test', suffix='.txt')
466484
os.close(fd)

0 commit comments

Comments
 (0)