cmd2 2.4.3__py3-none-any.whl → 2.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cmd2/cmd2.py CHANGED
@@ -21,6 +21,7 @@ is used in place of `print`.
21
21
 
22
22
  Git repository on GitHub at https://github.com/python-cmd2/cmd2
23
23
  """
24
+
24
25
  # This module has many imports, quite a few of which are only
25
26
  # infrequently utilized. To reduce the initial overhead of
26
27
  # import this module, many of these imports are lazy-loaded
@@ -30,6 +31,7 @@ Git repository on GitHub at https://github.com/python-cmd2/cmd2
30
31
  # setting is True
31
32
  import argparse
32
33
  import cmd
34
+ import copy
33
35
  import functools
34
36
  import glob
35
37
  import inspect
@@ -37,6 +39,7 @@ import os
37
39
  import pydoc
38
40
  import re
39
41
  import sys
42
+ import tempfile
40
43
  import threading
41
44
  from code import (
42
45
  InteractiveConsole,
@@ -53,6 +56,8 @@ from types import (
53
56
  ModuleType,
54
57
  )
55
58
  from typing import (
59
+ IO,
60
+ TYPE_CHECKING,
56
61
  Any,
57
62
  Callable,
58
63
  Dict,
@@ -83,7 +88,6 @@ from .argparse_custom import (
83
88
  CompletionItem,
84
89
  )
85
90
  from .clipboard import (
86
- can_clip,
87
91
  get_paste_buffer,
88
92
  write_to_paste_buffer,
89
93
  )
@@ -98,6 +102,7 @@ from .constants import (
98
102
  HELP_FUNC_PREFIX,
99
103
  )
100
104
  from .decorators import (
105
+ CommandParent,
101
106
  as_subcommand_to,
102
107
  with_argparser,
103
108
  )
@@ -114,6 +119,7 @@ from .exceptions import (
114
119
  from .history import (
115
120
  History,
116
121
  HistoryItem,
122
+ single_line_format,
117
123
  )
118
124
  from .parsing import (
119
125
  Macro,
@@ -125,8 +131,10 @@ from .parsing import (
125
131
  from .rl_utils import (
126
132
  RlType,
127
133
  rl_escape_prompt,
134
+ rl_get_display_prompt,
128
135
  rl_get_point,
129
136
  rl_get_prompt,
137
+ rl_in_search_mode,
130
138
  rl_set_prompt,
131
139
  rl_type,
132
140
  rl_warning,
@@ -140,6 +148,7 @@ from .utils import (
140
148
  Settable,
141
149
  get_defining_class,
142
150
  strip_doc_annotations,
151
+ suggest_similar,
143
152
  )
144
153
 
145
154
  # Set up readline
@@ -155,13 +164,10 @@ else:
155
164
  orig_rl_delims = readline.get_completer_delims()
156
165
 
157
166
  if rl_type == RlType.PYREADLINE:
158
-
159
167
  # Save the original pyreadline3 display completion function since we need to override it and restore it
160
- # noinspection PyProtectedMember,PyUnresolvedReferences
161
168
  orig_pyreadline_display = readline.rl.mode._display_completions
162
169
 
163
170
  elif rl_type == RlType.GNU:
164
-
165
171
  # Get the readline lib so we can make changes to it
166
172
  import ctypes
167
173
 
@@ -197,6 +203,14 @@ class _SavedCmd2Env:
197
203
  DisabledCommand = namedtuple('DisabledCommand', ['command_function', 'help_function', 'completer_function'])
198
204
 
199
205
 
206
+ if TYPE_CHECKING: # pragma: no cover
207
+ StaticArgParseBuilder = staticmethod[[], argparse.ArgumentParser]
208
+ ClassArgParseBuilder = classmethod[Union['Cmd', CommandSet], [], argparse.ArgumentParser]
209
+ else:
210
+ StaticArgParseBuilder = staticmethod
211
+ ClassArgParseBuilder = classmethod
212
+
213
+
200
214
  class Cmd(cmd.Cmd):
201
215
  """An easy but powerful framework for writing line-oriented command interpreters.
202
216
 
@@ -236,6 +250,8 @@ class Cmd(cmd.Cmd):
236
250
  shortcuts: Optional[Dict[str, str]] = None,
237
251
  command_sets: Optional[Iterable[CommandSet]] = None,
238
252
  auto_load_commands: bool = True,
253
+ allow_clipboard: bool = True,
254
+ suggest_similar_command: bool = False,
239
255
  ) -> None:
240
256
  """An easy but powerful framework for writing line-oriented command
241
257
  interpreters. Extends Python's cmd package.
@@ -283,6 +299,10 @@ class Cmd(cmd.Cmd):
283
299
  that are currently loaded by Python and automatically
284
300
  instantiate and register all commands. If False, CommandSets
285
301
  must be manually installed with `register_command_set`.
302
+ :param allow_clipboard: If False, cmd2 will disable clipboard interactions
303
+ :param suggest_similar_command: If ``True``, ``cmd2`` will attempt to suggest the most
304
+ similar command when the user types a command that does
305
+ not exist. Default: ``False``.
286
306
  """
287
307
  # Check if py or ipy need to be disabled in this instance
288
308
  if not include_py:
@@ -308,6 +328,7 @@ class Cmd(cmd.Cmd):
308
328
  self.editor = Cmd.DEFAULT_EDITOR
309
329
  self.feedback_to_output = False # Do not include nonessentials in >, | output by default (things like timing)
310
330
  self.quiet = False # Do not suppress nonessential output
331
+ self.scripts_add_to_history = True # Scripts and pyscripts add commands to history
311
332
  self.timing = False # Prints elapsed time for each command
312
333
 
313
334
  # The maximum number of CompletionItems to display during tab completion. If the number of completion
@@ -335,6 +356,7 @@ class Cmd(cmd.Cmd):
335
356
  self.hidden_commands = ['eof', '_relative_run_script']
336
357
 
337
358
  # Initialize history
359
+ self.persistent_history_file = ''
338
360
  self._persistent_history_length = persistent_history_length
339
361
  self._initialize_history(persistent_history_file)
340
362
 
@@ -389,7 +411,7 @@ class Cmd(cmd.Cmd):
389
411
  self.help_error = "No help on {}"
390
412
 
391
413
  # The error that prints when a non-existent command is run
392
- self.default_error = "{} is not a recognized command, alias, or macro"
414
+ self.default_error = "{} is not a recognized command, alias, or macro."
393
415
 
394
416
  # If non-empty, this string will be displayed if a broken pipe error occurs
395
417
  self.broken_pipe_warning = ''
@@ -436,8 +458,8 @@ class Cmd(cmd.Cmd):
436
458
  self.pager = 'less -RXF'
437
459
  self.pager_chop = 'less -SRXF'
438
460
 
439
- # This boolean flag determines whether or not the cmd2 application can interact with the clipboard
440
- self._can_clip = can_clip
461
+ # This boolean flag stores whether cmd2 will allow clipboard related features
462
+ self.allow_clipboard = allow_clipboard
441
463
 
442
464
  # This determines the value returned by cmdloop() when exiting the application
443
465
  self.exit_code = 0
@@ -507,6 +529,16 @@ class Cmd(cmd.Cmd):
507
529
  # This does not affect self.formatted_completions.
508
530
  self.matches_sorted = False
509
531
 
532
+ # Command parsers for this Cmd instance.
533
+ self._command_parsers: Dict[str, argparse.ArgumentParser] = {}
534
+
535
+ # Locates the command parser template or factory and creates an instance-specific parser
536
+ for command in self.get_all_commands():
537
+ self._register_command_parser(command, self.cmd_func(command)) # type: ignore[arg-type]
538
+
539
+ # Add functions decorated to be subcommands
540
+ self._register_subcommands(self)
541
+
510
542
  ############################################################################################################
511
543
  # The following code block loads CommandSets, verifies command names, and registers subcommands.
512
544
  # This block should appear after all attributes have been created since the registration code
@@ -526,8 +558,11 @@ class Cmd(cmd.Cmd):
526
558
  if not valid:
527
559
  raise ValueError(f"Invalid command name '{cur_cmd}': {errmsg}")
528
560
 
529
- # Add functions decorated to be subcommands
530
- self._register_subcommands(self)
561
+ self.suggest_similar_command = suggest_similar_command
562
+ self.default_suggestion_message = "Did you mean {}?"
563
+
564
+ # the current command being executed
565
+ self.current_command: Optional[Statement] = None
531
566
 
532
567
  def find_commandsets(self, commandset_type: Type[CommandSet], *, subclass_match: bool = False) -> List[CommandSet]:
533
568
  """
@@ -541,7 +576,7 @@ class Cmd(cmd.Cmd):
541
576
  return [
542
577
  cmdset
543
578
  for cmdset in self._installed_command_sets
544
- if type(cmdset) == commandset_type or (subclass_match and isinstance(cmdset, commandset_type))
579
+ if type(cmdset) == commandset_type or (subclass_match and isinstance(cmdset, commandset_type)) # noqa: E721
545
580
  ]
546
581
 
547
582
  def find_commandset_for_command(self, command_name: str) -> Optional[CommandSet]:
@@ -601,11 +636,14 @@ class Cmd(cmd.Cmd):
601
636
  raise CommandSetRegistrationError(f'Duplicate settable {key} is already registered')
602
637
 
603
638
  cmdset.on_register(self)
604
- methods = inspect.getmembers(
605
- cmdset,
606
- predicate=lambda meth: isinstance(meth, Callable) # type: ignore[arg-type]
607
- and hasattr(meth, '__name__')
608
- and meth.__name__.startswith(COMMAND_FUNC_PREFIX),
639
+ methods = cast(
640
+ List[Tuple[str, Callable[..., Any]]],
641
+ inspect.getmembers(
642
+ cmdset,
643
+ predicate=lambda meth: isinstance(meth, Callable) # type: ignore[arg-type]
644
+ and hasattr(meth, '__name__')
645
+ and meth.__name__.startswith(COMMAND_FUNC_PREFIX),
646
+ ),
609
647
  )
610
648
 
611
649
  default_category = getattr(cmdset, CLASS_ATTR_DEFAULT_HELP_CATEGORY, None)
@@ -650,6 +688,50 @@ class Cmd(cmd.Cmd):
650
688
  cmdset.on_unregistered()
651
689
  raise
652
690
 
691
+ def _build_parser(
692
+ self,
693
+ parent: CommandParent,
694
+ parser_builder: Optional[
695
+ Union[
696
+ argparse.ArgumentParser,
697
+ Callable[[], argparse.ArgumentParser],
698
+ StaticArgParseBuilder,
699
+ ClassArgParseBuilder,
700
+ ]
701
+ ],
702
+ ) -> Optional[argparse.ArgumentParser]:
703
+ parser: Optional[argparse.ArgumentParser] = None
704
+ if isinstance(parser_builder, staticmethod):
705
+ parser = parser_builder.__func__()
706
+ elif isinstance(parser_builder, classmethod):
707
+ parser = parser_builder.__func__(parent if not None else self) # type: ignore[arg-type]
708
+ elif callable(parser_builder):
709
+ parser = parser_builder()
710
+ elif isinstance(parser_builder, argparse.ArgumentParser):
711
+ parser = copy.deepcopy(parser_builder)
712
+ return parser
713
+
714
+ def _register_command_parser(self, command: str, command_method: Callable[..., Any]) -> None:
715
+ if command not in self._command_parsers:
716
+ parser_builder = getattr(command_method, constants.CMD_ATTR_ARGPARSER, None)
717
+ parent = self.find_commandset_for_command(command) or self
718
+ parser = self._build_parser(parent, parser_builder)
719
+ if parser is None:
720
+ return
721
+
722
+ # argparser defaults the program name to sys.argv[0], but we want it to be the name of our command
723
+ from .decorators import (
724
+ _set_parser_prog,
725
+ )
726
+
727
+ _set_parser_prog(parser, command)
728
+
729
+ # If the description has not been set, then use the method docstring if one exists
730
+ if parser.description is None and hasattr(command_method, '__wrapped__') and command_method.__wrapped__.__doc__:
731
+ parser.description = strip_doc_annotations(command_method.__wrapped__.__doc__)
732
+
733
+ self._command_parsers[command] = parser
734
+
653
735
  def _install_command_function(self, command: str, command_wrapper: Callable[..., Any], context: str = '') -> None:
654
736
  cmd_func_name = COMMAND_FUNC_PREFIX + command
655
737
 
@@ -672,6 +754,8 @@ class Cmd(cmd.Cmd):
672
754
  self.pwarning(f"Deleting macro '{command}' because it shares its name with a new command")
673
755
  del self.macros[command]
674
756
 
757
+ self._register_command_parser(command, command_wrapper)
758
+
675
759
  setattr(self, cmd_func_name, command_wrapper)
676
760
 
677
761
  def _install_completer_function(self, cmd_name: str, cmd_completer: CompleterFunc) -> None:
@@ -699,7 +783,7 @@ class Cmd(cmd.Cmd):
699
783
  cmdset.on_unregister()
700
784
  self._unregister_subcommands(cmdset)
701
785
 
702
- methods = inspect.getmembers(
786
+ methods: List[Tuple[str, Callable[[Any], Any]]] = inspect.getmembers(
703
787
  cmdset,
704
788
  predicate=lambda meth: isinstance(meth, Callable) # type: ignore[arg-type]
705
789
  and hasattr(meth, '__name__')
@@ -718,6 +802,8 @@ class Cmd(cmd.Cmd):
718
802
  del self._cmd_to_command_sets[cmd_name]
719
803
 
720
804
  delattr(self, COMMAND_FUNC_PREFIX + cmd_name)
805
+ if cmd_name in self._command_parsers:
806
+ del self._command_parsers[cmd_name]
721
807
 
722
808
  if hasattr(self, COMPLETER_FUNC_PREFIX + cmd_name):
723
809
  delattr(self, COMPLETER_FUNC_PREFIX + cmd_name)
@@ -728,7 +814,7 @@ class Cmd(cmd.Cmd):
728
814
  self._installed_command_sets.remove(cmdset)
729
815
 
730
816
  def _check_uninstallable(self, cmdset: CommandSet) -> None:
731
- methods = inspect.getmembers(
817
+ methods: List[Tuple[str, Callable[[Any], Any]]] = inspect.getmembers(
732
818
  cmdset,
733
819
  predicate=lambda meth: isinstance(meth, Callable) # type: ignore[arg-type]
734
820
  and hasattr(meth, '__name__')
@@ -737,14 +823,7 @@ class Cmd(cmd.Cmd):
737
823
 
738
824
  for method in methods:
739
825
  command_name = method[0][len(COMMAND_FUNC_PREFIX) :]
740
-
741
- # Search for the base command function and verify it has an argparser defined
742
- if command_name in self.disabled_commands:
743
- command_func = self.disabled_commands[command_name].command_function
744
- else:
745
- command_func = self.cmd_func(command_name)
746
-
747
- command_parser = cast(argparse.ArgumentParser, getattr(command_func, constants.CMD_ATTR_ARGPARSER, None))
826
+ command_parser = self._command_parsers.get(command_name, None)
748
827
 
749
828
  def check_parser_uninstallable(parser: argparse.ArgumentParser) -> None:
750
829
  for action in parser._actions:
@@ -783,7 +862,7 @@ class Cmd(cmd.Cmd):
783
862
  for method_name, method in methods:
784
863
  subcommand_name: str = getattr(method, constants.SUBCMD_ATTR_NAME)
785
864
  full_command_name: str = getattr(method, constants.SUBCMD_ATTR_COMMAND)
786
- subcmd_parser = getattr(method, constants.CMD_ATTR_ARGPARSER)
865
+ subcmd_parser_builder = getattr(method, constants.CMD_ATTR_ARGPARSER)
787
866
 
788
867
  subcommand_valid, errmsg = self.statement_parser.is_valid_command(subcommand_name, is_subcommand=True)
789
868
  if not subcommand_valid:
@@ -803,7 +882,7 @@ class Cmd(cmd.Cmd):
803
882
  raise CommandSetRegistrationError(
804
883
  f"Could not find command '{command_name}' needed by subcommand: {str(method)}"
805
884
  )
806
- command_parser = getattr(command_func, constants.CMD_ATTR_ARGPARSER, None)
885
+ command_parser = self._command_parsers.get(command_name, None)
807
886
  if command_parser is None:
808
887
  raise CommandSetRegistrationError(
809
888
  f"Could not find argparser for command '{command_name}' needed by subcommand: {str(method)}"
@@ -823,16 +902,17 @@ class Cmd(cmd.Cmd):
823
902
 
824
903
  target_parser = find_subcommand(command_parser, subcommand_names)
825
904
 
905
+ subcmd_parser = cast(argparse.ArgumentParser, self._build_parser(cmdset, subcmd_parser_builder))
906
+ from .decorators import (
907
+ _set_parser_prog,
908
+ )
909
+
910
+ _set_parser_prog(subcmd_parser, f'{command_name} {subcommand_name}')
911
+ if subcmd_parser.description is None and method.__doc__:
912
+ subcmd_parser.description = strip_doc_annotations(method.__doc__)
913
+
826
914
  for action in target_parser._actions:
827
915
  if isinstance(action, argparse._SubParsersAction):
828
- # Temporary workaround for avoiding subcommand help text repeatedly getting added to
829
- # action._choices_actions. Until we have instance-specific parser objects, we will remove
830
- # any existing subcommand which has the same name before replacing it. This problem is
831
- # exercised when more than one cmd2.Cmd-based object is created and the same subcommands
832
- # get added each time. Argparse overwrites the previous subcommand but keeps growing the help
833
- # text which is shown by running something like 'alias -h'.
834
- action.remove_parser(subcommand_name) # type: ignore[arg-type,attr-defined]
835
-
836
916
  # Get the kwargs for add_parser()
837
917
  add_parser_kwargs = getattr(method, constants.SUBCMD_ATTR_ADD_PARSER_KWARGS, {})
838
918
 
@@ -904,7 +984,7 @@ class Cmd(cmd.Cmd):
904
984
  raise CommandSetRegistrationError(
905
985
  f"Could not find command '{command_name}' needed by subcommand: {str(method)}"
906
986
  )
907
- command_parser = getattr(command_func, constants.CMD_ATTR_ARGPARSER, None)
987
+ command_parser = self._command_parsers.get(command_name, None)
908
988
  if command_parser is None: # pragma: no cover
909
989
  # This really shouldn't be possible since _register_subcommands would prevent this from happening
910
990
  # but keeping in case it does for some strange reason
@@ -1012,12 +1092,7 @@ class Cmd(cmd.Cmd):
1012
1092
  )
1013
1093
 
1014
1094
  self.add_settable(
1015
- Settable(
1016
- 'always_show_hint',
1017
- bool,
1018
- 'Display tab completion hint even when completion suggestions print',
1019
- self,
1020
- )
1095
+ Settable('always_show_hint', bool, 'Display tab completion hint even when completion suggestions print', self)
1021
1096
  )
1022
1097
  self.add_settable(Settable('debug', bool, "Show full traceback on exception", self))
1023
1098
  self.add_settable(Settable('echo', bool, "Echo command issued into output", self))
@@ -1027,6 +1102,7 @@ class Cmd(cmd.Cmd):
1027
1102
  Settable('max_completion_items', int, "Maximum number of CompletionItems to display during tab completion", self)
1028
1103
  )
1029
1104
  self.add_settable(Settable('quiet', bool, "Don't print nonessential feedback", self))
1105
+ self.add_settable(Settable('scripts_add_to_history', bool, 'Scripts and pyscripts add commands to history', self))
1030
1106
  self.add_settable(Settable('timing', bool, "Report execution times", self))
1031
1107
 
1032
1108
  # ----- Methods related to presenting output to the user -----
@@ -1056,7 +1132,40 @@ class Cmd(cmd.Cmd):
1056
1132
  """
1057
1133
  return ansi.strip_style(self.prompt)
1058
1134
 
1059
- def poutput(self, msg: Any = '', *, end: str = '\n') -> None:
1135
+ def print_to(
1136
+ self,
1137
+ dest: Union[TextIO, IO[str]],
1138
+ msg: Any,
1139
+ *,
1140
+ end: str = '\n',
1141
+ style: Optional[Callable[[str], str]] = None,
1142
+ paged: bool = False,
1143
+ chop: bool = False,
1144
+ ) -> None:
1145
+ final_msg = style(msg) if style is not None else msg
1146
+ if paged:
1147
+ self.ppaged(final_msg, end=end, chop=chop, dest=dest)
1148
+ else:
1149
+ try:
1150
+ ansi.style_aware_write(dest, f'{final_msg}{end}')
1151
+ except BrokenPipeError:
1152
+ # This occurs if a command's output is being piped to another
1153
+ # process and that process closes before the command is
1154
+ # finished. If you would like your application to print a
1155
+ # warning message, then set the broken_pipe_warning attribute
1156
+ # to the message you want printed.
1157
+ if self.broken_pipe_warning:
1158
+ sys.stderr.write(self.broken_pipe_warning)
1159
+
1160
+ def poutput(
1161
+ self,
1162
+ msg: Any = '',
1163
+ *,
1164
+ end: str = '\n',
1165
+ apply_style: bool = True,
1166
+ paged: bool = False,
1167
+ chop: bool = False,
1168
+ ) -> None:
1060
1169
  """Print message to self.stdout and appends a newline by default
1061
1170
 
1062
1171
  Also handles BrokenPipeError exceptions for when a command's output has
@@ -1065,44 +1174,83 @@ class Cmd(cmd.Cmd):
1065
1174
 
1066
1175
  :param msg: object to print
1067
1176
  :param end: string appended after the end of the message, default a newline
1177
+ :param apply_style: If True, then ansi.style_output will be applied to the message text. Set to False in cases
1178
+ where the message text already has the desired style. Defaults to True.
1179
+ :param paged: If True, pass the output through the configured pager.
1180
+ :param chop: If paged is True, True to truncate long lines or False to wrap long lines.
1068
1181
  """
1069
- try:
1070
- ansi.style_aware_write(self.stdout, f"{msg}{end}")
1071
- except BrokenPipeError:
1072
- # This occurs if a command's output is being piped to another
1073
- # process and that process closes before the command is
1074
- # finished. If you would like your application to print a
1075
- # warning message, then set the broken_pipe_warning attribute
1076
- # to the message you want printed.
1077
- if self.broken_pipe_warning:
1078
- sys.stderr.write(self.broken_pipe_warning)
1182
+ self.print_to(self.stdout, msg, end=end, style=ansi.style_output if apply_style else None, paged=paged, chop=chop)
1079
1183
 
1080
- # noinspection PyMethodMayBeStatic
1081
- def perror(self, msg: Any = '', *, end: str = '\n', apply_style: bool = True) -> None:
1184
+ def perror(
1185
+ self,
1186
+ msg: Any = '',
1187
+ *,
1188
+ end: str = '\n',
1189
+ apply_style: bool = True,
1190
+ paged: bool = False,
1191
+ chop: bool = False,
1192
+ ) -> None:
1082
1193
  """Print message to sys.stderr
1083
1194
 
1084
1195
  :param msg: object to print
1085
1196
  :param end: string appended after the end of the message, default a newline
1086
1197
  :param apply_style: If True, then ansi.style_error will be applied to the message text. Set to False in cases
1087
1198
  where the message text already has the desired style. Defaults to True.
1199
+ :param paged: If True, pass the output through the configured pager.
1200
+ :param chop: If paged is True, True to truncate long lines or False to wrap long lines.
1088
1201
  """
1089
- if apply_style:
1090
- final_msg = ansi.style_error(msg)
1091
- else:
1092
- final_msg = str(msg)
1093
- ansi.style_aware_write(sys.stderr, final_msg + end)
1202
+ self.print_to(sys.stderr, msg, end=end, style=ansi.style_error if apply_style else None, paged=paged, chop=chop)
1203
+
1204
+ def psuccess(
1205
+ self,
1206
+ msg: Any = '',
1207
+ *,
1208
+ end: str = '\n',
1209
+ paged: bool = False,
1210
+ chop: bool = False,
1211
+ ) -> None:
1212
+ """Writes to stdout applying ansi.style_success by default
1213
+
1214
+ :param msg: object to print
1215
+ :param end: string appended after the end of the message, default a newline
1216
+ :param paged: If True, pass the output through the configured pager.
1217
+ :param chop: If paged is True, True to truncate long lines or False to wrap long lines.
1218
+ """
1219
+ self.print_to(self.stdout, msg, end=end, style=ansi.style_success, paged=paged, chop=chop)
1094
1220
 
1095
- def pwarning(self, msg: Any = '', *, end: str = '\n', apply_style: bool = True) -> None:
1221
+ def pwarning(
1222
+ self,
1223
+ msg: Any = '',
1224
+ *,
1225
+ end: str = '\n',
1226
+ paged: bool = False,
1227
+ chop: bool = False,
1228
+ ) -> None:
1096
1229
  """Wraps perror, but applies ansi.style_warning by default
1097
1230
 
1098
1231
  :param msg: object to print
1099
1232
  :param end: string appended after the end of the message, default a newline
1100
- :param apply_style: If True, then ansi.style_warning will be applied to the message text. Set to False in cases
1101
- where the message text already has the desired style. Defaults to True.
1233
+ :param paged: If True, pass the output through the configured pager.
1234
+ :param chop: If paged is True, True to truncate long lines or False to wrap long lines.
1102
1235
  """
1103
- if apply_style:
1104
- msg = ansi.style_warning(msg)
1105
- self.perror(msg, end=end, apply_style=False)
1236
+ self.print_to(sys.stderr, msg, end=end, style=ansi.style_warning, paged=paged, chop=chop)
1237
+
1238
+ def pfailure(
1239
+ self,
1240
+ msg: Any = '',
1241
+ *,
1242
+ end: str = '\n',
1243
+ paged: bool = False,
1244
+ chop: bool = False,
1245
+ ) -> None:
1246
+ """Writes to stderr applying ansi.style_error by default
1247
+
1248
+ :param msg: object to print
1249
+ :param end: string appended after the end of the message, default a newline
1250
+ :param paged: If True, pass the output through the configured pager.
1251
+ :param chop: If paged is True, True to truncate long lines or False to wrap long lines.
1252
+ """
1253
+ self.print_to(sys.stderr, msg, end=end, style=ansi.style_error, paged=paged, chop=chop)
1106
1254
 
1107
1255
  def pexcept(self, msg: Any, *, end: str = '\n', apply_style: bool = True) -> None:
1108
1256
  """Print Exception message to sys.stderr. If debug is true, print exception traceback if one exists.
@@ -1131,23 +1279,39 @@ class Cmd(cmd.Cmd):
1131
1279
 
1132
1280
  self.perror(final_msg, end=end, apply_style=False)
1133
1281
 
1134
- def pfeedback(self, msg: Any, *, end: str = '\n') -> None:
1282
+ def pfeedback(
1283
+ self,
1284
+ msg: Any,
1285
+ *,
1286
+ end: str = '\n',
1287
+ apply_style: bool = True,
1288
+ paged: bool = False,
1289
+ chop: bool = False,
1290
+ ) -> None:
1135
1291
  """For printing nonessential feedback. Can be silenced with `quiet`.
1136
1292
  Inclusion in redirected output is controlled by `feedback_to_output`.
1137
1293
 
1138
1294
  :param msg: object to print
1139
1295
  :param end: string appended after the end of the message, default a newline
1296
+ :param apply_style: If True, then ansi.style_output will be applied to the message text. Set to False in cases
1297
+ where the message text already has the desired style. Defaults to True.
1298
+ :param paged: If True, pass the output through the configured pager.
1299
+ :param chop: If paged is True, True to truncate long lines or False to wrap long lines.
1140
1300
  """
1141
1301
  if not self.quiet:
1142
- if self.feedback_to_output:
1143
- self.poutput(msg, end=end)
1144
- else:
1145
- self.perror(msg, end=end, apply_style=False)
1302
+ self.print_to(
1303
+ self.stdout if self.feedback_to_output else sys.stderr,
1304
+ msg,
1305
+ end=end,
1306
+ style=ansi.style_output if apply_style else None,
1307
+ paged=paged,
1308
+ chop=chop,
1309
+ )
1146
1310
 
1147
- def ppaged(self, msg: Any, *, end: str = '\n', chop: bool = False) -> None:
1311
+ def ppaged(self, msg: Any, *, end: str = '\n', chop: bool = False, dest: Optional[Union[TextIO, IO[str]]] = None) -> None:
1148
1312
  """Print output using a pager if it would go off screen and stdout isn't currently being redirected.
1149
1313
 
1150
- Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when
1314
+ Never uses a pager inside a script (Python or text) or when output is being redirected or piped or when
1151
1315
  stdout or stdin are not a fully functional terminal.
1152
1316
 
1153
1317
  :param msg: object to print
@@ -1157,11 +1321,13 @@ class Cmd(cmd.Cmd):
1157
1321
  - chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
1158
1322
  False -> causes lines longer than the screen width to wrap to the next line
1159
1323
  - wrapping is ideal when you want to keep users from having to use horizontal scrolling
1324
+ :param dest: Optionally specify the destination stream to write to. If unspecified, defaults to self.stdout
1160
1325
 
1161
1326
  WARNING: On Windows, the text always wraps regardless of what the chop argument is set to
1162
1327
  """
1163
1328
  # msg can be any type, so convert to string before checking if it's blank
1164
1329
  msg_str = str(msg)
1330
+ dest = self.stdout if dest is None else dest
1165
1331
 
1166
1332
  # Consider None to be no data to print
1167
1333
  if msg is None or msg_str == '':
@@ -1195,7 +1361,7 @@ class Cmd(cmd.Cmd):
1195
1361
  pipe_proc = subprocess.Popen(pager, shell=True, stdin=subprocess.PIPE)
1196
1362
  pipe_proc.communicate(msg_str.encode('utf-8', 'replace'))
1197
1363
  else:
1198
- self.poutput(msg_str, end=end)
1364
+ ansi.style_aware_write(dest, f'{msg_str}{end}')
1199
1365
  except BrokenPipeError:
1200
1366
  # This occurs if a command's output is being piped to another process and that process closes before the
1201
1367
  # command is finished. If you would like your application to print a warning message, then set the
@@ -1222,7 +1388,6 @@ class Cmd(cmd.Cmd):
1222
1388
  if rl_type == RlType.GNU:
1223
1389
  readline.set_completion_display_matches_hook(self._display_matches_gnu_readline)
1224
1390
  elif rl_type == RlType.PYREADLINE:
1225
- # noinspection PyUnresolvedReferences
1226
1391
  readline.rl.mode._display_completions = self._display_matches_pyreadline
1227
1392
 
1228
1393
  def tokens_for_completion(self, line: str, begidx: int, endidx: int) -> Tuple[List[str], List[str]]:
@@ -1289,7 +1454,6 @@ class Cmd(cmd.Cmd):
1289
1454
 
1290
1455
  return tokens, raw_tokens
1291
1456
 
1292
- # noinspection PyMethodMayBeStatic, PyUnusedLocal
1293
1457
  def basic_complete(
1294
1458
  self,
1295
1459
  text: str,
@@ -1480,7 +1644,6 @@ class Cmd(cmd.Cmd):
1480
1644
 
1481
1645
  return matches
1482
1646
 
1483
- # noinspection PyUnusedLocal
1484
1647
  def path_complete(
1485
1648
  self, text: str, line: str, begidx: int, endidx: int, *, path_filter: Optional[Callable[[str], bool]] = None
1486
1649
  ) -> List[str]:
@@ -1498,7 +1661,6 @@ class Cmd(cmd.Cmd):
1498
1661
 
1499
1662
  # Used to complete ~ and ~user strings
1500
1663
  def complete_users() -> List[str]:
1501
-
1502
1664
  users = []
1503
1665
 
1504
1666
  # Windows lacks the pwd module so we can't get a list of users.
@@ -1516,10 +1678,8 @@ class Cmd(cmd.Cmd):
1516
1678
 
1517
1679
  # Iterate through a list of users from the password database
1518
1680
  for cur_pw in pwd.getpwall():
1519
-
1520
1681
  # Check if the user has an existing home dir
1521
1682
  if os.path.isdir(cur_pw.pw_dir):
1522
-
1523
1683
  # Add a ~ to the user to match against text
1524
1684
  cur_user = '~' + cur_pw.pw_name
1525
1685
  if cur_user.startswith(text):
@@ -1605,7 +1765,6 @@ class Cmd(cmd.Cmd):
1605
1765
 
1606
1766
  # Build display_matches and add a slash to directories
1607
1767
  for index, cur_match in enumerate(matches):
1608
-
1609
1768
  # Display only the basename of this path in the tab completion suggestions
1610
1769
  self.display_matches.append(os.path.basename(cur_match))
1611
1770
 
@@ -1674,7 +1833,6 @@ class Cmd(cmd.Cmd):
1674
1833
 
1675
1834
  # Must at least have the command
1676
1835
  if len(raw_tokens) > 1:
1677
-
1678
1836
  # True when command line contains any redirection tokens
1679
1837
  has_redirection = False
1680
1838
 
@@ -1766,7 +1924,6 @@ class Cmd(cmd.Cmd):
1766
1924
  :param longest_match_length: longest printed length of the matches
1767
1925
  """
1768
1926
  if rl_type == RlType.GNU:
1769
-
1770
1927
  # Print hint if one exists and we are supposed to display it
1771
1928
  hint_printed = False
1772
1929
  if self.always_show_hint and self.completion_hint:
@@ -1806,7 +1963,6 @@ class Cmd(cmd.Cmd):
1806
1963
 
1807
1964
  # rl_display_match_list() expects matches to be in argv format where
1808
1965
  # substitution is the first element, followed by the matches, and then a NULL.
1809
- # noinspection PyCallingNonCallable,PyTypeChecker
1810
1966
  strings_array = cast(List[Optional[bytes]], (ctypes.c_char_p * (1 + len(encoded_matches) + 1))())
1811
1967
 
1812
1968
  # Copy in the encoded strings and add a NULL to the end
@@ -1826,7 +1982,6 @@ class Cmd(cmd.Cmd):
1826
1982
  :param matches: the tab completion matches to display
1827
1983
  """
1828
1984
  if rl_type == RlType.PYREADLINE:
1829
-
1830
1985
  # Print hint if one exists and we are supposed to display it
1831
1986
  hint_printed = False
1832
1987
  if self.always_show_hint and self.completion_hint:
@@ -1865,9 +2020,8 @@ class Cmd(cmd.Cmd):
1865
2020
  :param parser: the parser to examine
1866
2021
  :return: type of ArgparseCompleter
1867
2022
  """
1868
- completer_type: Optional[
1869
- Type[argparse_completer.ArgparseCompleter]
1870
- ] = parser.get_ap_completer_type() # type: ignore[attr-defined]
2023
+ Completer = Optional[Type[argparse_completer.ArgparseCompleter]]
2024
+ completer_type: Completer = parser.get_ap_completer_type() # type: ignore[attr-defined]
1871
2025
 
1872
2026
  if completer_type is None:
1873
2027
  completer_type = argparse_completer.DEFAULT_AP_COMPLETER
@@ -1898,11 +2052,14 @@ class Cmd(cmd.Cmd):
1898
2052
 
1899
2053
  expanded_line = statement.command_and_args
1900
2054
 
1901
- # We overwrote line with a properly formatted but fully stripped version
1902
- # Restore the end spaces since line is only supposed to be lstripped when
1903
- # passed to completer functions according to Python docs
1904
- rstripped_len = len(line) - len(line.rstrip())
1905
- expanded_line += ' ' * rstripped_len
2055
+ if not expanded_line[-1:].isspace():
2056
+ # Unquoted trailing whitespace gets stripped by parse_command_only().
2057
+ # Restore it since line is only supposed to be lstripped when passed
2058
+ # to completer functions according to the Python cmd docs. Regardless
2059
+ # of what type of whitespace (' ', \n) was stripped, just append spaces
2060
+ # since shlex treats whitespace characters the same when splitting.
2061
+ rstripped_len = len(line) - len(line.rstrip())
2062
+ expanded_line += ' ' * rstripped_len
1906
2063
 
1907
2064
  # Fix the index values if expanded_line has a different size than line
1908
2065
  if len(expanded_line) != len(line):
@@ -1934,7 +2091,7 @@ class Cmd(cmd.Cmd):
1934
2091
  else:
1935
2092
  # There's no completer function, next see if the command uses argparse
1936
2093
  func = self.cmd_func(command)
1937
- argparser: Optional[argparse.ArgumentParser] = getattr(func, constants.CMD_ATTR_ARGPARSER, None)
2094
+ argparser = self._command_parsers.get(command, None)
1938
2095
 
1939
2096
  if func is not None and argparser is not None:
1940
2097
  # Get arguments for complete()
@@ -1980,7 +2137,6 @@ class Cmd(cmd.Cmd):
1980
2137
 
1981
2138
  # Check if the token being completed has an opening quote
1982
2139
  if raw_completion_token and raw_completion_token[0] in constants.QUOTES:
1983
-
1984
2140
  # Since the token is still being completed, we know the opening quote is unclosed.
1985
2141
  # Save the quote so we can add a matching closing quote later.
1986
2142
  completion_token_quote = raw_completion_token[0]
@@ -2005,7 +2161,6 @@ class Cmd(cmd.Cmd):
2005
2161
  self.completion_matches = self._redirect_complete(text, line, begidx, endidx, completer_func)
2006
2162
 
2007
2163
  if self.completion_matches:
2008
-
2009
2164
  # Eliminate duplicates
2010
2165
  self.completion_matches = utils.remove_duplicates(self.completion_matches)
2011
2166
  self.display_matches = utils.remove_duplicates(self.display_matches)
@@ -2020,7 +2175,6 @@ class Cmd(cmd.Cmd):
2020
2175
 
2021
2176
  # Check if we need to add an opening quote
2022
2177
  if not completion_token_quote:
2023
-
2024
2178
  add_quote = False
2025
2179
 
2026
2180
  # This is the tab completion text that will appear on the command line.
@@ -2073,7 +2227,6 @@ class Cmd(cmd.Cmd):
2073
2227
  :param custom_settings: used when not tab completing the main command line
2074
2228
  :return: the next possible completion for text or None
2075
2229
  """
2076
- # noinspection PyBroadException
2077
2230
  try:
2078
2231
  if state == 0:
2079
2232
  self._reset_completion_defaults()
@@ -2081,7 +2234,7 @@ class Cmd(cmd.Cmd):
2081
2234
  # Check if we are completing a multiline command
2082
2235
  if self._at_continuation_prompt:
2083
2236
  # lstrip and prepend the previously typed portion of this multiline command
2084
- lstripped_previous = self._multiline_in_progress.lstrip().replace(constants.LINE_FEED, ' ')
2237
+ lstripped_previous = self._multiline_in_progress.lstrip()
2085
2238
  line = lstripped_previous + readline.get_line_buffer()
2086
2239
 
2087
2240
  # Increment the indexes to account for the prepended text
@@ -2103,7 +2256,7 @@ class Cmd(cmd.Cmd):
2103
2256
  # from text and update the indexes. This only applies if we are at the beginning of the command line.
2104
2257
  shortcut_to_restore = ''
2105
2258
  if begidx == 0 and custom_settings is None:
2106
- for (shortcut, _) in self.statement_parser.shortcuts:
2259
+ for shortcut, _ in self.statement_parser.shortcuts:
2107
2260
  if text.startswith(shortcut):
2108
2261
  # Save the shortcut to restore later
2109
2262
  shortcut_to_restore = shortcut
@@ -2251,14 +2404,13 @@ class Cmd(cmd.Cmd):
2251
2404
  # Filter out hidden and disabled commands
2252
2405
  return [topic for topic in all_topics if topic not in self.hidden_commands and topic not in self.disabled_commands]
2253
2406
 
2254
- # noinspection PyUnusedLocal
2255
- def sigint_handler(self, signum: int, _: FrameType) -> None:
2407
+ def sigint_handler(self, signum: int, _: Optional[FrameType]) -> None:
2256
2408
  """Signal handler for SIGINTs which typically come from Ctrl-C events.
2257
2409
 
2258
- If you need custom SIGINT behavior, then override this function.
2410
+ If you need custom SIGINT behavior, then override this method.
2259
2411
 
2260
2412
  :param signum: signal number
2261
- :param _: required param for signal handlers
2413
+ :param _: the current stack frame or None
2262
2414
  """
2263
2415
  if self._cur_pipe_proc_reader is not None:
2264
2416
  # Pass the SIGINT to the current pipe process
@@ -2266,7 +2418,30 @@ class Cmd(cmd.Cmd):
2266
2418
 
2267
2419
  # Check if we are allowed to re-raise the KeyboardInterrupt
2268
2420
  if not self.sigint_protection:
2269
- self._raise_keyboard_interrupt()
2421
+ raise_interrupt = True
2422
+ if self.current_command is not None:
2423
+ command_set = self.find_commandset_for_command(self.current_command.command)
2424
+ if command_set is not None:
2425
+ raise_interrupt = not command_set.sigint_handler()
2426
+ if raise_interrupt:
2427
+ self._raise_keyboard_interrupt()
2428
+
2429
+ def termination_signal_handler(self, signum: int, _: Optional[FrameType]) -> None:
2430
+ """
2431
+ Signal handler for SIGHUP and SIGTERM. Only runs on Linux and Mac.
2432
+
2433
+ SIGHUP - received when terminal window is closed
2434
+ SIGTERM - received when this app has been requested to terminate
2435
+
2436
+ The basic purpose of this method is to call sys.exit() so our exit handler will run
2437
+ and save the persistent history file. If you need more complex behavior like killing
2438
+ threads and performing cleanup, then override this method.
2439
+
2440
+ :param signum: signal number
2441
+ :param _: the current stack frame or None
2442
+ """
2443
+ # POSIX systems add 128 to signal numbers for the exit code
2444
+ sys.exit(128 + signum)
2270
2445
 
2271
2446
  def _raise_keyboard_interrupt(self) -> None:
2272
2447
  """Helper function to raise a KeyboardInterrupt"""
@@ -2335,7 +2510,13 @@ class Cmd(cmd.Cmd):
2335
2510
  return statement.command, statement.args, statement.command_and_args
2336
2511
 
2337
2512
  def onecmd_plus_hooks(
2338
- self, line: str, *, add_to_history: bool = True, raise_keyboard_interrupt: bool = False, py_bridge_call: bool = False
2513
+ self,
2514
+ line: str,
2515
+ *,
2516
+ add_to_history: bool = True,
2517
+ raise_keyboard_interrupt: bool = False,
2518
+ py_bridge_call: bool = False,
2519
+ orig_rl_history_length: Optional[int] = None,
2339
2520
  ) -> bool:
2340
2521
  """Top-level function called by cmdloop() to handle parsing a line and running the command and all of its hooks.
2341
2522
 
@@ -2347,6 +2528,9 @@ class Cmd(cmd.Cmd):
2347
2528
  :param py_bridge_call: This should only ever be set to True by PyBridge to signify the beginning
2348
2529
  of an app() call from Python. It is used to enable/disable the storage of the
2349
2530
  command's stdout.
2531
+ :param orig_rl_history_length: Optional length of the readline history before the current command was typed.
2532
+ This is used to assist in combining multiline readline history entries and is only
2533
+ populated by cmd2. Defaults to None.
2350
2534
  :return: True if running of commands should stop
2351
2535
  """
2352
2536
  import datetime
@@ -2356,7 +2540,7 @@ class Cmd(cmd.Cmd):
2356
2540
 
2357
2541
  try:
2358
2542
  # Convert the line into a Statement
2359
- statement = self._input_line_to_statement(line)
2543
+ statement = self._input_line_to_statement(line, orig_rl_history_length=orig_rl_history_length)
2360
2544
 
2361
2545
  # call the postparsing hooks
2362
2546
  postparsing_data = plugin.PostparsingData(False, statement)
@@ -2510,7 +2694,7 @@ class Cmd(cmd.Cmd):
2510
2694
 
2511
2695
  return False
2512
2696
 
2513
- def _complete_statement(self, line: str) -> Statement:
2697
+ def _complete_statement(self, line: str, *, orig_rl_history_length: Optional[int] = None) -> Statement:
2514
2698
  """Keep accepting lines of input until the command is complete.
2515
2699
 
2516
2700
  There is some pretty hacky code here to handle some quirks of
@@ -2519,10 +2703,29 @@ class Cmd(cmd.Cmd):
2519
2703
  backwards compatibility with the standard library version of cmd.
2520
2704
 
2521
2705
  :param line: the line being parsed
2706
+ :param orig_rl_history_length: Optional length of the readline history before the current command was typed.
2707
+ This is used to assist in combining multiline readline history entries and is only
2708
+ populated by cmd2. Defaults to None.
2522
2709
  :return: the completed Statement
2523
2710
  :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
2524
2711
  :raises: EmptyStatement when the resulting Statement is blank
2525
2712
  """
2713
+
2714
+ def combine_rl_history(statement: Statement) -> None:
2715
+ """Combine all lines of a multiline command into a single readline history entry"""
2716
+ if orig_rl_history_length is None or not statement.multiline_command:
2717
+ return
2718
+
2719
+ # Remove all previous lines added to history for this command
2720
+ while readline.get_current_history_length() > orig_rl_history_length:
2721
+ readline.remove_history_item(readline.get_current_history_length() - 1)
2722
+
2723
+ formatted_command = single_line_format(statement)
2724
+
2725
+ # If formatted command is different than the previous history item, add it
2726
+ if orig_rl_history_length == 0 or formatted_command != readline.get_history_item(orig_rl_history_length):
2727
+ readline.add_history(formatted_command)
2728
+
2526
2729
  while True:
2527
2730
  try:
2528
2731
  statement = self.statement_parser.parse(line)
@@ -2534,7 +2737,7 @@ class Cmd(cmd.Cmd):
2534
2737
  # so we are done
2535
2738
  break
2536
2739
  except Cmd2ShlexError:
2537
- # we have unclosed quotation marks, lets parse only the command
2740
+ # we have an unclosed quotation mark, let's parse only the command
2538
2741
  # and see if it's a multiline
2539
2742
  statement = self.statement_parser.parse_command_only(line)
2540
2743
  if not statement.multiline_command:
@@ -2550,6 +2753,7 @@ class Cmd(cmd.Cmd):
2550
2753
  # Save the command line up to this point for tab completion
2551
2754
  self._multiline_in_progress = line + '\n'
2552
2755
 
2756
+ # Get next line of this command
2553
2757
  nextline = self._read_command_line(self.continuation_prompt)
2554
2758
  if nextline == 'eof':
2555
2759
  # they entered either a blank line, or we hit an EOF
@@ -2558,7 +2762,14 @@ class Cmd(cmd.Cmd):
2558
2762
  # terminator
2559
2763
  nextline = '\n'
2560
2764
  self.poutput(nextline)
2561
- line = f'{self._multiline_in_progress}{nextline}'
2765
+
2766
+ line += f'\n{nextline}'
2767
+
2768
+ # Combine all history lines of this multiline command as we go.
2769
+ if nextline:
2770
+ statement = self.statement_parser.parse_command_only(line)
2771
+ combine_rl_history(statement)
2772
+
2562
2773
  except KeyboardInterrupt:
2563
2774
  self.poutput('^C')
2564
2775
  statement = self.statement_parser.parse('')
@@ -2568,13 +2779,20 @@ class Cmd(cmd.Cmd):
2568
2779
 
2569
2780
  if not statement.command:
2570
2781
  raise EmptyStatement
2782
+ else:
2783
+ # If necessary, update history with completed multiline command.
2784
+ combine_rl_history(statement)
2785
+
2571
2786
  return statement
2572
2787
 
2573
- def _input_line_to_statement(self, line: str) -> Statement:
2788
+ def _input_line_to_statement(self, line: str, *, orig_rl_history_length: Optional[int] = None) -> Statement:
2574
2789
  """
2575
2790
  Parse the user's input line and convert it to a Statement, ensuring that all macros are also resolved
2576
2791
 
2577
2792
  :param line: the line being parsed
2793
+ :param orig_rl_history_length: Optional length of the readline history before the current command was typed.
2794
+ This is used to assist in combining multiline readline history entries and is only
2795
+ populated by cmd2. Defaults to None.
2578
2796
  :return: parsed command line as a Statement
2579
2797
  :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
2580
2798
  :raises: EmptyStatement when the resulting Statement is blank
@@ -2585,11 +2803,13 @@ class Cmd(cmd.Cmd):
2585
2803
  # Continue until all macros are resolved
2586
2804
  while True:
2587
2805
  # Make sure all input has been read and convert it to a Statement
2588
- statement = self._complete_statement(line)
2806
+ statement = self._complete_statement(line, orig_rl_history_length=orig_rl_history_length)
2589
2807
 
2590
- # Save the fully entered line if this is the first loop iteration
2808
+ # If this is the first loop iteration, save the original line and stop
2809
+ # combining multiline history entries in the remaining iterations.
2591
2810
  if orig_line is None:
2592
2811
  orig_line = statement.raw
2812
+ orig_rl_history_length = None
2593
2813
 
2594
2814
  # Check if this command matches a macro and wasn't already processed to avoid an infinite loop
2595
2815
  if statement.command in self.macros.keys() and statement.command not in used_macros:
@@ -2734,13 +2954,8 @@ class Cmd(cmd.Cmd):
2734
2954
  sys.stdout = self.stdout = new_stdout
2735
2955
 
2736
2956
  elif statement.output:
2737
- import tempfile
2738
-
2739
- if (not statement.output_to) and (not self._can_clip):
2740
- raise RedirectionError("Cannot redirect to paste buffer; missing 'pyperclip' and/or pyperclip dependencies")
2741
-
2742
- # Redirecting to a file
2743
- elif statement.output_to:
2957
+ if statement.output_to:
2958
+ # redirecting to a file
2744
2959
  # statement.output can only contain REDIRECTION_APPEND or REDIRECTION_OUTPUT
2745
2960
  mode = 'a' if statement.output == constants.REDIRECTION_APPEND else 'w'
2746
2961
  try:
@@ -2752,14 +2967,26 @@ class Cmd(cmd.Cmd):
2752
2967
  redir_saved_state.redirecting = True
2753
2968
  sys.stdout = self.stdout = new_stdout
2754
2969
 
2755
- # Redirecting to a paste buffer
2756
2970
  else:
2971
+ # Redirecting to a paste buffer
2972
+ # we are going to direct output to a temporary file, then read it back in and
2973
+ # put it in the paste buffer later
2974
+ if not self.allow_clipboard:
2975
+ raise RedirectionError("Clipboard access not allowed")
2976
+
2977
+ # attempt to get the paste buffer, this forces pyperclip to go figure
2978
+ # out if it can actually interact with the paste buffer, and will throw exceptions
2979
+ # if it's not gonna work. That way we throw the exception before we go
2980
+ # run the command and queue up all the output. if this is going to fail,
2981
+ # no point opening up the temporary file
2982
+ current_paste_buffer = get_paste_buffer()
2983
+ # create a temporary file to store output
2757
2984
  new_stdout = cast(TextIO, tempfile.TemporaryFile(mode="w+"))
2758
2985
  redir_saved_state.redirecting = True
2759
2986
  sys.stdout = self.stdout = new_stdout
2760
2987
 
2761
2988
  if statement.output == constants.REDIRECTION_APPEND:
2762
- self.stdout.write(get_paste_buffer())
2989
+ self.stdout.write(current_paste_buffer)
2763
2990
  self.stdout.flush()
2764
2991
 
2765
2992
  # These are updated regardless of whether the command redirected
@@ -2824,7 +3051,6 @@ class Cmd(cmd.Cmd):
2824
3051
  target = constants.COMMAND_FUNC_PREFIX + command
2825
3052
  return target if callable(getattr(self, target, None)) else ''
2826
3053
 
2827
- # noinspection PyMethodOverriding
2828
3054
  def onecmd(self, statement: Union[Statement, str], *, add_to_history: bool = True) -> bool:
2829
3055
  """This executes the actual do_* method for a command.
2830
3056
 
@@ -2849,7 +3075,11 @@ class Cmd(cmd.Cmd):
2849
3075
  ):
2850
3076
  self.history.append(statement)
2851
3077
 
2852
- stop = func(statement)
3078
+ try:
3079
+ self.current_command = statement
3080
+ stop = func(statement)
3081
+ finally:
3082
+ self.current_command = None
2853
3083
 
2854
3084
  else:
2855
3085
  stop = self.default(statement)
@@ -2865,15 +3095,19 @@ class Cmd(cmd.Cmd):
2865
3095
  if 'shell' not in self.exclude_from_history:
2866
3096
  self.history.append(statement)
2867
3097
 
2868
- # noinspection PyTypeChecker
2869
3098
  return self.do_shell(statement.command_and_args)
2870
3099
  else:
2871
3100
  err_msg = self.default_error.format(statement.command)
3101
+ if self.suggest_similar_command and (suggested_command := self._suggest_similar_command(statement.command)):
3102
+ err_msg += f"\n{self.default_suggestion_message.format(suggested_command)}"
2872
3103
 
2873
- # Set apply_style to False so default_error's style is not overridden
3104
+ # Set apply_style to False so styles for default_error and default_suggestion_message are not overridden
2874
3105
  self.perror(err_msg, apply_style=False)
2875
3106
  return None
2876
3107
 
3108
+ def _suggest_similar_command(self, command: str) -> Optional[str]:
3109
+ return suggest_similar(command, self.get_visible_commands())
3110
+
2877
3111
  def read_input(
2878
3112
  self,
2879
3113
  prompt: str,
@@ -2928,7 +3162,7 @@ class Cmd(cmd.Cmd):
2928
3162
  nonlocal saved_history
2929
3163
  nonlocal parser
2930
3164
 
2931
- if readline_configured: # pragma: no cover
3165
+ if readline_configured or rl_type == RlType.NONE: # pragma: no cover
2932
3166
  return
2933
3167
 
2934
3168
  # Configure tab completion
@@ -2937,7 +3171,7 @@ class Cmd(cmd.Cmd):
2937
3171
 
2938
3172
  # Disable completion
2939
3173
  if completion_mode == utils.CompletionMode.NONE:
2940
- # noinspection PyUnusedLocal
3174
+
2941
3175
  def complete_none(text: str, state: int) -> Optional[str]: # pragma: no cover
2942
3176
  return None
2943
3177
 
@@ -2968,7 +3202,6 @@ class Cmd(cmd.Cmd):
2968
3202
  if completion_mode != utils.CompletionMode.COMMANDS or history is not None:
2969
3203
  saved_history = []
2970
3204
  for i in range(1, readline.get_current_history_length() + 1):
2971
- # noinspection PyArgumentList
2972
3205
  saved_history.append(readline.get_history_item(i))
2973
3206
 
2974
3207
  readline.clear_history()
@@ -2981,7 +3214,7 @@ class Cmd(cmd.Cmd):
2981
3214
  def restore_readline() -> None:
2982
3215
  """Restore readline tab completion and history"""
2983
3216
  nonlocal readline_configured
2984
- if not readline_configured: # pragma: no cover
3217
+ if not readline_configured or rl_type == RlType.NONE: # pragma: no cover
2985
3218
  return
2986
3219
 
2987
3220
  if self._completion_supported():
@@ -3065,8 +3298,13 @@ class Cmd(cmd.Cmd):
3065
3298
  """
3066
3299
  readline_settings = _SavedReadlineSettings()
3067
3300
 
3068
- if self._completion_supported():
3301
+ if rl_type == RlType.GNU:
3302
+ # To calculate line count when printing async_alerts, we rely on commands wider than
3303
+ # the terminal to wrap across multiple lines. The default for horizontal-scroll-mode
3304
+ # is "off" but a user may have overridden it in their readline initialization file.
3305
+ readline.parse_and_bind("set horizontal-scroll-mode off")
3069
3306
 
3307
+ if self._completion_supported():
3070
3308
  # Set up readline for our tab completion needs
3071
3309
  if rl_type == RlType.GNU:
3072
3310
  # GNU readline automatically adds a closing quote if the text being completed has an opening quote.
@@ -3100,7 +3338,6 @@ class Cmd(cmd.Cmd):
3100
3338
  :param readline_settings: the readline settings to restore
3101
3339
  """
3102
3340
  if self._completion_supported():
3103
-
3104
3341
  # Restore what we changed in readline
3105
3342
  readline.set_completer(readline_settings.completer)
3106
3343
  readline.set_completer_delims(readline_settings.delims)
@@ -3109,7 +3346,6 @@ class Cmd(cmd.Cmd):
3109
3346
  readline.set_completion_display_matches_hook(None)
3110
3347
  rl_basic_quote_characters.value = readline_settings.basic_quotes
3111
3348
  elif rl_type == RlType.PYREADLINE:
3112
- # noinspection PyUnresolvedReferences
3113
3349
  readline.rl.mode._display_completions = orig_pyreadline_display
3114
3350
 
3115
3351
  def _cmdloop(self) -> None:
@@ -3131,6 +3367,13 @@ class Cmd(cmd.Cmd):
3131
3367
  self._startup_commands.clear()
3132
3368
 
3133
3369
  while not stop:
3370
+ # Used in building multiline readline history entries. Only applies
3371
+ # when command line is read by input() in a terminal.
3372
+ if rl_type != RlType.NONE and self.use_rawinput and sys.stdin.isatty():
3373
+ orig_rl_history_length = readline.get_current_history_length()
3374
+ else:
3375
+ orig_rl_history_length = None
3376
+
3134
3377
  # Get commands from user
3135
3378
  try:
3136
3379
  line = self._read_command_line(self.prompt)
@@ -3139,7 +3382,7 @@ class Cmd(cmd.Cmd):
3139
3382
  line = ''
3140
3383
 
3141
3384
  # Run the command along with all associated pre and post hooks
3142
- stop = self.onecmd_plus_hooks(line)
3385
+ stop = self.onecmd_plus_hooks(line, orig_rl_history_length=orig_rl_history_length)
3143
3386
  finally:
3144
3387
  # Get sigint protection while we restore readline settings
3145
3388
  with self.sigint_protection:
@@ -3573,7 +3816,7 @@ class Cmd(cmd.Cmd):
3573
3816
 
3574
3817
  # Check if this command uses argparse
3575
3818
  func = self.cmd_func(command)
3576
- argparser = getattr(func, constants.CMD_ATTR_ARGPARSER, None)
3819
+ argparser = self._command_parsers.get(command, None)
3577
3820
  if func is None or argparser is None:
3578
3821
  return []
3579
3822
 
@@ -3609,7 +3852,7 @@ class Cmd(cmd.Cmd):
3609
3852
  # Getting help for a specific command
3610
3853
  func = self.cmd_func(args.command)
3611
3854
  help_func = getattr(self, constants.HELP_FUNC_PREFIX + args.command, None)
3612
- argparser = getattr(func, constants.CMD_ATTR_ARGPARSER, None)
3855
+ argparser = self._command_parsers.get(args.command, None)
3613
3856
 
3614
3857
  # If the command function uses argparse, then use argparse's help
3615
3858
  if func is not None and argparser is not None:
@@ -3745,7 +3988,7 @@ class Cmd(cmd.Cmd):
3745
3988
  help_topics.remove(command)
3746
3989
 
3747
3990
  # Non-argparse commands can have help_functions for their documentation
3748
- if not hasattr(func, constants.CMD_ATTR_ARGPARSER):
3991
+ if command not in self._command_parsers:
3749
3992
  has_help_func = True
3750
3993
 
3751
3994
  if hasattr(func, constants.CMD_ATTR_HELP_CATEGORY):
@@ -3791,7 +4034,7 @@ class Cmd(cmd.Cmd):
3791
4034
  doc: Optional[str]
3792
4035
 
3793
4036
  # Non-argparse commands can have help_functions for their documentation
3794
- if not hasattr(cmd_func, constants.CMD_ATTR_ARGPARSER) and command in topics:
4037
+ if command not in self._command_parsers and command in topics:
3795
4038
  help_func = getattr(self, constants.HELP_FUNC_PREFIX + command)
3796
4039
  result = io.StringIO()
3797
4040
 
@@ -3844,7 +4087,6 @@ class Cmd(cmd.Cmd):
3844
4087
  self.poutput()
3845
4088
 
3846
4089
  # self.last_result will be set by do_quit()
3847
- # noinspection PyTypeChecker
3848
4090
  return self.do_quit('')
3849
4091
 
3850
4092
  quit_parser = argparse_custom.DEFAULT_ARGUMENT_PARSER(description="Exit this application")
@@ -3881,7 +4123,7 @@ class Cmd(cmd.Cmd):
3881
4123
  fulloptions.append((opt[0], opt[1]))
3882
4124
  except IndexError:
3883
4125
  fulloptions.append((opt[0], opt[0]))
3884
- for (idx, (_, text)) in enumerate(fulloptions):
4126
+ for idx, (_, text) in enumerate(fulloptions):
3885
4127
  self.poutput(' %2d. %s' % (idx + 1, text))
3886
4128
 
3887
4129
  while True:
@@ -3980,7 +4222,6 @@ class Cmd(cmd.Cmd):
3980
4222
  try:
3981
4223
  orig_value = settable.get_value()
3982
4224
  new_value = settable.set_value(utils.strip_quotes(args.value))
3983
- # noinspection PyBroadException
3984
4225
  except Exception as ex:
3985
4226
  self.perror(f"Error setting {args.param}: {ex}")
3986
4227
  else:
@@ -4116,7 +4357,6 @@ class Cmd(cmd.Cmd):
4116
4357
  if rl_type != RlType.NONE:
4117
4358
  # Save cmd2 history
4118
4359
  for i in range(1, readline.get_current_history_length() + 1):
4119
- # noinspection PyArgumentList
4120
4360
  cmd2_env.history.append(readline.get_history_item(i))
4121
4361
 
4122
4362
  readline.clear_history()
@@ -4150,7 +4390,6 @@ class Cmd(cmd.Cmd):
4150
4390
  if rl_type == RlType.GNU:
4151
4391
  readline.set_completion_display_matches_hook(None)
4152
4392
  elif rl_type == RlType.PYREADLINE:
4153
- # noinspection PyUnresolvedReferences
4154
4393
  readline.rl.mode._display_completions = orig_pyreadline_display
4155
4394
 
4156
4395
  # Save off the current completer and set a new one in the Python console
@@ -4185,7 +4424,6 @@ class Cmd(cmd.Cmd):
4185
4424
  # Save py's history
4186
4425
  self._py_history.clear()
4187
4426
  for i in range(1, readline.get_current_history_length() + 1):
4188
- # noinspection PyArgumentList
4189
4427
  self._py_history.append(readline.get_history_item(i))
4190
4428
 
4191
4429
  readline.clear_history()
@@ -4229,7 +4467,8 @@ class Cmd(cmd.Cmd):
4229
4467
  PyBridge,
4230
4468
  )
4231
4469
 
4232
- py_bridge = PyBridge(self)
4470
+ add_to_history = self.scripts_add_to_history if pyscript else True
4471
+ py_bridge = PyBridge(self, add_to_history=add_to_history)
4233
4472
  saved_sys_path = None
4234
4473
 
4235
4474
  if self.in_pyscript():
@@ -4281,7 +4520,6 @@ class Cmd(cmd.Cmd):
4281
4520
 
4282
4521
  # Check if we are running Python code
4283
4522
  if py_code_to_run:
4284
- # noinspection PyBroadException
4285
4523
  try:
4286
4524
  interp.runcode(py_code_to_run) # type: ignore[arg-type]
4287
4525
  except BaseException:
@@ -4299,7 +4537,6 @@ class Cmd(cmd.Cmd):
4299
4537
 
4300
4538
  saved_cmd2_env = None
4301
4539
 
4302
- # noinspection PyBroadException
4303
4540
  try:
4304
4541
  # Get sigint protection while we set up the Python shell environment
4305
4542
  with self.sigint_protection:
@@ -4380,7 +4617,6 @@ class Cmd(cmd.Cmd):
4380
4617
 
4381
4618
  ipython_parser = argparse_custom.DEFAULT_ARGUMENT_PARSER(description="Run an interactive IPython shell")
4382
4619
 
4383
- # noinspection PyPackageRequirements
4384
4620
  @with_argparser(ipython_parser)
4385
4621
  def do_ipy(self, _: argparse.Namespace) -> Optional[bool]: # pragma: no cover
4386
4622
  """
@@ -4436,7 +4672,7 @@ class Cmd(cmd.Cmd):
4436
4672
  )
4437
4673
 
4438
4674
  # Start IPython
4439
- start_ipython(config=config, argv=[], user_ns=local_vars)
4675
+ start_ipython(config=config, argv=[], user_ns=local_vars) # type: ignore[no-untyped-call]
4440
4676
  self.poutput("Now exiting IPython shell...")
4441
4677
 
4442
4678
  # The IPython application is a singleton and won't be recreated next time
@@ -4551,8 +4787,6 @@ class Cmd(cmd.Cmd):
4551
4787
  self.last_result = True
4552
4788
  return stop
4553
4789
  elif args.edit:
4554
- import tempfile
4555
-
4556
4790
  fd, fname = tempfile.mkstemp(suffix='.txt', text=True)
4557
4791
  fobj: TextIO
4558
4792
  with os.fdopen(fd, 'w') as fobj:
@@ -4565,7 +4799,6 @@ class Cmd(cmd.Cmd):
4565
4799
  self.run_editor(fname)
4566
4800
 
4567
4801
  # self.last_resort will be set by do_run_script()
4568
- # noinspection PyTypeChecker
4569
4802
  return self.do_run_script(utils.quote_string(fname))
4570
4803
  finally:
4571
4804
  os.remove(fname)
@@ -4625,11 +4858,9 @@ class Cmd(cmd.Cmd):
4625
4858
  previous sessions will be included. Additionally, all history will be written
4626
4859
  to this file when the application exits.
4627
4860
  """
4628
- import json
4629
- import lzma
4630
-
4631
4861
  self.history = History()
4632
- # with no persistent history, nothing else in this method is relevant
4862
+
4863
+ # With no persistent history, nothing else in this method is relevant
4633
4864
  if not hist_file:
4634
4865
  self.persistent_history_file = hist_file
4635
4866
  return
@@ -4650,64 +4881,96 @@ class Cmd(cmd.Cmd):
4650
4881
  self.perror(f"Error creating persistent history file directory '{hist_file_dir}': {ex}")
4651
4882
  return
4652
4883
 
4653
- # Read and process history file
4884
+ # Read history file
4654
4885
  try:
4655
4886
  with open(hist_file, 'rb') as fobj:
4656
4887
  compressed_bytes = fobj.read()
4657
- history_json = lzma.decompress(compressed_bytes).decode(encoding='utf-8')
4658
- self.history = History.from_json(history_json)
4659
4888
  except FileNotFoundError:
4660
- # Just use an empty history
4661
- pass
4889
+ compressed_bytes = bytes()
4662
4890
  except OSError as ex:
4663
4891
  self.perror(f"Cannot read persistent history file '{hist_file}': {ex}")
4664
4892
  return
4665
- except (json.JSONDecodeError, lzma.LZMAError, KeyError, UnicodeDecodeError, ValueError) as ex:
4893
+
4894
+ # Register a function to write history at save
4895
+ import atexit
4896
+
4897
+ self.persistent_history_file = hist_file
4898
+ atexit.register(self._persist_history)
4899
+
4900
+ # Empty or nonexistent history file. Nothing more to do.
4901
+ if not compressed_bytes:
4902
+ return
4903
+
4904
+ # Decompress history data
4905
+ try:
4906
+ import lzma as decompress_lib
4907
+
4908
+ decompress_exceptions: Tuple[type[Exception]] = (decompress_lib.LZMAError,)
4909
+ except ModuleNotFoundError: # pragma: no cover
4910
+ import bz2 as decompress_lib # type: ignore[no-redef]
4911
+
4912
+ decompress_exceptions: Tuple[type[Exception]] = (OSError, ValueError) # type: ignore[no-redef]
4913
+
4914
+ try:
4915
+ history_json = decompress_lib.decompress(compressed_bytes).decode(encoding='utf-8')
4916
+ except decompress_exceptions as ex:
4666
4917
  self.perror(
4667
- f"Error processing persistent history file '{hist_file}': {ex}\n"
4918
+ f"Error decompressing persistent history data '{hist_file}': {ex}\n"
4668
4919
  f"The history file will be recreated when this application exits."
4669
4920
  )
4921
+ return
4922
+
4923
+ # Decode history json
4924
+ import json
4925
+
4926
+ try:
4927
+ self.history = History.from_json(history_json)
4928
+ except (json.JSONDecodeError, KeyError, ValueError) as ex:
4929
+ self.perror(
4930
+ f"Error processing persistent history data '{hist_file}': {ex}\n"
4931
+ f"The history file will be recreated when this application exits."
4932
+ )
4933
+ return
4670
4934
 
4671
4935
  self.history.start_session()
4672
- self.persistent_history_file = hist_file
4673
4936
 
4674
- # populate readline history
4937
+ # Populate readline history
4675
4938
  if rl_type != RlType.NONE:
4676
- last = None
4677
4939
  for item in self.history:
4678
- # Break the command into its individual lines
4679
- for line in item.raw.splitlines():
4680
- # readline only adds a single entry for multiple sequential identical lines
4681
- # so we emulate that behavior here
4682
- if line != last:
4683
- readline.add_history(line)
4684
- last = line
4685
-
4686
- # register a function to write history at save
4687
- # if the history file is in plain text format from 0.9.12 or lower
4688
- # this will fail, and the history in the plain text file will be lost
4689
- import atexit
4940
+ formatted_command = single_line_format(item.statement)
4690
4941
 
4691
- atexit.register(self._persist_history)
4942
+ # If formatted command is different than the previous history item, add it
4943
+ cur_history_length = readline.get_current_history_length()
4944
+ if cur_history_length == 0 or formatted_command != readline.get_history_item(cur_history_length):
4945
+ readline.add_history(formatted_command)
4692
4946
 
4693
4947
  def _persist_history(self) -> None:
4694
4948
  """Write history out to the persistent history file as compressed JSON"""
4695
- import lzma
4696
-
4697
4949
  if not self.persistent_history_file:
4698
4950
  return
4699
4951
 
4700
- self.history.truncate(self._persistent_history_length)
4701
4952
  try:
4702
- history_json = self.history.to_json()
4703
- compressed_bytes = lzma.compress(history_json.encode(encoding='utf-8'))
4953
+ import lzma as compress_lib
4954
+ except ModuleNotFoundError: # pragma: no cover
4955
+ import bz2 as compress_lib # type: ignore[no-redef]
4704
4956
 
4957
+ self.history.truncate(self._persistent_history_length)
4958
+ history_json = self.history.to_json()
4959
+ compressed_bytes = compress_lib.compress(history_json.encode(encoding='utf-8'))
4960
+
4961
+ try:
4705
4962
  with open(self.persistent_history_file, 'wb') as fobj:
4706
4963
  fobj.write(compressed_bytes)
4707
4964
  except OSError as ex:
4708
4965
  self.perror(f"Cannot write persistent history file '{self.persistent_history_file}': {ex}")
4709
4966
 
4710
- def _generate_transcript(self, history: Union[List[HistoryItem], List[str]], transcript_file: str) -> None:
4967
+ def _generate_transcript(
4968
+ self,
4969
+ history: Union[List[HistoryItem], List[str]],
4970
+ transcript_file: str,
4971
+ *,
4972
+ add_to_history: bool = True,
4973
+ ) -> None:
4711
4974
  """Generate a transcript file from a given history of commands"""
4712
4975
  self.last_result = False
4713
4976
 
@@ -4757,7 +5020,11 @@ class Cmd(cmd.Cmd):
4757
5020
 
4758
5021
  # then run the command and let the output go into our buffer
4759
5022
  try:
4760
- stop = self.onecmd_plus_hooks(history_item, raise_keyboard_interrupt=True)
5023
+ stop = self.onecmd_plus_hooks(
5024
+ history_item,
5025
+ add_to_history=add_to_history,
5026
+ raise_keyboard_interrupt=True,
5027
+ )
4761
5028
  except KeyboardInterrupt as ex:
4762
5029
  self.perror(ex)
4763
5030
  stop = True
@@ -4829,7 +5096,6 @@ class Cmd(cmd.Cmd):
4829
5096
  if file_path:
4830
5097
  command += " " + utils.quote_string(os.path.expanduser(file_path))
4831
5098
 
4832
- # noinspection PyTypeChecker
4833
5099
  self.do_shell(command)
4834
5100
 
4835
5101
  @property
@@ -4902,9 +5168,17 @@ class Cmd(cmd.Cmd):
4902
5168
 
4903
5169
  if args.transcript:
4904
5170
  # self.last_resort will be set by _generate_transcript()
4905
- self._generate_transcript(script_commands, os.path.expanduser(args.transcript))
5171
+ self._generate_transcript(
5172
+ script_commands,
5173
+ os.path.expanduser(args.transcript),
5174
+ add_to_history=self.scripts_add_to_history,
5175
+ )
4906
5176
  else:
4907
- stop = self.runcmds_plus_hooks(script_commands, stop_on_keyboard_interrupt=True)
5177
+ stop = self.runcmds_plus_hooks(
5178
+ script_commands,
5179
+ add_to_history=self.scripts_add_to_history,
5180
+ stop_on_keyboard_interrupt=True,
5181
+ )
4908
5182
  self.last_result = True
4909
5183
  return stop
4910
5184
 
@@ -4941,7 +5215,6 @@ class Cmd(cmd.Cmd):
4941
5215
  relative_path = os.path.join(self._current_script_dir or '', file_path)
4942
5216
 
4943
5217
  # self.last_result will be set by do_run_script()
4944
- # noinspection PyTypeChecker
4945
5218
  return self.do_run_script(utils.quote_string(relative_path))
4946
5219
 
4947
5220
  def _run_transcript_tests(self, transcript_paths: List[str]) -> None:
@@ -4984,7 +5257,6 @@ class Cmd(cmd.Cmd):
4984
5257
  sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()
4985
5258
  testcase = TestMyAppCase()
4986
5259
  stream = cast(TextIO, utils.StdSim(sys.stderr))
4987
- # noinspection PyTypeChecker
4988
5260
  runner = unittest.TextTestRunner(stream=stream)
4989
5261
  start_time = time.time()
4990
5262
  test_results = runner.run(testcase)
@@ -4992,8 +5264,8 @@ class Cmd(cmd.Cmd):
4992
5264
  if test_results.wasSuccessful():
4993
5265
  ansi.style_aware_write(sys.stderr, stream.read())
4994
5266
  finish_msg = f' {num_transcripts} transcript{plural} passed in {execution_time:.3f} seconds '
4995
- finish_msg = ansi.style_success(utils.align_center(finish_msg, fill_char='='))
4996
- self.poutput(finish_msg)
5267
+ finish_msg = utils.align_center(finish_msg, fill_char='=')
5268
+ self.psuccess(finish_msg)
4997
5269
  else:
4998
5270
  # Strip off the initial traceback which isn't particularly useful for end users
4999
5271
  error_str = stream.read()
@@ -5010,16 +5282,16 @@ class Cmd(cmd.Cmd):
5010
5282
  def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: # pragma: no cover
5011
5283
  """
5012
5284
  Display an important message to the user while they are at a command line prompt.
5013
- To the user it appears as if an alert message is printed above the prompt and their current input
5014
- text and cursor location is left alone.
5285
+ To the user it appears as if an alert message is printed above the prompt and their
5286
+ current input text and cursor location is left alone.
5015
5287
 
5016
- IMPORTANT: This function will not print an alert unless it can acquire self.terminal_lock to ensure
5017
- a prompt is onscreen. Therefore, it is best to acquire the lock before calling this function
5018
- to guarantee the alert prints and to avoid raising a RuntimeError.
5288
+ This function needs to acquire self.terminal_lock to ensure a prompt is on screen.
5289
+ Therefore, it is best to acquire the lock before calling this function to avoid
5290
+ raising a RuntimeError.
5019
5291
 
5020
- This function is only needed when you need to print an alert while the main thread is blocking
5021
- at the prompt. Therefore, this should never be called from the main thread. Doing so will
5022
- raise a RuntimeError.
5292
+ This function is only needed when you need to print an alert or update the prompt while the
5293
+ main thread is blocking at the prompt. Therefore, this should never be called from the main
5294
+ thread. Doing so will raise a RuntimeError.
5023
5295
 
5024
5296
  :param alert_msg: the message to display to the user
5025
5297
  :param new_prompt: If you also want to change the prompt that is displayed, then include it here.
@@ -5035,7 +5307,6 @@ class Cmd(cmd.Cmd):
5035
5307
 
5036
5308
  # Sanity check that can't fail if self.terminal_lock was acquired before calling this function
5037
5309
  if self.terminal_lock.acquire(blocking=False):
5038
-
5039
5310
  # Windows terminals tend to flicker when we redraw the prompt and input lines.
5040
5311
  # To reduce how often this occurs, only update terminal if there are changes.
5041
5312
  update_terminal = False
@@ -5047,20 +5318,18 @@ class Cmd(cmd.Cmd):
5047
5318
  if new_prompt is not None:
5048
5319
  self.prompt = new_prompt
5049
5320
 
5050
- # Check if the prompt to display has changed from what's currently displayed
5051
- cur_onscreen_prompt = rl_get_prompt()
5052
- new_onscreen_prompt = self.continuation_prompt if self._at_continuation_prompt else self.prompt
5053
-
5054
- if new_onscreen_prompt != cur_onscreen_prompt:
5321
+ # Check if the onscreen prompt needs to be refreshed to match self.prompt.
5322
+ if self.need_prompt_refresh():
5055
5323
  update_terminal = True
5324
+ rl_set_prompt(self.prompt)
5056
5325
 
5057
5326
  if update_terminal:
5058
5327
  import shutil
5059
5328
 
5060
- # Generate the string which will replace the current prompt and input lines with the alert
5329
+ # Print a string which replaces the onscreen prompt and input lines with the alert.
5061
5330
  terminal_str = ansi.async_alert_str(
5062
5331
  terminal_columns=shutil.get_terminal_size().columns,
5063
- prompt=cur_onscreen_prompt,
5332
+ prompt=rl_get_display_prompt(),
5064
5333
  line=readline.get_line_buffer(),
5065
5334
  cursor_offset=rl_get_point(),
5066
5335
  alert_msg=alert_msg,
@@ -5069,12 +5338,8 @@ class Cmd(cmd.Cmd):
5069
5338
  sys.stderr.write(terminal_str)
5070
5339
  sys.stderr.flush()
5071
5340
  elif rl_type == RlType.PYREADLINE:
5072
- # noinspection PyUnresolvedReferences
5073
5341
  readline.rl.mode.console.write(terminal_str)
5074
5342
 
5075
- # Update Readline's prompt before we redraw it
5076
- rl_set_prompt(new_onscreen_prompt)
5077
-
5078
5343
  # Redraw the prompt and input lines below the alert
5079
5344
  rl_force_redisplay()
5080
5345
 
@@ -5085,23 +5350,17 @@ class Cmd(cmd.Cmd):
5085
5350
 
5086
5351
  def async_update_prompt(self, new_prompt: str) -> None: # pragma: no cover
5087
5352
  """
5088
- Update the command line prompt while the user is still typing at it. This is good for alerting the user to
5089
- system changes dynamically in between commands. For instance you could alter the color of the prompt to
5090
- indicate a system status or increase a counter to report an event. If you do alter the actual text of the
5091
- prompt, it is best to keep the prompt the same width as what's on screen. Otherwise the user's input text will
5092
- be shifted and the update will not be seamless.
5353
+ Update the command line prompt while the user is still typing at it.
5093
5354
 
5094
- IMPORTANT: This function will not update the prompt unless it can acquire self.terminal_lock to ensure
5095
- a prompt is onscreen. Therefore, it is best to acquire the lock before calling this function
5096
- to guarantee the prompt changes and to avoid raising a RuntimeError.
5355
+ This is good for alerting the user to system changes dynamically in between commands.
5356
+ For instance you could alter the color of the prompt to indicate a system status or increase a
5357
+ counter to report an event. If you do alter the actual text of the prompt, it is best to keep
5358
+ the prompt the same width as what's on screen. Otherwise the user's input text will be shifted
5359
+ and the update will not be seamless.
5097
5360
 
5098
- This function is only needed when you need to update the prompt while the main thread is blocking
5099
- at the prompt. Therefore, this should never be called from the main thread. Doing so will
5100
- raise a RuntimeError.
5101
-
5102
- If user is at a continuation prompt while entering a multiline command, the onscreen prompt will
5103
- not change. However, self.prompt will still be updated and display immediately after the multiline
5104
- line command completes.
5361
+ If user is at a continuation prompt while entering a multiline command, the onscreen prompt will
5362
+ not change. However, self.prompt will still be updated and display immediately after the multiline
5363
+ line command completes.
5105
5364
 
5106
5365
  :param new_prompt: what to change the prompt to
5107
5366
  :raises RuntimeError: if called from the main thread.
@@ -5109,6 +5368,32 @@ class Cmd(cmd.Cmd):
5109
5368
  """
5110
5369
  self.async_alert('', new_prompt)
5111
5370
 
5371
+ def async_refresh_prompt(self) -> None: # pragma: no cover
5372
+ """
5373
+ Refresh the oncreen prompt to match self.prompt.
5374
+
5375
+ One case where the onscreen prompt and self.prompt can get out of sync is
5376
+ when async_alert() is called while a user is in search mode (e.g. Ctrl-r).
5377
+ To prevent overwriting readline's onscreen search prompt, self.prompt is updated
5378
+ but readline's saved prompt isn't.
5379
+
5380
+ Therefore when a user aborts a search, the old prompt is still on screen until they
5381
+ press Enter or this method is called. Call need_prompt_refresh() in an async print
5382
+ thread to know when a refresh is needed.
5383
+
5384
+ :raises RuntimeError: if called from the main thread.
5385
+ :raises RuntimeError: if called while another thread holds `terminal_lock`
5386
+ """
5387
+ self.async_alert('')
5388
+
5389
+ def need_prompt_refresh(self) -> bool: # pragma: no cover
5390
+ """Check whether the onscreen prompt needs to be asynchronously refreshed to match self.prompt."""
5391
+ if not (vt100_support and self.use_rawinput):
5392
+ return False
5393
+
5394
+ # Don't overwrite a readline search prompt or a continuation prompt.
5395
+ return not rl_in_search_mode() and not self._at_continuation_prompt and self.prompt != rl_get_prompt()
5396
+
5112
5397
  @staticmethod
5113
5398
  def set_window_title(title: str) -> None: # pragma: no cover
5114
5399
  """
@@ -5252,14 +5537,21 @@ class Cmd(cmd.Cmd):
5252
5537
  """
5253
5538
  # cmdloop() expects to be run in the main thread to support extensive use of KeyboardInterrupts throughout the
5254
5539
  # other built-in functions. You are free to override cmdloop, but much of cmd2's features will be limited.
5255
- if not threading.current_thread() is threading.main_thread():
5540
+ if threading.current_thread() is not threading.main_thread():
5256
5541
  raise RuntimeError("cmdloop must be run in the main thread")
5257
5542
 
5258
- # Register a SIGINT signal handler for Ctrl+C
5543
+ # Register signal handlers
5259
5544
  import signal
5260
5545
 
5261
5546
  original_sigint_handler = signal.getsignal(signal.SIGINT)
5262
- signal.signal(signal.SIGINT, self.sigint_handler) # type: ignore
5547
+ signal.signal(signal.SIGINT, self.sigint_handler)
5548
+
5549
+ if not sys.platform.startswith('win'):
5550
+ original_sighup_handler = signal.getsignal(signal.SIGHUP)
5551
+ signal.signal(signal.SIGHUP, self.termination_signal_handler)
5552
+
5553
+ original_sigterm_handler = signal.getsignal(signal.SIGTERM)
5554
+ signal.signal(signal.SIGTERM, self.termination_signal_handler)
5263
5555
 
5264
5556
  # Grab terminal lock before the command line prompt has been drawn by readline
5265
5557
  self.terminal_lock.acquire()
@@ -5293,9 +5585,13 @@ class Cmd(cmd.Cmd):
5293
5585
  # This will also zero the lock count in case cmdloop() is called again
5294
5586
  self.terminal_lock.release()
5295
5587
 
5296
- # Restore the original signal handler
5588
+ # Restore original signal handlers
5297
5589
  signal.signal(signal.SIGINT, original_sigint_handler)
5298
5590
 
5591
+ if not sys.platform.startswith('win'):
5592
+ signal.signal(signal.SIGHUP, original_sighup_handler)
5593
+ signal.signal(signal.SIGTERM, original_sigterm_handler)
5594
+
5299
5595
  return self.exit_code
5300
5596
 
5301
5597
  ###
@@ -5446,7 +5742,7 @@ class Cmd(cmd.Cmd):
5446
5742
  func_self = None
5447
5743
  candidate_sets: List[CommandSet] = []
5448
5744
  for installed_cmd_set in self._installed_command_sets:
5449
- if type(installed_cmd_set) == func_class:
5745
+ if type(installed_cmd_set) == func_class: # noqa: E721
5450
5746
  # Case 2: CommandSet is an exact type match for the function's CommandSet
5451
5747
  func_self = installed_cmd_set
5452
5748
  break