id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
230,200
python-cmd2/cmd2
examples/tab_completion.py
TabCompleteExample.do_add_item
def do_add_item(self, args): """Add item command help""" if args.food: add_item = args.food elif args.sport: add_item = args.sport elif args.other: add_item = args.other else: add_item = 'no items' self.poutput("You added {}".format(add_item))
python
def do_add_item(self, args): if args.food: add_item = args.food elif args.sport: add_item = args.sport elif args.other: add_item = args.other else: add_item = 'no items' self.poutput("You added {}".format(add_item))
[ "def", "do_add_item", "(", "self", ",", "args", ")", ":", "if", "args", ".", "food", ":", "add_item", "=", "args", ".", "food", "elif", "args", ".", "sport", ":", "add_item", "=", "args", ".", "sport", "elif", "args", ".", "other", ":", "add_item", ...
Add item command help
[ "Add", "item", "command", "help" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/tab_completion.py#L27-L38
230,201
python-cmd2/cmd2
examples/decorator_example.py
CmdLineApp.do_tag
def do_tag(self, args: argparse.Namespace): """create an html tag""" # The Namespace always includes the Statement object created when parsing the command line statement = args.__statement__ self.poutput("The command line you ran was: {}".format(statement.command_and_args)) self.poutput("It generated this tag:") self.poutput('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
python
def do_tag(self, args: argparse.Namespace): # The Namespace always includes the Statement object created when parsing the command line statement = args.__statement__ self.poutput("The command line you ran was: {}".format(statement.command_and_args)) self.poutput("It generated this tag:") self.poutput('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content)))
[ "def", "do_tag", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", ":", "# The Namespace always includes the Statement object created when parsing the command line", "statement", "=", "args", ".", "__statement__", "self", ".", "poutput", "(", "\"The comman...
create an html tag
[ "create", "an", "html", "tag" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/decorator_example.py#L71-L78
230,202
python-cmd2/cmd2
examples/decorator_example.py
CmdLineApp.do_tagg
def do_tagg(self, arglist: List[str]): """version of creating an html tag using arglist instead of argparser""" if len(arglist) >= 2: tag = arglist[0] content = arglist[1:] self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content))) else: self.perror("tagg requires at least 2 arguments")
python
def do_tagg(self, arglist: List[str]): if len(arglist) >= 2: tag = arglist[0] content = arglist[1:] self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content))) else: self.perror("tagg requires at least 2 arguments")
[ "def", "do_tagg", "(", "self", ",", "arglist", ":", "List", "[", "str", "]", ")", ":", "if", "len", "(", "arglist", ")", ">=", "2", ":", "tag", "=", "arglist", "[", "0", "]", "content", "=", "arglist", "[", "1", ":", "]", "self", ".", "poutput"...
version of creating an html tag using arglist instead of argparser
[ "version", "of", "creating", "an", "html", "tag", "using", "arglist", "instead", "of", "argparser" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/decorator_example.py#L81-L88
230,203
python-cmd2/cmd2
examples/exit_code.py
ReplWithExitCode.do_exit
def do_exit(self, arg_list: List[str]) -> bool: """Exit the application with an optional exit code. Usage: exit [exit_code] Where: * exit_code - integer exit code to return to the shell """ # If an argument was provided if arg_list: try: self.exit_code = int(arg_list[0]) except ValueError: self.perror("{} isn't a valid integer exit code".format(arg_list[0])) self.exit_code = -1 self._should_quit = True return self._STOP_AND_EXIT
python
def do_exit(self, arg_list: List[str]) -> bool: # If an argument was provided if arg_list: try: self.exit_code = int(arg_list[0]) except ValueError: self.perror("{} isn't a valid integer exit code".format(arg_list[0])) self.exit_code = -1 self._should_quit = True return self._STOP_AND_EXIT
[ "def", "do_exit", "(", "self", ",", "arg_list", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "# If an argument was provided", "if", "arg_list", ":", "try", ":", "self", ".", "exit_code", "=", "int", "(", "arg_list", "[", "0", "]", ")", "except...
Exit the application with an optional exit code. Usage: exit [exit_code] Where: * exit_code - integer exit code to return to the shell
[ "Exit", "the", "application", "with", "an", "optional", "exit", "code", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/exit_code.py#L17-L33
230,204
python-cmd2/cmd2
cmd2/cmd2.py
categorize
def categorize(func: Union[Callable, Iterable], category: str) -> None: """Categorize a function. The help command output will group this function under the specified category heading :param func: function to categorize :param category: category to put it in """ if isinstance(func, Iterable): for item in func: setattr(item, HELP_CATEGORY, category) else: setattr(func, HELP_CATEGORY, category)
python
def categorize(func: Union[Callable, Iterable], category: str) -> None: if isinstance(func, Iterable): for item in func: setattr(item, HELP_CATEGORY, category) else: setattr(func, HELP_CATEGORY, category)
[ "def", "categorize", "(", "func", ":", "Union", "[", "Callable", ",", "Iterable", "]", ",", "category", ":", "str", ")", "->", "None", ":", "if", "isinstance", "(", "func", ",", "Iterable", ")", ":", "for", "item", "in", "func", ":", "setattr", "(", ...
Categorize a function. The help command output will group this function under the specified category heading :param func: function to categorize :param category: category to put it in
[ "Categorize", "a", "function", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L142-L154
230,205
python-cmd2/cmd2
cmd2/cmd2.py
with_category
def with_category(category: str) -> Callable: """A decorator to apply a category to a command function.""" def cat_decorator(func): categorize(func, category) return func return cat_decorator
python
def with_category(category: str) -> Callable: def cat_decorator(func): categorize(func, category) return func return cat_decorator
[ "def", "with_category", "(", "category", ":", "str", ")", "->", "Callable", ":", "def", "cat_decorator", "(", "func", ")", ":", "categorize", "(", "func", ",", "category", ")", "return", "func", "return", "cat_decorator" ]
A decorator to apply a category to a command function.
[ "A", "decorator", "to", "apply", "a", "category", "to", "a", "command", "function", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L157-L162
230,206
python-cmd2/cmd2
cmd2/cmd2.py
with_argparser_and_unknown_args
def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \ Callable[[argparse.Namespace, List], Optional[bool]]: """A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given instance of argparse.ArgumentParser, but also returning unknown args as a list. :param argparser: unique instance of ArgumentParser :param preserve_quotes: if True, then arguments passed to argparse maintain their quotes :return: function that gets passed argparse-parsed args in a Namespace and a list of unknown argument strings A member called __statement__ is added to the Namespace to provide command functions access to the Statement object. This can be useful if the command function needs to know the command line. """ import functools # noinspection PyProtectedMember def arg_decorator(func: Callable): @functools.wraps(func) def cmd_wrapper(cmd2_instance, statement: Union[Statement, str]): statement, parsed_arglist = cmd2_instance.statement_parser.get_command_arg_list(command_name, statement, preserve_quotes) try: args, unknown = argparser.parse_known_args(parsed_arglist) except SystemExit: return else: setattr(args, '__statement__', statement) return func(cmd2_instance, args, unknown) # argparser defaults the program name to sys.argv[0] # we want it to be the name of our command command_name = func.__name__[len(COMMAND_FUNC_PREFIX):] argparser.prog = command_name # If the description has not been set, then use the method docstring if one exists if argparser.description is None and func.__doc__: argparser.description = func.__doc__ # Set the command's help text as argparser.description (which can be None) cmd_wrapper.__doc__ = argparser.description # Mark this function as having an argparse ArgumentParser setattr(cmd_wrapper, 'argparser', argparser) return cmd_wrapper return arg_decorator
python
def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \ Callable[[argparse.Namespace, List], Optional[bool]]: import functools # noinspection PyProtectedMember def arg_decorator(func: Callable): @functools.wraps(func) def cmd_wrapper(cmd2_instance, statement: Union[Statement, str]): statement, parsed_arglist = cmd2_instance.statement_parser.get_command_arg_list(command_name, statement, preserve_quotes) try: args, unknown = argparser.parse_known_args(parsed_arglist) except SystemExit: return else: setattr(args, '__statement__', statement) return func(cmd2_instance, args, unknown) # argparser defaults the program name to sys.argv[0] # we want it to be the name of our command command_name = func.__name__[len(COMMAND_FUNC_PREFIX):] argparser.prog = command_name # If the description has not been set, then use the method docstring if one exists if argparser.description is None and func.__doc__: argparser.description = func.__doc__ # Set the command's help text as argparser.description (which can be None) cmd_wrapper.__doc__ = argparser.description # Mark this function as having an argparse ArgumentParser setattr(cmd_wrapper, 'argparser', argparser) return cmd_wrapper return arg_decorator
[ "def", "with_argparser_and_unknown_args", "(", "argparser", ":", "argparse", ".", "ArgumentParser", ",", "preserve_quotes", ":", "bool", "=", "False", ")", "->", "Callable", "[", "[", "argparse", ".", "Namespace", ",", "List", "]", ",", "Optional", "[", "bool"...
A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given instance of argparse.ArgumentParser, but also returning unknown args as a list. :param argparser: unique instance of ArgumentParser :param preserve_quotes: if True, then arguments passed to argparse maintain their quotes :return: function that gets passed argparse-parsed args in a Namespace and a list of unknown argument strings A member called __statement__ is added to the Namespace to provide command functions access to the Statement object. This can be useful if the command function needs to know the command line.
[ "A", "decorator", "to", "alter", "a", "cmd2", "method", "to", "populate", "its", "args", "argument", "by", "parsing", "arguments", "with", "the", "given", "instance", "of", "argparse", ".", "ArgumentParser", "but", "also", "returning", "unknown", "args", "as",...
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L194-L241
230,207
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.decolorized_write
def decolorized_write(self, fileobj: IO, msg: str) -> None: """Write a string to a fileobject, stripping ANSI escape sequences if necessary Honor the current colors setting, which requires us to check whether the fileobject is a tty. """ if self.colors.lower() == constants.COLORS_NEVER.lower() or \ (self.colors.lower() == constants.COLORS_TERMINAL.lower() and not fileobj.isatty()): msg = utils.strip_ansi(msg) fileobj.write(msg)
python
def decolorized_write(self, fileobj: IO, msg: str) -> None: if self.colors.lower() == constants.COLORS_NEVER.lower() or \ (self.colors.lower() == constants.COLORS_TERMINAL.lower() and not fileobj.isatty()): msg = utils.strip_ansi(msg) fileobj.write(msg)
[ "def", "decolorized_write", "(", "self", ",", "fileobj", ":", "IO", ",", "msg", ":", "str", ")", "->", "None", ":", "if", "self", ".", "colors", ".", "lower", "(", ")", "==", "constants", ".", "COLORS_NEVER", ".", "lower", "(", ")", "or", "(", "sel...
Write a string to a fileobject, stripping ANSI escape sequences if necessary Honor the current colors setting, which requires us to check whether the fileobject is a tty.
[ "Write", "a", "string", "to", "a", "fileobject", "stripping", "ANSI", "escape", "sequences", "if", "necessary" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L582-L591
230,208
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.perror
def perror(self, err: Union[str, Exception], traceback_war: bool = True, err_color: str = Fore.LIGHTRED_EX, war_color: str = Fore.LIGHTYELLOW_EX) -> None: """ Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists. :param err: an Exception or error message to print out :param traceback_war: (optional) if True, print a message to let user know they can enable debug :param err_color: (optional) color escape to output error with :param war_color: (optional) color escape to output warning with """ if self.debug and sys.exc_info() != (None, None, None): import traceback traceback.print_exc() if isinstance(err, Exception): err_msg = "EXCEPTION of type '{}' occurred with message: '{}'\n".format(type(err).__name__, err) else: err_msg = "{}\n".format(err) err_msg = err_color + err_msg + Fore.RESET self.decolorized_write(sys.stderr, err_msg) if traceback_war and not self.debug: war = "To enable full traceback, run the following command: 'set debug true'\n" war = war_color + war + Fore.RESET self.decolorized_write(sys.stderr, war)
python
def perror(self, err: Union[str, Exception], traceback_war: bool = True, err_color: str = Fore.LIGHTRED_EX, war_color: str = Fore.LIGHTYELLOW_EX) -> None: if self.debug and sys.exc_info() != (None, None, None): import traceback traceback.print_exc() if isinstance(err, Exception): err_msg = "EXCEPTION of type '{}' occurred with message: '{}'\n".format(type(err).__name__, err) else: err_msg = "{}\n".format(err) err_msg = err_color + err_msg + Fore.RESET self.decolorized_write(sys.stderr, err_msg) if traceback_war and not self.debug: war = "To enable full traceback, run the following command: 'set debug true'\n" war = war_color + war + Fore.RESET self.decolorized_write(sys.stderr, war)
[ "def", "perror", "(", "self", ",", "err", ":", "Union", "[", "str", ",", "Exception", "]", ",", "traceback_war", ":", "bool", "=", "True", ",", "err_color", ":", "str", "=", "Fore", ".", "LIGHTRED_EX", ",", "war_color", ":", "str", "=", "Fore", ".", ...
Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists. :param err: an Exception or error message to print out :param traceback_war: (optional) if True, print a message to let user know they can enable debug :param err_color: (optional) color escape to output error with :param war_color: (optional) color escape to output warning with
[ "Print", "error", "message", "to", "sys", ".", "stderr", "and", "if", "debug", "is", "true", "print", "an", "exception", "Traceback", "if", "one", "exists", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L621-L644
230,209
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.pfeedback
def pfeedback(self, msg: str) -> None: """For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.""" if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: self.decolorized_write(sys.stderr, "{}\n".format(msg))
python
def pfeedback(self, msg: str) -> None: if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: self.decolorized_write(sys.stderr, "{}\n".format(msg))
[ "def", "pfeedback", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "if", "not", "self", ".", "quiet", ":", "if", "self", ".", "feedback_to_output", ":", "self", ".", "poutput", "(", "msg", ")", "else", ":", "self", ".", "decolorized_wri...
For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.
[ "For", "printing", "nonessential", "feedback", ".", "Can", "be", "silenced", "with", "quiet", ".", "Inclusion", "in", "redirected", "output", "is", "controlled", "by", "feedback_to_output", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L646-L653
230,210
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.ppaged
def ppaged(self, msg: str, end: str = '\n', chop: bool = False) -> None: """Print output using a pager if it would go off screen and stdout isn't currently being redirected. Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when stdout or stdin are not a fully functional terminal. :param msg: message to print to current stdout (anything convertible to a str with '{}'.format() is OK) :param end: string appended after the end of the message if not already present, default a newline :param chop: True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped - truncated text is still accessible by scrolling with the right & left arrow keys - chopping is ideal for displaying wide tabular data as is done in utilities like pgcli False -> causes lines longer than the screen width to wrap to the next line - wrapping is ideal when you want to keep users from having to use horizontal scrolling WARNING: On Windows, the text always wraps regardless of what the chop argument is set to """ import subprocess if msg is not None and msg != '': try: msg_str = '{}'.format(msg) if not msg_str.endswith(end): msg_str += end # Attempt to detect if we are not running within a fully functional terminal. # Don't try to use the pager when being run by a continuous integration system like Jenkins + pexpect. functional_terminal = False if self.stdin.isatty() and self.stdout.isatty(): if sys.platform.startswith('win') or os.environ.get('TERM') is not None: functional_terminal = True # Don't attempt to use a pager that can block if redirecting or running a script (either text or Python) # Also only attempt to use a pager if actually running in a real fully functional terminal if functional_terminal and not self.redirecting and not self._in_py and not self._script_dir: if self.colors.lower() == constants.COLORS_NEVER.lower(): msg_str = utils.strip_ansi(msg_str) pager = self.pager if chop: pager = self.pager_chop # Prevent KeyboardInterrupts while in the pager. The pager application will # still receive the SIGINT since it is in the same process group as us. with self.sigint_protection: pipe_proc = subprocess.Popen(pager, shell=True, stdin=subprocess.PIPE) pipe_proc.communicate(msg_str.encode('utf-8', 'replace')) else: self.decolorized_write(self.stdout, msg_str) except BrokenPipeError: # This occurs if a command's output is being piped to another process and that process closes before the # command is finished. If you would like your application to print a warning message, then set the # broken_pipe_warning attribute to the message you want printed.` if self.broken_pipe_warning: sys.stderr.write(self.broken_pipe_warning)
python
def ppaged(self, msg: str, end: str = '\n', chop: bool = False) -> None: import subprocess if msg is not None and msg != '': try: msg_str = '{}'.format(msg) if not msg_str.endswith(end): msg_str += end # Attempt to detect if we are not running within a fully functional terminal. # Don't try to use the pager when being run by a continuous integration system like Jenkins + pexpect. functional_terminal = False if self.stdin.isatty() and self.stdout.isatty(): if sys.platform.startswith('win') or os.environ.get('TERM') is not None: functional_terminal = True # Don't attempt to use a pager that can block if redirecting or running a script (either text or Python) # Also only attempt to use a pager if actually running in a real fully functional terminal if functional_terminal and not self.redirecting and not self._in_py and not self._script_dir: if self.colors.lower() == constants.COLORS_NEVER.lower(): msg_str = utils.strip_ansi(msg_str) pager = self.pager if chop: pager = self.pager_chop # Prevent KeyboardInterrupts while in the pager. The pager application will # still receive the SIGINT since it is in the same process group as us. with self.sigint_protection: pipe_proc = subprocess.Popen(pager, shell=True, stdin=subprocess.PIPE) pipe_proc.communicate(msg_str.encode('utf-8', 'replace')) else: self.decolorized_write(self.stdout, msg_str) except BrokenPipeError: # This occurs if a command's output is being piped to another process and that process closes before the # command is finished. If you would like your application to print a warning message, then set the # broken_pipe_warning attribute to the message you want printed.` if self.broken_pipe_warning: sys.stderr.write(self.broken_pipe_warning)
[ "def", "ppaged", "(", "self", ",", "msg", ":", "str", ",", "end", ":", "str", "=", "'\\n'", ",", "chop", ":", "bool", "=", "False", ")", "->", "None", ":", "import", "subprocess", "if", "msg", "is", "not", "None", "and", "msg", "!=", "''", ":", ...
Print output using a pager if it would go off screen and stdout isn't currently being redirected. Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when stdout or stdin are not a fully functional terminal. :param msg: message to print to current stdout (anything convertible to a str with '{}'.format() is OK) :param end: string appended after the end of the message if not already present, default a newline :param chop: True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped - truncated text is still accessible by scrolling with the right & left arrow keys - chopping is ideal for displaying wide tabular data as is done in utilities like pgcli False -> causes lines longer than the screen width to wrap to the next line - wrapping is ideal when you want to keep users from having to use horizontal scrolling WARNING: On Windows, the text always wraps regardless of what the chop argument is set to
[ "Print", "output", "using", "a", "pager", "if", "it", "would", "go", "off", "screen", "and", "stdout", "isn", "t", "currently", "being", "redirected", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L655-L708
230,211
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.reset_completion_defaults
def reset_completion_defaults(self) -> None: """ Resets tab completion settings Needs to be called each time readline runs tab completion """ self.allow_appended_space = True self.allow_closing_quote = True self.completion_header = '' self.display_matches = [] self.matches_delimited = False self.matches_sorted = False if rl_type == RlType.GNU: readline.set_completion_display_matches_hook(self._display_matches_gnu_readline) elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode._display_completions = self._display_matches_pyreadline
python
def reset_completion_defaults(self) -> None: self.allow_appended_space = True self.allow_closing_quote = True self.completion_header = '' self.display_matches = [] self.matches_delimited = False self.matches_sorted = False if rl_type == RlType.GNU: readline.set_completion_display_matches_hook(self._display_matches_gnu_readline) elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode._display_completions = self._display_matches_pyreadline
[ "def", "reset_completion_defaults", "(", "self", ")", "->", "None", ":", "self", ".", "allow_appended_space", "=", "True", "self", ".", "allow_closing_quote", "=", "True", "self", ".", "completion_header", "=", "''", "self", ".", "display_matches", "=", "[", "...
Resets tab completion settings Needs to be called each time readline runs tab completion
[ "Resets", "tab", "completion", "settings", "Needs", "to", "be", "called", "each", "time", "readline", "runs", "tab", "completion" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L712-L728
230,212
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.basic_complete
def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]: """ Performs tab completion against a list :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line with leading whitespace removed :param begidx: the beginning index of the prefix text :param endidx: the ending index of the prefix text :param match_against: the list being matched against :return: a list of possible tab completions """ return [cur_match for cur_match in match_against if cur_match.startswith(text)]
python
def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]: return [cur_match for cur_match in match_against if cur_match.startswith(text)]
[ "def", "basic_complete", "(", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "match_against", ":", "Iterable", ")", "->", "List", "[", "str", "]", ":", "return", "[", "cur_match", "for", "cur_m...
Performs tab completion against a list :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line with leading whitespace removed :param begidx: the beginning index of the prefix text :param endidx: the ending index of the prefix text :param match_against: the list being matched against :return: a list of possible tab completions
[ "Performs", "tab", "completion", "against", "a", "list" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L851-L862
230,213
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.delimiter_complete
def delimiter_complete(self, text: str, line: str, begidx: int, endidx: int, match_against: Iterable, delimiter: str) -> List[str]: """ Performs tab completion against a list but each match is split on a delimiter and only the portion of the match being tab completed is shown as the completion suggestions. This is useful if you match against strings that are hierarchical in nature and have a common delimiter. An easy way to illustrate this concept is path completion since paths are just directories/files delimited by a slash. If you are tab completing items in /home/user you don't get the following as suggestions: /home/user/file.txt /home/user/program.c /home/user/maps/ /home/user/cmd2.py Instead you are shown: file.txt program.c maps/ cmd2.py For a large set of data, this can be visually more pleasing and easier to search. Another example would be strings formatted with the following syntax: company::department::name In this case the delimiter would be :: and the user could easily narrow down what they are looking for if they were only shown suggestions in the category they are at in the string. :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line with leading whitespace removed :param begidx: the beginning index of the prefix text :param endidx: the ending index of the prefix text :param match_against: the list being matched against :param delimiter: what delimits each portion of the matches (ex: paths are delimited by a slash) :return: a list of possible tab completions """ matches = self.basic_complete(text, line, begidx, endidx, match_against) # Display only the portion of the match that's being completed based on delimiter if matches: # Set this to True for proper quoting of matches with spaces self.matches_delimited = True # Get the common beginning for the matches common_prefix = os.path.commonprefix(matches) prefix_tokens = common_prefix.split(delimiter) # Calculate what portion of the match we are completing display_token_index = 0 if prefix_tokens: display_token_index = len(prefix_tokens) - 1 # Get this portion for each match and store them in self.display_matches for cur_match in matches: match_tokens = cur_match.split(delimiter) display_token = match_tokens[display_token_index] if not display_token: display_token = delimiter self.display_matches.append(display_token) return matches
python
def delimiter_complete(self, text: str, line: str, begidx: int, endidx: int, match_against: Iterable, delimiter: str) -> List[str]: matches = self.basic_complete(text, line, begidx, endidx, match_against) # Display only the portion of the match that's being completed based on delimiter if matches: # Set this to True for proper quoting of matches with spaces self.matches_delimited = True # Get the common beginning for the matches common_prefix = os.path.commonprefix(matches) prefix_tokens = common_prefix.split(delimiter) # Calculate what portion of the match we are completing display_token_index = 0 if prefix_tokens: display_token_index = len(prefix_tokens) - 1 # Get this portion for each match and store them in self.display_matches for cur_match in matches: match_tokens = cur_match.split(delimiter) display_token = match_tokens[display_token_index] if not display_token: display_token = delimiter self.display_matches.append(display_token) return matches
[ "def", "delimiter_complete", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "match_against", ":", "Iterable", ",", "delimiter", ":", "str", ")", "->", "List", "[", "str", "]",...
Performs tab completion against a list but each match is split on a delimiter and only the portion of the match being tab completed is shown as the completion suggestions. This is useful if you match against strings that are hierarchical in nature and have a common delimiter. An easy way to illustrate this concept is path completion since paths are just directories/files delimited by a slash. If you are tab completing items in /home/user you don't get the following as suggestions: /home/user/file.txt /home/user/program.c /home/user/maps/ /home/user/cmd2.py Instead you are shown: file.txt program.c maps/ cmd2.py For a large set of data, this can be visually more pleasing and easier to search. Another example would be strings formatted with the following syntax: company::department::name In this case the delimiter would be :: and the user could easily narrow down what they are looking for if they were only shown suggestions in the category they are at in the string. :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line with leading whitespace removed :param begidx: the beginning index of the prefix text :param endidx: the ending index of the prefix text :param match_against: the list being matched against :param delimiter: what delimits each portion of the matches (ex: paths are delimited by a slash) :return: a list of possible tab completions
[ "Performs", "tab", "completion", "against", "a", "list", "but", "each", "match", "is", "split", "on", "a", "delimiter", "and", "only", "the", "portion", "of", "the", "match", "being", "tab", "completed", "is", "shown", "as", "the", "completion", "suggestions...
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L864-L923
230,214
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.get_exes_in_path
def get_exes_in_path(starts_with: str) -> List[str]: """Returns names of executables in a user's path :param starts_with: what the exes should start with. leave blank for all exes in path. :return: a list of matching exe names """ # Purposely don't match any executable containing wildcards wildcards = ['*', '?'] for wildcard in wildcards: if wildcard in starts_with: return [] # Get a list of every directory in the PATH environment variable and ignore symbolic links paths = [p for p in os.getenv('PATH').split(os.path.pathsep) if not os.path.islink(p)] # Use a set to store exe names since there can be duplicates exes_set = set() # Find every executable file in the user's path that matches the pattern for path in paths: full_path = os.path.join(path, starts_with) matches = [f for f in glob.glob(full_path + '*') if os.path.isfile(f) and os.access(f, os.X_OK)] for match in matches: exes_set.add(os.path.basename(match)) return list(exes_set)
python
def get_exes_in_path(starts_with: str) -> List[str]: # Purposely don't match any executable containing wildcards wildcards = ['*', '?'] for wildcard in wildcards: if wildcard in starts_with: return [] # Get a list of every directory in the PATH environment variable and ignore symbolic links paths = [p for p in os.getenv('PATH').split(os.path.pathsep) if not os.path.islink(p)] # Use a set to store exe names since there can be duplicates exes_set = set() # Find every executable file in the user's path that matches the pattern for path in paths: full_path = os.path.join(path, starts_with) matches = [f for f in glob.glob(full_path + '*') if os.path.isfile(f) and os.access(f, os.X_OK)] for match in matches: exes_set.add(os.path.basename(match)) return list(exes_set)
[ "def", "get_exes_in_path", "(", "starts_with", ":", "str", ")", "->", "List", "[", "str", "]", ":", "# Purposely don't match any executable containing wildcards", "wildcards", "=", "[", "'*'", ",", "'?'", "]", "for", "wildcard", "in", "wildcards", ":", "if", "wi...
Returns names of executables in a user's path :param starts_with: what the exes should start with. leave blank for all exes in path. :return: a list of matching exe names
[ "Returns", "names", "of", "executables", "in", "a", "user", "s", "path" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1157-L1183
230,215
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._autocomplete_default
def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int, argparser: argparse.ArgumentParser) -> List[str]: """Default completion function for argparse commands.""" completer = AutoCompleter(argparser, self) tokens, _ = self.tokens_for_completion(line, begidx, endidx) if not tokens: return [] return completer.complete_command(tokens, text, line, begidx, endidx)
python
def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int, argparser: argparse.ArgumentParser) -> List[str]: completer = AutoCompleter(argparser, self) tokens, _ = self.tokens_for_completion(line, begidx, endidx) if not tokens: return [] return completer.complete_command(tokens, text, line, begidx, endidx)
[ "def", "_autocomplete_default", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "argparser", ":", "argparse", ".", "ArgumentParser", ")", "->", "List", "[", "str", "]", ":", "c...
Default completion function for argparse commands.
[ "Default", "completion", "function", "for", "argparse", "commands", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1584-L1593
230,216
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.get_all_commands
def get_all_commands(self) -> List[str]: """Returns a list of all commands.""" return [name[len(COMMAND_FUNC_PREFIX):] for name in self.get_names() if name.startswith(COMMAND_FUNC_PREFIX) and callable(getattr(self, name))]
python
def get_all_commands(self) -> List[str]: return [name[len(COMMAND_FUNC_PREFIX):] for name in self.get_names() if name.startswith(COMMAND_FUNC_PREFIX) and callable(getattr(self, name))]
[ "def", "get_all_commands", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "name", "[", "len", "(", "COMMAND_FUNC_PREFIX", ")", ":", "]", "for", "name", "in", "self", ".", "get_names", "(", ")", "if", "name", ".", "startswith", "...
Returns a list of all commands.
[ "Returns", "a", "list", "of", "all", "commands", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1595-L1598
230,217
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.get_visible_commands
def get_visible_commands(self) -> List[str]: """Returns a list of commands that have not been hidden or disabled.""" commands = self.get_all_commands() # Remove the hidden commands for name in self.hidden_commands: if name in commands: commands.remove(name) # Remove the disabled commands for name in self.disabled_commands: if name in commands: commands.remove(name) return commands
python
def get_visible_commands(self) -> List[str]: commands = self.get_all_commands() # Remove the hidden commands for name in self.hidden_commands: if name in commands: commands.remove(name) # Remove the disabled commands for name in self.disabled_commands: if name in commands: commands.remove(name) return commands
[ "def", "get_visible_commands", "(", "self", ")", "->", "List", "[", "str", "]", ":", "commands", "=", "self", ".", "get_all_commands", "(", ")", "# Remove the hidden commands", "for", "name", "in", "self", ".", "hidden_commands", ":", "if", "name", "in", "co...
Returns a list of commands that have not been hidden or disabled.
[ "Returns", "a", "list", "of", "commands", "that", "have", "not", "been", "hidden", "or", "disabled", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1600-L1614
230,218
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.get_commands_aliases_and_macros_for_completion
def get_commands_aliases_and_macros_for_completion(self) -> List[str]: """Return a list of visible commands, aliases, and macros for tab completion""" visible_commands = set(self.get_visible_commands()) alias_names = set(self.get_alias_names()) macro_names = set(self.get_macro_names()) return list(visible_commands | alias_names | macro_names)
python
def get_commands_aliases_and_macros_for_completion(self) -> List[str]: visible_commands = set(self.get_visible_commands()) alias_names = set(self.get_alias_names()) macro_names = set(self.get_macro_names()) return list(visible_commands | alias_names | macro_names)
[ "def", "get_commands_aliases_and_macros_for_completion", "(", "self", ")", "->", "List", "[", "str", "]", ":", "visible_commands", "=", "set", "(", "self", ".", "get_visible_commands", "(", ")", ")", "alias_names", "=", "set", "(", "self", ".", "get_alias_names"...
Return a list of visible commands, aliases, and macros for tab completion
[ "Return", "a", "list", "of", "visible", "commands", "aliases", "and", "macros", "for", "tab", "completion" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1628-L1633
230,219
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.get_help_topics
def get_help_topics(self) -> List[str]: """ Returns a list of help topics """ return [name[len(HELP_FUNC_PREFIX):] for name in self.get_names() if name.startswith(HELP_FUNC_PREFIX) and callable(getattr(self, name))]
python
def get_help_topics(self) -> List[str]: return [name[len(HELP_FUNC_PREFIX):] for name in self.get_names() if name.startswith(HELP_FUNC_PREFIX) and callable(getattr(self, name))]
[ "def", "get_help_topics", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "name", "[", "len", "(", "HELP_FUNC_PREFIX", ")", ":", "]", "for", "name", "in", "self", ".", "get_names", "(", ")", "if", "name", ".", "startswith", "(", ...
Returns a list of help topics
[ "Returns", "a", "list", "of", "help", "topics" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1635-L1638
230,220
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.sigint_handler
def sigint_handler(self, signum: int, frame) -> None: """Signal handler for SIGINTs which typically come from Ctrl-C events. If you need custom SIGINT behavior, then override this function. :param signum: signal number :param frame """ if self.cur_pipe_proc_reader is not None: # Pass the SIGINT to the current pipe process self.cur_pipe_proc_reader.send_sigint() # Check if we are allowed to re-raise the KeyboardInterrupt if not self.sigint_protection: raise KeyboardInterrupt("Got a keyboard interrupt")
python
def sigint_handler(self, signum: int, frame) -> None: if self.cur_pipe_proc_reader is not None: # Pass the SIGINT to the current pipe process self.cur_pipe_proc_reader.send_sigint() # Check if we are allowed to re-raise the KeyboardInterrupt if not self.sigint_protection: raise KeyboardInterrupt("Got a keyboard interrupt")
[ "def", "sigint_handler", "(", "self", ",", "signum", ":", "int", ",", "frame", ")", "->", "None", ":", "if", "self", ".", "cur_pipe_proc_reader", "is", "not", "None", ":", "# Pass the SIGINT to the current pipe process", "self", ".", "cur_pipe_proc_reader", ".", ...
Signal handler for SIGINTs which typically come from Ctrl-C events. If you need custom SIGINT behavior, then override this function. :param signum: signal number :param frame
[ "Signal", "handler", "for", "SIGINTs", "which", "typically", "come", "from", "Ctrl", "-", "C", "events", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1641-L1655
230,221
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.parseline
def parseline(self, line: str) -> Tuple[str, str, str]: """Parse the line into a command name and a string containing the arguments. NOTE: This is an override of a parent class method. It is only used by other parent class methods. Different from the parent class method, this ignores self.identchars. :param line: line read by readline :return: tuple containing (command, args, line) """ statement = self.statement_parser.parse_command_only(line) return statement.command, statement.args, statement.command_and_args
python
def parseline(self, line: str) -> Tuple[str, str, str]: statement = self.statement_parser.parse_command_only(line) return statement.command, statement.args, statement.command_and_args
[ "def", "parseline", "(", "self", ",", "line", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", ",", "str", "]", ":", "statement", "=", "self", ".", "statement_parser", ".", "parse_command_only", "(", "line", ")", "return", "statement", ".", "com...
Parse the line into a command name and a string containing the arguments. NOTE: This is an override of a parent class method. It is only used by other parent class methods. Different from the parent class method, this ignores self.identchars. :param line: line read by readline :return: tuple containing (command, args, line)
[ "Parse", "the", "line", "into", "a", "command", "name", "and", "a", "string", "containing", "the", "arguments", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1665-L1676
230,222
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._run_cmdfinalization_hooks
def _run_cmdfinalization_hooks(self, stop: bool, statement: Optional[Statement]) -> bool: """Run the command finalization hooks""" with self.sigint_protection: if not sys.platform.startswith('win') and self.stdout.isatty(): # Before the next command runs, fix any terminal problems like those # caused by certain binary characters having been printed to it. import subprocess proc = subprocess.Popen(['stty', 'sane']) proc.communicate() try: data = plugin.CommandFinalizationData(stop, statement) for func in self._cmdfinalization_hooks: data = func(data) # retrieve the final value of stop, ignoring any # modifications to the statement return data.stop except Exception as ex: self.perror(ex)
python
def _run_cmdfinalization_hooks(self, stop: bool, statement: Optional[Statement]) -> bool: with self.sigint_protection: if not sys.platform.startswith('win') and self.stdout.isatty(): # Before the next command runs, fix any terminal problems like those # caused by certain binary characters having been printed to it. import subprocess proc = subprocess.Popen(['stty', 'sane']) proc.communicate() try: data = plugin.CommandFinalizationData(stop, statement) for func in self._cmdfinalization_hooks: data = func(data) # retrieve the final value of stop, ignoring any # modifications to the statement return data.stop except Exception as ex: self.perror(ex)
[ "def", "_run_cmdfinalization_hooks", "(", "self", ",", "stop", ":", "bool", ",", "statement", ":", "Optional", "[", "Statement", "]", ")", "->", "bool", ":", "with", "self", ".", "sigint_protection", ":", "if", "not", "sys", ".", "platform", ".", "startswi...
Run the command finalization hooks
[ "Run", "the", "command", "finalization", "hooks" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1785-L1804
230,223
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.runcmds_plus_hooks
def runcmds_plus_hooks(self, cmds: List[str]) -> bool: """Convenience method to run multiple commands by onecmd_plus_hooks. This method adds the given cmds to the command queue and processes the queue until completion or an error causes it to abort. Scripts that are loaded will have their commands added to the queue. Scripts may even load other scripts recursively. This means, however, that you should not use this method if there is a running cmdloop or some other event-loop. This method is only intended to be used in "one-off" scenarios. NOTE: You may need this method even if you only have one command. If that command is a load, then you will need this command to fully process all the subsequent commands that are loaded from the script file. This is an improvement over onecmd_plus_hooks, which expects to be used inside of a command loop which does the processing of loaded commands. Example: cmd_obj.runcmds_plus_hooks(['load myscript.txt']) :param cmds: command strings suitable for onecmd_plus_hooks. :return: True implies the entire application should exit. """ stop = False self.cmdqueue = list(cmds) + self.cmdqueue try: while self.cmdqueue and not stop: line = self.cmdqueue.pop(0) if self.echo and line != 'eos': self.poutput('{}{}'.format(self.prompt, line)) stop = self.onecmd_plus_hooks(line) finally: # Clear out the command queue and script directory stack, just in # case we hit an error and they were not completed. self.cmdqueue = [] self._script_dir = [] # NOTE: placing this return here inside the finally block will # swallow exceptions. This is consistent with what is done in # onecmd_plus_hooks and _cmdloop, although it may not be # necessary/desired here. return stop
python
def runcmds_plus_hooks(self, cmds: List[str]) -> bool: stop = False self.cmdqueue = list(cmds) + self.cmdqueue try: while self.cmdqueue and not stop: line = self.cmdqueue.pop(0) if self.echo and line != 'eos': self.poutput('{}{}'.format(self.prompt, line)) stop = self.onecmd_plus_hooks(line) finally: # Clear out the command queue and script directory stack, just in # case we hit an error and they were not completed. self.cmdqueue = [] self._script_dir = [] # NOTE: placing this return here inside the finally block will # swallow exceptions. This is consistent with what is done in # onecmd_plus_hooks and _cmdloop, although it may not be # necessary/desired here. return stop
[ "def", "runcmds_plus_hooks", "(", "self", ",", "cmds", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "stop", "=", "False", "self", ".", "cmdqueue", "=", "list", "(", "cmds", ")", "+", "self", ".", "cmdqueue", "try", ":", "while", "self", "....
Convenience method to run multiple commands by onecmd_plus_hooks. This method adds the given cmds to the command queue and processes the queue until completion or an error causes it to abort. Scripts that are loaded will have their commands added to the queue. Scripts may even load other scripts recursively. This means, however, that you should not use this method if there is a running cmdloop or some other event-loop. This method is only intended to be used in "one-off" scenarios. NOTE: You may need this method even if you only have one command. If that command is a load, then you will need this command to fully process all the subsequent commands that are loaded from the script file. This is an improvement over onecmd_plus_hooks, which expects to be used inside of a command loop which does the processing of loaded commands. Example: cmd_obj.runcmds_plus_hooks(['load myscript.txt']) :param cmds: command strings suitable for onecmd_plus_hooks. :return: True implies the entire application should exit.
[ "Convenience", "method", "to", "run", "multiple", "commands", "by", "onecmd_plus_hooks", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1806-L1846
230,224
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._complete_statement
def _complete_statement(self, line: str) -> Statement: """Keep accepting lines of input until the command is complete. There is some pretty hacky code here to handle some quirks of self.pseudo_raw_input(). It returns a literal 'eof' if the input pipe runs out. We can't refactor it because we need to retain backwards compatibility with the standard library version of cmd. """ while True: try: statement = self.statement_parser.parse(line) if statement.multiline_command and statement.terminator: # we have a completed multiline command, we are done break if not statement.multiline_command: # it's not a multiline command, but we parsed it ok # so we are done break except ValueError: # we have unclosed quotation marks, lets parse only the command # and see if it's a multiline statement = self.statement_parser.parse_command_only(line) if not statement.multiline_command: # not a multiline command, so raise the exception raise # if we get here we must have: # - a multiline command with no terminator # - a multiline command with unclosed quotation marks try: self.at_continuation_prompt = True newline = self.pseudo_raw_input(self.continuation_prompt) if newline == 'eof': # they entered either a blank line, or we hit an EOF # for some other reason. Turn the literal 'eof' # into a blank line, which serves as a command # terminator newline = '\n' self.poutput(newline) line = '{}\n{}'.format(statement.raw, newline) except KeyboardInterrupt as ex: if self.quit_on_sigint: raise ex else: self.poutput('^C') statement = self.statement_parser.parse('') break finally: self.at_continuation_prompt = False if not statement.command: raise EmptyStatement() return statement
python
def _complete_statement(self, line: str) -> Statement: while True: try: statement = self.statement_parser.parse(line) if statement.multiline_command and statement.terminator: # we have a completed multiline command, we are done break if not statement.multiline_command: # it's not a multiline command, but we parsed it ok # so we are done break except ValueError: # we have unclosed quotation marks, lets parse only the command # and see if it's a multiline statement = self.statement_parser.parse_command_only(line) if not statement.multiline_command: # not a multiline command, so raise the exception raise # if we get here we must have: # - a multiline command with no terminator # - a multiline command with unclosed quotation marks try: self.at_continuation_prompt = True newline = self.pseudo_raw_input(self.continuation_prompt) if newline == 'eof': # they entered either a blank line, or we hit an EOF # for some other reason. Turn the literal 'eof' # into a blank line, which serves as a command # terminator newline = '\n' self.poutput(newline) line = '{}\n{}'.format(statement.raw, newline) except KeyboardInterrupt as ex: if self.quit_on_sigint: raise ex else: self.poutput('^C') statement = self.statement_parser.parse('') break finally: self.at_continuation_prompt = False if not statement.command: raise EmptyStatement() return statement
[ "def", "_complete_statement", "(", "self", ",", "line", ":", "str", ")", "->", "Statement", ":", "while", "True", ":", "try", ":", "statement", "=", "self", ".", "statement_parser", ".", "parse", "(", "line", ")", "if", "statement", ".", "multiline_command...
Keep accepting lines of input until the command is complete. There is some pretty hacky code here to handle some quirks of self.pseudo_raw_input(). It returns a literal 'eof' if the input pipe runs out. We can't refactor it because we need to retain backwards compatibility with the standard library version of cmd.
[ "Keep", "accepting", "lines", "of", "input", "until", "the", "command", "is", "complete", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1848-L1900
230,225
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._redirect_output
def _redirect_output(self, statement: Statement) -> Tuple[bool, utils.RedirectionSavedState]: """Handles output redirection for >, >>, and |. :param statement: a parsed statement from the user :return: A bool telling if an error occurred and a utils.RedirectionSavedState object """ import io import subprocess redir_error = False # Initialize the saved state saved_state = utils.RedirectionSavedState(self.stdout, sys.stdout, self.cur_pipe_proc_reader) if not self.allow_redirection: return redir_error, saved_state if statement.pipe_to: # Create a pipe with read and write sides read_fd, write_fd = os.pipe() # Open each side of the pipe subproc_stdin = io.open(read_fd, 'r') new_stdout = io.open(write_fd, 'w') # We want Popen to raise an exception if it fails to open the process. Thus we don't set shell to True. try: # Set options to not forward signals to the pipe process. If a Ctrl-C event occurs, # our sigint handler will forward it only to the most recent pipe process. This makes # sure pipe processes close in the right order (most recent first). if sys.platform == 'win32': creationflags = subprocess.CREATE_NEW_PROCESS_GROUP start_new_session = False else: creationflags = 0 start_new_session = True # For any stream that is a StdSim, we will use a pipe so we can capture its output proc = \ subprocess.Popen(statement.pipe_to, stdin=subproc_stdin, stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout, stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr, creationflags=creationflags, start_new_session=start_new_session) saved_state.redirecting = True saved_state.pipe_proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr) sys.stdout = self.stdout = new_stdout except Exception as ex: self.perror('Failed to open pipe because - {}'.format(ex), traceback_war=False) subproc_stdin.close() new_stdout.close() redir_error = True elif statement.output: import tempfile if (not statement.output_to) and (not self.can_clip): self.perror("Cannot redirect to paste buffer; install 'pyperclip' and re-run to enable", traceback_war=False) redir_error = True elif statement.output_to: # going to a file mode = 'w' # statement.output can only contain # REDIRECTION_APPEND or REDIRECTION_OUTPUT if statement.output == constants.REDIRECTION_APPEND: mode = 'a' try: new_stdout = open(statement.output_to, mode) saved_state.redirecting = True sys.stdout = self.stdout = new_stdout except OSError as ex: self.perror('Failed to redirect because - {}'.format(ex), traceback_war=False) redir_error = True else: # going to a paste buffer new_stdout = tempfile.TemporaryFile(mode="w+") saved_state.redirecting = True sys.stdout = self.stdout = new_stdout if statement.output == constants.REDIRECTION_APPEND: self.poutput(get_paste_buffer()) return redir_error, saved_state
python
def _redirect_output(self, statement: Statement) -> Tuple[bool, utils.RedirectionSavedState]: import io import subprocess redir_error = False # Initialize the saved state saved_state = utils.RedirectionSavedState(self.stdout, sys.stdout, self.cur_pipe_proc_reader) if not self.allow_redirection: return redir_error, saved_state if statement.pipe_to: # Create a pipe with read and write sides read_fd, write_fd = os.pipe() # Open each side of the pipe subproc_stdin = io.open(read_fd, 'r') new_stdout = io.open(write_fd, 'w') # We want Popen to raise an exception if it fails to open the process. Thus we don't set shell to True. try: # Set options to not forward signals to the pipe process. If a Ctrl-C event occurs, # our sigint handler will forward it only to the most recent pipe process. This makes # sure pipe processes close in the right order (most recent first). if sys.platform == 'win32': creationflags = subprocess.CREATE_NEW_PROCESS_GROUP start_new_session = False else: creationflags = 0 start_new_session = True # For any stream that is a StdSim, we will use a pipe so we can capture its output proc = \ subprocess.Popen(statement.pipe_to, stdin=subproc_stdin, stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout, stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr, creationflags=creationflags, start_new_session=start_new_session) saved_state.redirecting = True saved_state.pipe_proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr) sys.stdout = self.stdout = new_stdout except Exception as ex: self.perror('Failed to open pipe because - {}'.format(ex), traceback_war=False) subproc_stdin.close() new_stdout.close() redir_error = True elif statement.output: import tempfile if (not statement.output_to) and (not self.can_clip): self.perror("Cannot redirect to paste buffer; install 'pyperclip' and re-run to enable", traceback_war=False) redir_error = True elif statement.output_to: # going to a file mode = 'w' # statement.output can only contain # REDIRECTION_APPEND or REDIRECTION_OUTPUT if statement.output == constants.REDIRECTION_APPEND: mode = 'a' try: new_stdout = open(statement.output_to, mode) saved_state.redirecting = True sys.stdout = self.stdout = new_stdout except OSError as ex: self.perror('Failed to redirect because - {}'.format(ex), traceback_war=False) redir_error = True else: # going to a paste buffer new_stdout = tempfile.TemporaryFile(mode="w+") saved_state.redirecting = True sys.stdout = self.stdout = new_stdout if statement.output == constants.REDIRECTION_APPEND: self.poutput(get_paste_buffer()) return redir_error, saved_state
[ "def", "_redirect_output", "(", "self", ",", "statement", ":", "Statement", ")", "->", "Tuple", "[", "bool", ",", "utils", ".", "RedirectionSavedState", "]", ":", "import", "io", "import", "subprocess", "redir_error", "=", "False", "# Initialize the saved state", ...
Handles output redirection for >, >>, and |. :param statement: a parsed statement from the user :return: A bool telling if an error occurred and a utils.RedirectionSavedState object
[ "Handles", "output", "redirection", "for", ">", ">>", "and", "|", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1902-L1987
230,226
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._restore_output
def _restore_output(self, statement: Statement, saved_state: utils.RedirectionSavedState) -> None: """Handles restoring state after output redirection as well as the actual pipe operation if present. :param statement: Statement object which contains the parsed input from the user :param saved_state: contains information needed to restore state data """ if saved_state.redirecting: # If we redirected output to the clipboard if statement.output and not statement.output_to: self.stdout.seek(0) write_to_paste_buffer(self.stdout.read()) try: # Close the file or pipe that stdout was redirected to self.stdout.close() except BrokenPipeError: pass # Restore the stdout values self.stdout = saved_state.saved_self_stdout sys.stdout = saved_state.saved_sys_stdout # Check if we need to wait for the process being piped to if self.cur_pipe_proc_reader is not None: self.cur_pipe_proc_reader.wait() # Restore cur_pipe_proc_reader. This always is done, regardless of whether this command redirected. self.cur_pipe_proc_reader = saved_state.saved_pipe_proc_reader
python
def _restore_output(self, statement: Statement, saved_state: utils.RedirectionSavedState) -> None: if saved_state.redirecting: # If we redirected output to the clipboard if statement.output and not statement.output_to: self.stdout.seek(0) write_to_paste_buffer(self.stdout.read()) try: # Close the file or pipe that stdout was redirected to self.stdout.close() except BrokenPipeError: pass # Restore the stdout values self.stdout = saved_state.saved_self_stdout sys.stdout = saved_state.saved_sys_stdout # Check if we need to wait for the process being piped to if self.cur_pipe_proc_reader is not None: self.cur_pipe_proc_reader.wait() # Restore cur_pipe_proc_reader. This always is done, regardless of whether this command redirected. self.cur_pipe_proc_reader = saved_state.saved_pipe_proc_reader
[ "def", "_restore_output", "(", "self", ",", "statement", ":", "Statement", ",", "saved_state", ":", "utils", ".", "RedirectionSavedState", ")", "->", "None", ":", "if", "saved_state", ".", "redirecting", ":", "# If we redirected output to the clipboard", "if", "stat...
Handles restoring state after output redirection as well as the actual pipe operation if present. :param statement: Statement object which contains the parsed input from the user :param saved_state: contains information needed to restore state data
[ "Handles", "restoring", "state", "after", "output", "redirection", "as", "well", "as", "the", "actual", "pipe", "operation", "if", "present", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L1989-L2017
230,227
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.cmd_func_name
def cmd_func_name(self, command: str) -> str: """Get the method name associated with a given command. :param command: command to look up method name which implements it :return: method name which implements the given command """ target = COMMAND_FUNC_PREFIX + command return target if callable(getattr(self, target, None)) else ''
python
def cmd_func_name(self, command: str) -> str: target = COMMAND_FUNC_PREFIX + command return target if callable(getattr(self, target, None)) else ''
[ "def", "cmd_func_name", "(", "self", ",", "command", ":", "str", ")", "->", "str", ":", "target", "=", "COMMAND_FUNC_PREFIX", "+", "command", "return", "target", "if", "callable", "(", "getattr", "(", "self", ",", "target", ",", "None", ")", ")", "else",...
Get the method name associated with a given command. :param command: command to look up method name which implements it :return: method name which implements the given command
[ "Get", "the", "method", "name", "associated", "with", "a", "given", "command", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2028-L2035
230,228
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._run_macro
def _run_macro(self, statement: Statement) -> bool: """ Resolve a macro and run the resulting string :param statement: the parsed statement from the command line :return: a flag indicating whether the interpretation of commands should stop """ from itertools import islice if statement.command not in self.macros.keys(): raise KeyError('{} is not a macro'.format(statement.command)) macro = self.macros[statement.command] # Make sure enough arguments were passed in if len(statement.arg_list) < macro.minimum_arg_count: self.perror("The macro '{}' expects at least {} argument(s)".format(statement.command, macro.minimum_arg_count), traceback_war=False) return False # Resolve the arguments in reverse and read their values from statement.argv since those # are unquoted. Macro args should have been quoted when the macro was created. resolved = macro.value reverse_arg_list = sorted(macro.arg_list, key=lambda ma: ma.start_index, reverse=True) for arg in reverse_arg_list: if arg.is_escaped: to_replace = '{{' + arg.number_str + '}}' replacement = '{' + arg.number_str + '}' else: to_replace = '{' + arg.number_str + '}' replacement = statement.argv[int(arg.number_str)] parts = resolved.rsplit(to_replace, maxsplit=1) resolved = parts[0] + replacement + parts[1] # Append extra arguments and use statement.arg_list since these arguments need their quotes preserved for arg in islice(statement.arg_list, macro.minimum_arg_count, None): resolved += ' ' + arg # Run the resolved command return self.onecmd_plus_hooks(resolved)
python
def _run_macro(self, statement: Statement) -> bool: from itertools import islice if statement.command not in self.macros.keys(): raise KeyError('{} is not a macro'.format(statement.command)) macro = self.macros[statement.command] # Make sure enough arguments were passed in if len(statement.arg_list) < macro.minimum_arg_count: self.perror("The macro '{}' expects at least {} argument(s)".format(statement.command, macro.minimum_arg_count), traceback_war=False) return False # Resolve the arguments in reverse and read their values from statement.argv since those # are unquoted. Macro args should have been quoted when the macro was created. resolved = macro.value reverse_arg_list = sorted(macro.arg_list, key=lambda ma: ma.start_index, reverse=True) for arg in reverse_arg_list: if arg.is_escaped: to_replace = '{{' + arg.number_str + '}}' replacement = '{' + arg.number_str + '}' else: to_replace = '{' + arg.number_str + '}' replacement = statement.argv[int(arg.number_str)] parts = resolved.rsplit(to_replace, maxsplit=1) resolved = parts[0] + replacement + parts[1] # Append extra arguments and use statement.arg_list since these arguments need their quotes preserved for arg in islice(statement.arg_list, macro.minimum_arg_count, None): resolved += ' ' + arg # Run the resolved command return self.onecmd_plus_hooks(resolved)
[ "def", "_run_macro", "(", "self", ",", "statement", ":", "Statement", ")", "->", "bool", ":", "from", "itertools", "import", "islice", "if", "statement", ".", "command", "not", "in", "self", ".", "macros", ".", "keys", "(", ")", ":", "raise", "KeyError",...
Resolve a macro and run the resulting string :param statement: the parsed statement from the command line :return: a flag indicating whether the interpretation of commands should stop
[ "Resolve", "a", "macro", "and", "run", "the", "resulting", "string" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2071-L2113
230,229
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.pseudo_raw_input
def pseudo_raw_input(self, prompt: str) -> str: """Began life as a copy of cmd's cmdloop; like raw_input but - accounts for changed stdin, stdout - if input is a pipe (instead of a tty), look at self.echo to decide whether to print the prompt and the input """ if self.use_rawinput: try: if sys.stdin.isatty(): # Wrap in try since terminal_lock may not be locked when this function is called from unit tests try: # A prompt is about to be drawn. Allow asynchronous changes to the terminal. self.terminal_lock.release() except RuntimeError: pass # Deal with the vagaries of readline and ANSI escape codes safe_prompt = rl_make_safe_prompt(prompt) line = input(safe_prompt) else: line = input() if self.echo: sys.stdout.write('{}{}\n'.format(prompt, line)) except EOFError: line = 'eof' finally: if sys.stdin.isatty(): # The prompt is gone. Do not allow asynchronous changes to the terminal. self.terminal_lock.acquire() else: if self.stdin.isatty(): # on a tty, print the prompt first, then read the line self.poutput(prompt, end='') self.stdout.flush() line = self.stdin.readline() if len(line) == 0: line = 'eof' else: # we are reading from a pipe, read the line to see if there is # anything there, if so, then decide whether to print the # prompt or not line = self.stdin.readline() if len(line): # we read something, output the prompt and the something if self.echo: self.poutput('{}{}'.format(prompt, line)) else: line = 'eof' return line.strip()
python
def pseudo_raw_input(self, prompt: str) -> str: if self.use_rawinput: try: if sys.stdin.isatty(): # Wrap in try since terminal_lock may not be locked when this function is called from unit tests try: # A prompt is about to be drawn. Allow asynchronous changes to the terminal. self.terminal_lock.release() except RuntimeError: pass # Deal with the vagaries of readline and ANSI escape codes safe_prompt = rl_make_safe_prompt(prompt) line = input(safe_prompt) else: line = input() if self.echo: sys.stdout.write('{}{}\n'.format(prompt, line)) except EOFError: line = 'eof' finally: if sys.stdin.isatty(): # The prompt is gone. Do not allow asynchronous changes to the terminal. self.terminal_lock.acquire() else: if self.stdin.isatty(): # on a tty, print the prompt first, then read the line self.poutput(prompt, end='') self.stdout.flush() line = self.stdin.readline() if len(line) == 0: line = 'eof' else: # we are reading from a pipe, read the line to see if there is # anything there, if so, then decide whether to print the # prompt or not line = self.stdin.readline() if len(line): # we read something, output the prompt and the something if self.echo: self.poutput('{}{}'.format(prompt, line)) else: line = 'eof' return line.strip()
[ "def", "pseudo_raw_input", "(", "self", ",", "prompt", ":", "str", ")", "->", "str", ":", "if", "self", ".", "use_rawinput", ":", "try", ":", "if", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "# Wrap in try since terminal_lock may not be locked when thi...
Began life as a copy of cmd's cmdloop; like raw_input but - accounts for changed stdin, stdout - if input is a pipe (instead of a tty), look at self.echo to decide whether to print the prompt and the input
[ "Began", "life", "as", "a", "copy", "of", "cmd", "s", "cmdloop", ";", "like", "raw_input", "but" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2129-L2179
230,230
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._cmdloop
def _cmdloop(self) -> bool: """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. This serves the same role as cmd.cmdloop(). :return: True implies the entire application should exit. """ # An almost perfect copy from Cmd; however, the pseudo_raw_input portion # has been split out so that it can be called separately if self.use_rawinput and self.completekey and rl_type != RlType.NONE: # Set up readline for our tab completion needs if rl_type == RlType.GNU: # Set GNU readline's rl_basic_quote_characters to NULL so it won't automatically add a closing quote # We don't need to worry about setting rl_completion_suppress_quote since we never declared # rl_completer_quote_characters. saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value rl_basic_quote_characters.value = None saved_completer = readline.get_completer() readline.set_completer(self.complete) # Break words on whitespace and quotes when tab completing completer_delims = " \t\n" + ''.join(constants.QUOTES) if self.allow_redirection: # If redirection is allowed, then break words on those characters too completer_delims += ''.join(constants.REDIRECTION_CHARS) saved_delims = readline.get_completer_delims() readline.set_completer_delims(completer_delims) # Enable tab completion readline.parse_and_bind(self.completekey + ": complete") stop = False try: while not stop: if self.cmdqueue: # Run command out of cmdqueue if nonempty (populated by load command or commands at invocation) line = self.cmdqueue.pop(0) if self.echo and line != 'eos': self.poutput('{}{}'.format(self.prompt, line)) else: # Otherwise, read a command from stdin try: line = self.pseudo_raw_input(self.prompt) except KeyboardInterrupt as ex: if self.quit_on_sigint: raise ex else: self.poutput('^C') line = '' # Run the command along with all associated pre and post hooks stop = self.onecmd_plus_hooks(line) finally: if self.use_rawinput and self.completekey and rl_type != RlType.NONE: # Restore what we changed in readline readline.set_completer(saved_completer) readline.set_completer_delims(saved_delims) if rl_type == RlType.GNU: readline.set_completion_display_matches_hook(None) rl_basic_quote_characters.value = saved_basic_quotes elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode._display_completions = orig_pyreadline_display self.cmdqueue.clear() self._script_dir.clear() return stop
python
def _cmdloop(self) -> bool: # An almost perfect copy from Cmd; however, the pseudo_raw_input portion # has been split out so that it can be called separately if self.use_rawinput and self.completekey and rl_type != RlType.NONE: # Set up readline for our tab completion needs if rl_type == RlType.GNU: # Set GNU readline's rl_basic_quote_characters to NULL so it won't automatically add a closing quote # We don't need to worry about setting rl_completion_suppress_quote since we never declared # rl_completer_quote_characters. saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value rl_basic_quote_characters.value = None saved_completer = readline.get_completer() readline.set_completer(self.complete) # Break words on whitespace and quotes when tab completing completer_delims = " \t\n" + ''.join(constants.QUOTES) if self.allow_redirection: # If redirection is allowed, then break words on those characters too completer_delims += ''.join(constants.REDIRECTION_CHARS) saved_delims = readline.get_completer_delims() readline.set_completer_delims(completer_delims) # Enable tab completion readline.parse_and_bind(self.completekey + ": complete") stop = False try: while not stop: if self.cmdqueue: # Run command out of cmdqueue if nonempty (populated by load command or commands at invocation) line = self.cmdqueue.pop(0) if self.echo and line != 'eos': self.poutput('{}{}'.format(self.prompt, line)) else: # Otherwise, read a command from stdin try: line = self.pseudo_raw_input(self.prompt) except KeyboardInterrupt as ex: if self.quit_on_sigint: raise ex else: self.poutput('^C') line = '' # Run the command along with all associated pre and post hooks stop = self.onecmd_plus_hooks(line) finally: if self.use_rawinput and self.completekey and rl_type != RlType.NONE: # Restore what we changed in readline readline.set_completer(saved_completer) readline.set_completer_delims(saved_delims) if rl_type == RlType.GNU: readline.set_completion_display_matches_hook(None) rl_basic_quote_characters.value = saved_basic_quotes elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode._display_completions = orig_pyreadline_display self.cmdqueue.clear() self._script_dir.clear() return stop
[ "def", "_cmdloop", "(", "self", ")", "->", "bool", ":", "# An almost perfect copy from Cmd; however, the pseudo_raw_input portion", "# has been split out so that it can be called separately", "if", "self", ".", "use_rawinput", "and", "self", ".", "completekey", "and", "rl_type"...
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. This serves the same role as cmd.cmdloop(). :return: True implies the entire application should exit.
[ "Repeatedly", "issue", "a", "prompt", "accept", "input", "parse", "an", "initial", "prefix", "off", "the", "received", "input", "and", "dispatch", "to", "action", "methods", "passing", "them", "the", "remainder", "of", "the", "line", "as", "argument", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2181-L2257
230,231
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.alias_create
def alias_create(self, args: argparse.Namespace) -> None: """Create or overwrite an alias""" # Validate the alias name valid, errmsg = self.statement_parser.is_valid_command(args.name) if not valid: self.perror("Invalid alias name: {}".format(errmsg), traceback_war=False) return if args.name in self.macros: self.perror("Alias cannot have the same name as a macro", traceback_war=False) return utils.unquote_redirection_tokens(args.command_args) # Build the alias value string value = args.command if args.command_args: value += ' ' + ' '.join(args.command_args) # Set the alias result = "overwritten" if args.name in self.aliases else "created" self.aliases[args.name] = value self.poutput("Alias '{}' {}".format(args.name, result))
python
def alias_create(self, args: argparse.Namespace) -> None: # Validate the alias name valid, errmsg = self.statement_parser.is_valid_command(args.name) if not valid: self.perror("Invalid alias name: {}".format(errmsg), traceback_war=False) return if args.name in self.macros: self.perror("Alias cannot have the same name as a macro", traceback_war=False) return utils.unquote_redirection_tokens(args.command_args) # Build the alias value string value = args.command if args.command_args: value += ' ' + ' '.join(args.command_args) # Set the alias result = "overwritten" if args.name in self.aliases else "created" self.aliases[args.name] = value self.poutput("Alias '{}' {}".format(args.name, result))
[ "def", "alias_create", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "# Validate the alias name", "valid", ",", "errmsg", "=", "self", ".", "statement_parser", ".", "is_valid_command", "(", "args", ".", "name", ")", "if...
Create or overwrite an alias
[ "Create", "or", "overwrite", "an", "alias" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2261-L2284
230,232
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.alias_list
def alias_list(self, args: argparse.Namespace) -> None: """List some or all aliases""" if args.name: for cur_name in utils.remove_duplicates(args.name): if cur_name in self.aliases: self.poutput("alias create {} {}".format(cur_name, self.aliases[cur_name])) else: self.perror("Alias '{}' not found".format(cur_name), traceback_war=False) else: sorted_aliases = utils.alphabetical_sort(self.aliases) for cur_alias in sorted_aliases: self.poutput("alias create {} {}".format(cur_alias, self.aliases[cur_alias]))
python
def alias_list(self, args: argparse.Namespace) -> None: if args.name: for cur_name in utils.remove_duplicates(args.name): if cur_name in self.aliases: self.poutput("alias create {} {}".format(cur_name, self.aliases[cur_name])) else: self.perror("Alias '{}' not found".format(cur_name), traceback_war=False) else: sorted_aliases = utils.alphabetical_sort(self.aliases) for cur_alias in sorted_aliases: self.poutput("alias create {} {}".format(cur_alias, self.aliases[cur_alias]))
[ "def", "alias_list", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "if", "args", ".", "name", ":", "for", "cur_name", "in", "utils", ".", "remove_duplicates", "(", "args", ".", "name", ")", ":", "if", "cur_name", ...
List some or all aliases
[ "List", "some", "or", "all", "aliases" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2301-L2312
230,233
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.macro_create
def macro_create(self, args: argparse.Namespace) -> None: """Create or overwrite a macro""" # Validate the macro name valid, errmsg = self.statement_parser.is_valid_command(args.name) if not valid: self.perror("Invalid macro name: {}".format(errmsg), traceback_war=False) return if args.name in self.get_all_commands(): self.perror("Macro cannot have the same name as a command", traceback_war=False) return if args.name in self.aliases: self.perror("Macro cannot have the same name as an alias", traceback_war=False) return utils.unquote_redirection_tokens(args.command_args) # Build the macro value string value = args.command if args.command_args: value += ' ' + ' '.join(args.command_args) # Find all normal arguments arg_list = [] normal_matches = re.finditer(MacroArg.macro_normal_arg_pattern, value) max_arg_num = 0 arg_nums = set() while True: try: cur_match = normal_matches.__next__() # Get the number string between the braces cur_num_str = (re.findall(MacroArg.digit_pattern, cur_match.group())[0]) cur_num = int(cur_num_str) if cur_num < 1: self.perror("Argument numbers must be greater than 0", traceback_war=False) return arg_nums.add(cur_num) if cur_num > max_arg_num: max_arg_num = cur_num arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=False)) except StopIteration: break # Make sure the argument numbers are continuous if len(arg_nums) != max_arg_num: self.perror("Not all numbers between 1 and {} are present " "in the argument placeholders".format(max_arg_num), traceback_war=False) return # Find all escaped arguments escaped_matches = re.finditer(MacroArg.macro_escaped_arg_pattern, value) while True: try: cur_match = escaped_matches.__next__() # Get the number string between the braces cur_num_str = re.findall(MacroArg.digit_pattern, cur_match.group())[0] arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=True)) except StopIteration: break # Set the macro result = "overwritten" if args.name in self.macros else "created" self.macros[args.name] = Macro(name=args.name, value=value, minimum_arg_count=max_arg_num, arg_list=arg_list) self.poutput("Macro '{}' {}".format(args.name, result))
python
def macro_create(self, args: argparse.Namespace) -> None: # Validate the macro name valid, errmsg = self.statement_parser.is_valid_command(args.name) if not valid: self.perror("Invalid macro name: {}".format(errmsg), traceback_war=False) return if args.name in self.get_all_commands(): self.perror("Macro cannot have the same name as a command", traceback_war=False) return if args.name in self.aliases: self.perror("Macro cannot have the same name as an alias", traceback_war=False) return utils.unquote_redirection_tokens(args.command_args) # Build the macro value string value = args.command if args.command_args: value += ' ' + ' '.join(args.command_args) # Find all normal arguments arg_list = [] normal_matches = re.finditer(MacroArg.macro_normal_arg_pattern, value) max_arg_num = 0 arg_nums = set() while True: try: cur_match = normal_matches.__next__() # Get the number string between the braces cur_num_str = (re.findall(MacroArg.digit_pattern, cur_match.group())[0]) cur_num = int(cur_num_str) if cur_num < 1: self.perror("Argument numbers must be greater than 0", traceback_war=False) return arg_nums.add(cur_num) if cur_num > max_arg_num: max_arg_num = cur_num arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=False)) except StopIteration: break # Make sure the argument numbers are continuous if len(arg_nums) != max_arg_num: self.perror("Not all numbers between 1 and {} are present " "in the argument placeholders".format(max_arg_num), traceback_war=False) return # Find all escaped arguments escaped_matches = re.finditer(MacroArg.macro_escaped_arg_pattern, value) while True: try: cur_match = escaped_matches.__next__() # Get the number string between the braces cur_num_str = re.findall(MacroArg.digit_pattern, cur_match.group())[0] arg_list.append(MacroArg(start_index=cur_match.start(), number_str=cur_num_str, is_escaped=True)) except StopIteration: break # Set the macro result = "overwritten" if args.name in self.macros else "created" self.macros[args.name] = Macro(name=args.name, value=value, minimum_arg_count=max_arg_num, arg_list=arg_list) self.poutput("Macro '{}' {}".format(args.name, result))
[ "def", "macro_create", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "# Validate the macro name", "valid", ",", "errmsg", "=", "self", ".", "statement_parser", ".", "is_valid_command", "(", "args", ".", "name", ")", "if...
Create or overwrite a macro
[ "Create", "or", "overwrite", "a", "macro" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2389-L2462
230,234
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.macro_list
def macro_list(self, args: argparse.Namespace) -> None: """List some or all macros""" if args.name: for cur_name in utils.remove_duplicates(args.name): if cur_name in self.macros: self.poutput("macro create {} {}".format(cur_name, self.macros[cur_name].value)) else: self.perror("Macro '{}' not found".format(cur_name), traceback_war=False) else: sorted_macros = utils.alphabetical_sort(self.macros) for cur_macro in sorted_macros: self.poutput("macro create {} {}".format(cur_macro, self.macros[cur_macro].value))
python
def macro_list(self, args: argparse.Namespace) -> None: if args.name: for cur_name in utils.remove_duplicates(args.name): if cur_name in self.macros: self.poutput("macro create {} {}".format(cur_name, self.macros[cur_name].value)) else: self.perror("Macro '{}' not found".format(cur_name), traceback_war=False) else: sorted_macros = utils.alphabetical_sort(self.macros) for cur_macro in sorted_macros: self.poutput("macro create {} {}".format(cur_macro, self.macros[cur_macro].value))
[ "def", "macro_list", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "if", "args", ".", "name", ":", "for", "cur_name", "in", "utils", ".", "remove_duplicates", "(", "args", ".", "name", ")", ":", "if", "cur_name", ...
List some or all macros
[ "List", "some", "or", "all", "macros" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2479-L2490
230,235
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.complete_help_command
def complete_help_command(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: """Completes the command argument of help""" # Complete token against topics and visible commands topics = set(self.get_help_topics()) visible_commands = set(self.get_visible_commands()) strs_to_match = list(topics | visible_commands) return self.basic_complete(text, line, begidx, endidx, strs_to_match)
python
def complete_help_command(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: # Complete token against topics and visible commands topics = set(self.get_help_topics()) visible_commands = set(self.get_visible_commands()) strs_to_match = list(topics | visible_commands) return self.basic_complete(text, line, begidx, endidx, strs_to_match)
[ "def", "complete_help_command", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ")", "->", "List", "[", "str", "]", ":", "# Complete token against topics and visible commands", "topics", "=...
Completes the command argument of help
[ "Completes", "the", "command", "argument", "of", "help" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2590-L2597
230,236
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.complete_help_subcommand
def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: """Completes the subcommand argument of help""" # Get all tokens through the one being completed tokens, _ = self.tokens_for_completion(line, begidx, endidx) if not tokens: return [] # Must have at least 3 args for 'help command sub-command' if len(tokens) < 3: return [] # Find where the command is by skipping past any flags cmd_index = 1 for cur_token in tokens[cmd_index:]: if not cur_token.startswith('-'): break cmd_index += 1 if cmd_index >= len(tokens): return [] command = tokens[cmd_index] matches = [] # Check if this is a command with an argparse function func = self.cmd_func(command) if func and hasattr(func, 'argparser'): completer = AutoCompleter(getattr(func, 'argparser'), self) matches = completer.complete_command_help(tokens[cmd_index:], text, line, begidx, endidx) return matches
python
def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: # Get all tokens through the one being completed tokens, _ = self.tokens_for_completion(line, begidx, endidx) if not tokens: return [] # Must have at least 3 args for 'help command sub-command' if len(tokens) < 3: return [] # Find where the command is by skipping past any flags cmd_index = 1 for cur_token in tokens[cmd_index:]: if not cur_token.startswith('-'): break cmd_index += 1 if cmd_index >= len(tokens): return [] command = tokens[cmd_index] matches = [] # Check if this is a command with an argparse function func = self.cmd_func(command) if func and hasattr(func, 'argparser'): completer = AutoCompleter(getattr(func, 'argparser'), self) matches = completer.complete_command_help(tokens[cmd_index:], text, line, begidx, endidx) return matches
[ "def", "complete_help_subcommand", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ")", "->", "List", "[", "str", "]", ":", "# Get all tokens through the one being completed", "tokens", ","...
Completes the subcommand argument of help
[ "Completes", "the", "subcommand", "argument", "of", "help" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2599-L2631
230,237
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_help
def do_help(self, args: argparse.Namespace) -> None: """List available commands or provide detailed help for a specific command""" if not args.command or args.verbose: self._help_menu(args.verbose) else: # Getting help for a specific command func = self.cmd_func(args.command) help_func = getattr(self, HELP_FUNC_PREFIX + args.command, None) # If the command function uses argparse, then use argparse's help if func and hasattr(func, 'argparser'): completer = AutoCompleter(getattr(func, 'argparser'), self) tokens = [args.command] + args.subcommand self.poutput(completer.format_help(tokens)) # If there is no help information then print an error elif help_func is None and (func is None or not func.__doc__): err_msg = self.help_error.format(args.command) self.decolorized_write(sys.stderr, "{}\n".format(err_msg)) # Otherwise delegate to cmd base class do_help() else: super().do_help(args.command)
python
def do_help(self, args: argparse.Namespace) -> None: if not args.command or args.verbose: self._help_menu(args.verbose) else: # Getting help for a specific command func = self.cmd_func(args.command) help_func = getattr(self, HELP_FUNC_PREFIX + args.command, None) # If the command function uses argparse, then use argparse's help if func and hasattr(func, 'argparser'): completer = AutoCompleter(getattr(func, 'argparser'), self) tokens = [args.command] + args.subcommand self.poutput(completer.format_help(tokens)) # If there is no help information then print an error elif help_func is None and (func is None or not func.__doc__): err_msg = self.help_error.format(args.command) self.decolorized_write(sys.stderr, "{}\n".format(err_msg)) # Otherwise delegate to cmd base class do_help() else: super().do_help(args.command)
[ "def", "do_help", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "if", "not", "args", ".", "command", "or", "args", ".", "verbose", ":", "self", ".", "_help_menu", "(", "args", ".", "verbose", ")", "else", ":", ...
List available commands or provide detailed help for a specific command
[ "List", "available", "commands", "or", "provide", "detailed", "help", "for", "a", "specific", "command" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2648-L2671
230,238
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._help_menu
def _help_menu(self, verbose: bool = False) -> None: """Show a list of commands which help can be displayed for. """ # Get a sorted list of help topics help_topics = utils.alphabetical_sort(self.get_help_topics()) # Get a sorted list of visible command names visible_commands = utils.alphabetical_sort(self.get_visible_commands()) cmds_doc = [] cmds_undoc = [] cmds_cats = {} for command in visible_commands: func = self.cmd_func(command) has_help_func = False if command in help_topics: # Prevent the command from showing as both a command and help topic in the output help_topics.remove(command) # Non-argparse commands can have help_functions for their documentation if not hasattr(func, 'argparser'): has_help_func = True if hasattr(func, HELP_CATEGORY): category = getattr(func, HELP_CATEGORY) cmds_cats.setdefault(category, []) cmds_cats[category].append(command) elif func.__doc__ or has_help_func: cmds_doc.append(command) else: cmds_undoc.append(command) if len(cmds_cats) == 0: # No categories found, fall back to standard behavior self.poutput("{}\n".format(str(self.doc_leader))) self._print_topics(self.doc_header, cmds_doc, verbose) else: # Categories found, Organize all commands by category self.poutput('{}\n'.format(str(self.doc_leader))) self.poutput('{}\n\n'.format(str(self.doc_header))) for category in sorted(cmds_cats.keys()): self._print_topics(category, cmds_cats[category], verbose) self._print_topics('Other', cmds_doc, verbose) self.print_topics(self.misc_header, help_topics, 15, 80) self.print_topics(self.undoc_header, cmds_undoc, 15, 80)
python
def _help_menu(self, verbose: bool = False) -> None: # Get a sorted list of help topics help_topics = utils.alphabetical_sort(self.get_help_topics()) # Get a sorted list of visible command names visible_commands = utils.alphabetical_sort(self.get_visible_commands()) cmds_doc = [] cmds_undoc = [] cmds_cats = {} for command in visible_commands: func = self.cmd_func(command) has_help_func = False if command in help_topics: # Prevent the command from showing as both a command and help topic in the output help_topics.remove(command) # Non-argparse commands can have help_functions for their documentation if not hasattr(func, 'argparser'): has_help_func = True if hasattr(func, HELP_CATEGORY): category = getattr(func, HELP_CATEGORY) cmds_cats.setdefault(category, []) cmds_cats[category].append(command) elif func.__doc__ or has_help_func: cmds_doc.append(command) else: cmds_undoc.append(command) if len(cmds_cats) == 0: # No categories found, fall back to standard behavior self.poutput("{}\n".format(str(self.doc_leader))) self._print_topics(self.doc_header, cmds_doc, verbose) else: # Categories found, Organize all commands by category self.poutput('{}\n'.format(str(self.doc_leader))) self.poutput('{}\n\n'.format(str(self.doc_header))) for category in sorted(cmds_cats.keys()): self._print_topics(category, cmds_cats[category], verbose) self._print_topics('Other', cmds_doc, verbose) self.print_topics(self.misc_header, help_topics, 15, 80) self.print_topics(self.undoc_header, cmds_undoc, 15, 80)
[ "def", "_help_menu", "(", "self", ",", "verbose", ":", "bool", "=", "False", ")", "->", "None", ":", "# Get a sorted list of help topics", "help_topics", "=", "utils", ".", "alphabetical_sort", "(", "self", ".", "get_help_topics", "(", ")", ")", "# Get a sorted ...
Show a list of commands which help can be displayed for.
[ "Show", "a", "list", "of", "commands", "which", "help", "can", "be", "displayed", "for", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2673-L2720
230,239
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._print_topics
def _print_topics(self, header: str, cmds: List[str], verbose: bool) -> None: """Customized version of print_topics that can switch between verbose or traditional output""" import io if cmds: if not verbose: self.print_topics(header, cmds, 15, 80) else: self.stdout.write('{}\n'.format(str(header))) widest = 0 # measure the commands for command in cmds: width = utils.ansi_safe_wcswidth(command) if width > widest: widest = width # add a 4-space pad widest += 4 if widest < 20: widest = 20 if self.ruler: self.stdout.write('{:{ruler}<{width}}\n'.format('', ruler=self.ruler, width=80)) # Try to get the documentation string for each command topics = self.get_help_topics() for command in cmds: cmd_func = self.cmd_func(command) # Non-argparse commands can have help_functions for their documentation if not hasattr(cmd_func, 'argparser') and command in topics: help_func = getattr(self, HELP_FUNC_PREFIX + command) result = io.StringIO() # try to redirect system stdout with redirect_stdout(result): # save our internal stdout stdout_orig = self.stdout try: # redirect our internal stdout self.stdout = result help_func() finally: # restore internal stdout self.stdout = stdout_orig doc = result.getvalue() else: doc = cmd_func.__doc__ # Attempt to locate the first documentation block if not doc: doc_block = [''] else: doc_block = [] found_first = False for doc_line in doc.splitlines(): stripped_line = doc_line.strip() # Don't include :param type lines if stripped_line.startswith(':'): if found_first: break elif stripped_line: doc_block.append(stripped_line) found_first = True elif found_first: break for doc_line in doc_block: self.stdout.write('{: <{col_width}}{doc}\n'.format(command, col_width=widest, doc=doc_line)) command = '' self.stdout.write("\n")
python
def _print_topics(self, header: str, cmds: List[str], verbose: bool) -> None: import io if cmds: if not verbose: self.print_topics(header, cmds, 15, 80) else: self.stdout.write('{}\n'.format(str(header))) widest = 0 # measure the commands for command in cmds: width = utils.ansi_safe_wcswidth(command) if width > widest: widest = width # add a 4-space pad widest += 4 if widest < 20: widest = 20 if self.ruler: self.stdout.write('{:{ruler}<{width}}\n'.format('', ruler=self.ruler, width=80)) # Try to get the documentation string for each command topics = self.get_help_topics() for command in cmds: cmd_func = self.cmd_func(command) # Non-argparse commands can have help_functions for their documentation if not hasattr(cmd_func, 'argparser') and command in topics: help_func = getattr(self, HELP_FUNC_PREFIX + command) result = io.StringIO() # try to redirect system stdout with redirect_stdout(result): # save our internal stdout stdout_orig = self.stdout try: # redirect our internal stdout self.stdout = result help_func() finally: # restore internal stdout self.stdout = stdout_orig doc = result.getvalue() else: doc = cmd_func.__doc__ # Attempt to locate the first documentation block if not doc: doc_block = [''] else: doc_block = [] found_first = False for doc_line in doc.splitlines(): stripped_line = doc_line.strip() # Don't include :param type lines if stripped_line.startswith(':'): if found_first: break elif stripped_line: doc_block.append(stripped_line) found_first = True elif found_first: break for doc_line in doc_block: self.stdout.write('{: <{col_width}}{doc}\n'.format(command, col_width=widest, doc=doc_line)) command = '' self.stdout.write("\n")
[ "def", "_print_topics", "(", "self", ",", "header", ":", "str", ",", "cmds", ":", "List", "[", "str", "]", ",", "verbose", ":", "bool", ")", "->", "None", ":", "import", "io", "if", "cmds", ":", "if", "not", "verbose", ":", "self", ".", "print_topi...
Customized version of print_topics that can switch between verbose or traditional output
[ "Customized", "version", "of", "print_topics", "that", "can", "switch", "between", "verbose", "or", "traditional", "output" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2722-L2796
230,240
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_shortcuts
def do_shortcuts(self, _: argparse.Namespace) -> None: """List available shortcuts""" result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) self.poutput("Shortcuts for other commands:\n{}\n".format(result))
python
def do_shortcuts(self, _: argparse.Namespace) -> None: result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) self.poutput("Shortcuts for other commands:\n{}\n".format(result))
[ "def", "do_shortcuts", "(", "self", ",", "_", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "result", "=", "\"\\n\"", ".", "join", "(", "'%s: %s'", "%", "(", "sc", "[", "0", "]", ",", "sc", "[", "1", "]", ")", "for", "sc", "in", "s...
List available shortcuts
[ "List", "available", "shortcuts" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2799-L2802
230,241
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_quit
def do_quit(self, _: argparse.Namespace) -> bool: """Exit this application""" self._should_quit = True return self._STOP_AND_EXIT
python
def do_quit(self, _: argparse.Namespace) -> bool: self._should_quit = True return self._STOP_AND_EXIT
[ "def", "do_quit", "(", "self", ",", "_", ":", "argparse", ".", "Namespace", ")", "->", "bool", ":", "self", ".", "_should_quit", "=", "True", "return", "self", ".", "_STOP_AND_EXIT" ]
Exit this application
[ "Exit", "this", "application" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2811-L2814
230,242
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.select
def select(self, opts: Union[str, List[str], List[Tuple[Any, Optional[str]]]], prompt: str = 'Your choice? ') -> str: """Presents a numbered menu to the user. Modeled after the bash shell's SELECT. Returns the item chosen. Argument ``opts`` can be: | a single string -> will be split into one-word options | a list of strings -> will be offered as options | a list of tuples -> interpreted as (value, text), so that the return value can differ from the text advertised to the user """ local_opts = opts if isinstance(opts, str): local_opts = list(zip(opts.split(), opts.split())) fulloptions = [] for opt in local_opts: if isinstance(opt, str): fulloptions.append((opt, opt)) else: try: fulloptions.append((opt[0], opt[1])) except IndexError: fulloptions.append((opt[0], opt[0])) for (idx, (_, text)) in enumerate(fulloptions): self.poutput(' %2d. %s\n' % (idx + 1, text)) while True: safe_prompt = rl_make_safe_prompt(prompt) response = input(safe_prompt) if rl_type != RlType.NONE: hlen = readline.get_current_history_length() if hlen >= 1 and response != '': readline.remove_history_item(hlen - 1) try: choice = int(response) if choice < 1: raise IndexError result = fulloptions[choice - 1][0] break except (ValueError, IndexError): self.poutput("{!r} isn't a valid choice. Pick a number between 1 and {}:\n".format(response, len(fulloptions))) return result
python
def select(self, opts: Union[str, List[str], List[Tuple[Any, Optional[str]]]], prompt: str = 'Your choice? ') -> str: local_opts = opts if isinstance(opts, str): local_opts = list(zip(opts.split(), opts.split())) fulloptions = [] for opt in local_opts: if isinstance(opt, str): fulloptions.append((opt, opt)) else: try: fulloptions.append((opt[0], opt[1])) except IndexError: fulloptions.append((opt[0], opt[0])) for (idx, (_, text)) in enumerate(fulloptions): self.poutput(' %2d. %s\n' % (idx + 1, text)) while True: safe_prompt = rl_make_safe_prompt(prompt) response = input(safe_prompt) if rl_type != RlType.NONE: hlen = readline.get_current_history_length() if hlen >= 1 and response != '': readline.remove_history_item(hlen - 1) try: choice = int(response) if choice < 1: raise IndexError result = fulloptions[choice - 1][0] break except (ValueError, IndexError): self.poutput("{!r} isn't a valid choice. Pick a number between 1 and {}:\n".format(response, len(fulloptions))) return result
[ "def", "select", "(", "self", ",", "opts", ":", "Union", "[", "str", ",", "List", "[", "str", "]", ",", "List", "[", "Tuple", "[", "Any", ",", "Optional", "[", "str", "]", "]", "]", "]", ",", "prompt", ":", "str", "=", "'Your choice? '", ")", "...
Presents a numbered menu to the user. Modeled after the bash shell's SELECT. Returns the item chosen. Argument ``opts`` can be: | a single string -> will be split into one-word options | a list of strings -> will be offered as options | a list of tuples -> interpreted as (value, text), so that the return value can differ from the text advertised to the user
[ "Presents", "a", "numbered", "menu", "to", "the", "user", ".", "Modeled", "after", "the", "bash", "shell", "s", "SELECT", ".", "Returns", "the", "item", "chosen", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2816-L2860
230,243
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.show
def show(self, args: argparse.Namespace, parameter: str = '') -> None: """Shows current settings of parameters. :param args: argparse parsed arguments from the set command :param parameter: optional search parameter """ param = utils.norm_fold(parameter.strip()) result = {} maxlen = 0 for p in self.settable: if (not param) or p.startswith(param): result[p] = '{}: {}'.format(p, str(getattr(self, p))) maxlen = max(maxlen, len(result[p])) if result: for p in sorted(result): if args.long: self.poutput('{} # {}'.format(result[p].ljust(maxlen), self.settable[p])) else: self.poutput(result[p]) # If user has requested to see all settings, also show read-only settings if args.all: self.poutput('\nRead only settings:{}'.format(self.cmdenvironment())) else: self.perror("Parameter '{}' not supported (type 'set' for list of parameters).".format(param), traceback_war=False)
python
def show(self, args: argparse.Namespace, parameter: str = '') -> None: param = utils.norm_fold(parameter.strip()) result = {} maxlen = 0 for p in self.settable: if (not param) or p.startswith(param): result[p] = '{}: {}'.format(p, str(getattr(self, p))) maxlen = max(maxlen, len(result[p])) if result: for p in sorted(result): if args.long: self.poutput('{} # {}'.format(result[p].ljust(maxlen), self.settable[p])) else: self.poutput(result[p]) # If user has requested to see all settings, also show read-only settings if args.all: self.poutput('\nRead only settings:{}'.format(self.cmdenvironment())) else: self.perror("Parameter '{}' not supported (type 'set' for list of parameters).".format(param), traceback_war=False)
[ "def", "show", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ",", "parameter", ":", "str", "=", "''", ")", "->", "None", ":", "param", "=", "utils", ".", "norm_fold", "(", "parameter", ".", "strip", "(", ")", ")", "result", "=", "{",...
Shows current settings of parameters. :param args: argparse parsed arguments from the set command :param parameter: optional search parameter
[ "Shows", "current", "settings", "of", "parameters", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2874-L2901
230,244
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_set
def do_set(self, args: argparse.Namespace) -> None: """Set a settable parameter or show current settings of parameters""" # Check if param was passed in if not args.param: return self.show(args) param = utils.norm_fold(args.param.strip()) # Check if value was passed in if not args.value: return self.show(args, param) value = args.value # Check if param points to just one settable if param not in self.settable: hits = [p for p in self.settable if p.startswith(param)] if len(hits) == 1: param = hits[0] else: return self.show(args, param) # Update the settable's value current_value = getattr(self, param) value = utils.cast(current_value, value) setattr(self, param, value) self.poutput('{} - was: {}\nnow: {}\n'.format(param, current_value, value)) # See if we need to call a change hook for this settable if current_value != value: onchange_hook = getattr(self, '_onchange_{}'.format(param), None) if onchange_hook is not None: onchange_hook(old=current_value, new=value)
python
def do_set(self, args: argparse.Namespace) -> None: # Check if param was passed in if not args.param: return self.show(args) param = utils.norm_fold(args.param.strip()) # Check if value was passed in if not args.value: return self.show(args, param) value = args.value # Check if param points to just one settable if param not in self.settable: hits = [p for p in self.settable if p.startswith(param)] if len(hits) == 1: param = hits[0] else: return self.show(args, param) # Update the settable's value current_value = getattr(self, param) value = utils.cast(current_value, value) setattr(self, param, value) self.poutput('{} - was: {}\nnow: {}\n'.format(param, current_value, value)) # See if we need to call a change hook for this settable if current_value != value: onchange_hook = getattr(self, '_onchange_{}'.format(param), None) if onchange_hook is not None: onchange_hook(old=current_value, new=value)
[ "def", "do_set", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "# Check if param was passed in", "if", "not", "args", ".", "param", ":", "return", "self", ".", "show", "(", "args", ")", "param", "=", "utils", ".", ...
Set a settable parameter or show current settings of parameters
[ "Set", "a", "settable", "parameter", "or", "show", "current", "settings", "of", "parameters" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2916-L2948
230,245
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_shell
def do_shell(self, args: argparse.Namespace) -> None: """Execute a command as if at the OS prompt""" import subprocess # Create a list of arguments to shell tokens = [args.command] + args.command_args # Support expanding ~ in quoted paths for index, _ in enumerate(tokens): if tokens[index]: # Check if the token is quoted. Since parsing already passed, there isn't # an unclosed quote. So we only need to check the first character. first_char = tokens[index][0] if first_char in constants.QUOTES: tokens[index] = utils.strip_quotes(tokens[index]) tokens[index] = os.path.expanduser(tokens[index]) # Restore the quotes if first_char in constants.QUOTES: tokens[index] = first_char + tokens[index] + first_char expanded_command = ' '.join(tokens) # Prevent KeyboardInterrupts while in the shell process. The shell process will # still receive the SIGINT since it is in the same process group as us. with self.sigint_protection: # For any stream that is a StdSim, we will use a pipe so we can capture its output proc = subprocess.Popen(expanded_command, stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout, stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr, shell=True) proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr) proc_reader.wait()
python
def do_shell(self, args: argparse.Namespace) -> None: import subprocess # Create a list of arguments to shell tokens = [args.command] + args.command_args # Support expanding ~ in quoted paths for index, _ in enumerate(tokens): if tokens[index]: # Check if the token is quoted. Since parsing already passed, there isn't # an unclosed quote. So we only need to check the first character. first_char = tokens[index][0] if first_char in constants.QUOTES: tokens[index] = utils.strip_quotes(tokens[index]) tokens[index] = os.path.expanduser(tokens[index]) # Restore the quotes if first_char in constants.QUOTES: tokens[index] = first_char + tokens[index] + first_char expanded_command = ' '.join(tokens) # Prevent KeyboardInterrupts while in the shell process. The shell process will # still receive the SIGINT since it is in the same process group as us. with self.sigint_protection: # For any stream that is a StdSim, we will use a pipe so we can capture its output proc = subprocess.Popen(expanded_command, stdout=subprocess.PIPE if isinstance(self.stdout, utils.StdSim) else self.stdout, stderr=subprocess.PIPE if isinstance(sys.stderr, utils.StdSim) else sys.stderr, shell=True) proc_reader = utils.ProcReader(proc, self.stdout, sys.stderr) proc_reader.wait()
[ "def", "do_shell", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "import", "subprocess", "# Create a list of arguments to shell", "tokens", "=", "[", "args", ".", "command", "]", "+", "args", ".", "command_args", "# Suppo...
Execute a command as if at the OS prompt
[ "Execute", "a", "command", "as", "if", "at", "the", "OS", "prompt" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2959-L2993
230,246
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._reset_py_display
def _reset_py_display() -> None: """ Resets the dynamic objects in the sys module that the py and ipy consoles fight over. When a Python console starts it adopts certain display settings if they've already been set. If an ipy console has previously been run, then py uses its settings and ends up looking like an ipy console in terms of prompt and exception text. This method forces the Python console to create its own display settings since they won't exist. IPython does not have this problem since it always overwrites the display settings when it is run. Therefore this method only needs to be called before creating a Python console. """ # Delete any prompts that have been set attributes = ['ps1', 'ps2', 'ps3'] for cur_attr in attributes: try: del sys.__dict__[cur_attr] except KeyError: pass # Reset functions sys.displayhook = sys.__displayhook__ sys.excepthook = sys.__excepthook__
python
def _reset_py_display() -> None: # Delete any prompts that have been set attributes = ['ps1', 'ps2', 'ps3'] for cur_attr in attributes: try: del sys.__dict__[cur_attr] except KeyError: pass # Reset functions sys.displayhook = sys.__displayhook__ sys.excepthook = sys.__excepthook__
[ "def", "_reset_py_display", "(", ")", "->", "None", ":", "# Delete any prompts that have been set", "attributes", "=", "[", "'ps1'", ",", "'ps2'", ",", "'ps3'", "]", "for", "cur_attr", "in", "attributes", ":", "try", ":", "del", "sys", ".", "__dict__", "[", ...
Resets the dynamic objects in the sys module that the py and ipy consoles fight over. When a Python console starts it adopts certain display settings if they've already been set. If an ipy console has previously been run, then py uses its settings and ends up looking like an ipy console in terms of prompt and exception text. This method forces the Python console to create its own display settings since they won't exist. IPython does not have this problem since it always overwrites the display settings when it is run. Therefore this method only needs to be called before creating a Python console.
[ "Resets", "the", "dynamic", "objects", "in", "the", "sys", "module", "that", "the", "py", "and", "ipy", "consoles", "fight", "over", ".", "When", "a", "Python", "console", "starts", "it", "adopts", "certain", "display", "settings", "if", "they", "ve", "alr...
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2996-L3017
230,247
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_pyscript
def do_pyscript(self, args: argparse.Namespace) -> bool: """Run a Python script file inside the console""" script_path = os.path.expanduser(args.script_path) py_return = False # Save current command line arguments orig_args = sys.argv try: # Overwrite sys.argv to allow the script to take command line arguments sys.argv = [script_path] + args.script_arguments # Run the script - use repr formatting to escape things which # need to be escaped to prevent issues on Windows py_return = self.do_py("run({!r})".format(script_path)) except KeyboardInterrupt: pass finally: # Restore command line arguments to original state sys.argv = orig_args return py_return
python
def do_pyscript(self, args: argparse.Namespace) -> bool: script_path = os.path.expanduser(args.script_path) py_return = False # Save current command line arguments orig_args = sys.argv try: # Overwrite sys.argv to allow the script to take command line arguments sys.argv = [script_path] + args.script_arguments # Run the script - use repr formatting to escape things which # need to be escaped to prevent issues on Windows py_return = self.do_py("run({!r})".format(script_path)) except KeyboardInterrupt: pass finally: # Restore command line arguments to original state sys.argv = orig_args return py_return
[ "def", "do_pyscript", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "bool", ":", "script_path", "=", "os", ".", "path", ".", "expanduser", "(", "args", ".", "script_path", ")", "py_return", "=", "False", "# Save current command line...
Run a Python script file inside the console
[ "Run", "a", "Python", "script", "file", "inside", "the", "console" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3222-L3245
230,248
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._generate_transcript
def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None: """Generate a transcript file from a given history of commands.""" import io # Validate the transcript file path to make sure directory exists and write access is available transcript_path = os.path.abspath(os.path.expanduser(transcript_file)) transcript_dir = os.path.dirname(transcript_path) if not os.path.isdir(transcript_dir) or not os.access(transcript_dir, os.W_OK): self.perror("{!r} is not a directory or you don't have write access".format(transcript_dir), traceback_war=False) return try: with self.sigint_protection: # Disable echo while we manually redirect stdout to a StringIO buffer saved_echo = self.echo saved_stdout = self.stdout self.echo = False # The problem with supporting regular expressions in transcripts # is that they shouldn't be processed in the command, just the output. # In addition, when we generate a transcript, any slashes in the output # are not really intended to indicate regular expressions, so they should # be escaped. # # We have to jump through some hoops here in order to catch the commands # separately from the output and escape the slashes in the output. transcript = '' for history_item in history: # build the command, complete with prompts. When we replay # the transcript, we look for the prompts to separate # the command from the output first = True command = '' for line in history_item.splitlines(): if first: command += '{}{}\n'.format(self.prompt, line) first = False else: command += '{}{}\n'.format(self.continuation_prompt, line) transcript += command # create a new string buffer and set it to stdout to catch the output # of the command membuf = io.StringIO() self.stdout = membuf # then run the command and let the output go into our buffer self.onecmd_plus_hooks(history_item) # rewind the buffer to the beginning membuf.seek(0) # get the output out of the buffer output = membuf.read() # and add the regex-escaped output to the transcript transcript += output.replace('/', r'\/') finally: with self.sigint_protection: # Restore altered attributes to their original state self.echo = saved_echo self.stdout = saved_stdout # finally, we can write the transcript out to the file try: with open(transcript_file, 'w') as fout: fout.write(transcript) except OSError as ex: self.perror('Failed to save transcript: {}'.format(ex), traceback_war=False) else: # and let the user know what we did if len(history) > 1: plural = 'commands and their outputs' else: plural = 'command and its output' msg = '{} {} saved to transcript file {!r}' self.pfeedback(msg.format(len(history), plural, transcript_file))
python
def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None: import io # Validate the transcript file path to make sure directory exists and write access is available transcript_path = os.path.abspath(os.path.expanduser(transcript_file)) transcript_dir = os.path.dirname(transcript_path) if not os.path.isdir(transcript_dir) or not os.access(transcript_dir, os.W_OK): self.perror("{!r} is not a directory or you don't have write access".format(transcript_dir), traceback_war=False) return try: with self.sigint_protection: # Disable echo while we manually redirect stdout to a StringIO buffer saved_echo = self.echo saved_stdout = self.stdout self.echo = False # The problem with supporting regular expressions in transcripts # is that they shouldn't be processed in the command, just the output. # In addition, when we generate a transcript, any slashes in the output # are not really intended to indicate regular expressions, so they should # be escaped. # # We have to jump through some hoops here in order to catch the commands # separately from the output and escape the slashes in the output. transcript = '' for history_item in history: # build the command, complete with prompts. When we replay # the transcript, we look for the prompts to separate # the command from the output first = True command = '' for line in history_item.splitlines(): if first: command += '{}{}\n'.format(self.prompt, line) first = False else: command += '{}{}\n'.format(self.continuation_prompt, line) transcript += command # create a new string buffer and set it to stdout to catch the output # of the command membuf = io.StringIO() self.stdout = membuf # then run the command and let the output go into our buffer self.onecmd_plus_hooks(history_item) # rewind the buffer to the beginning membuf.seek(0) # get the output out of the buffer output = membuf.read() # and add the regex-escaped output to the transcript transcript += output.replace('/', r'\/') finally: with self.sigint_protection: # Restore altered attributes to their original state self.echo = saved_echo self.stdout = saved_stdout # finally, we can write the transcript out to the file try: with open(transcript_file, 'w') as fout: fout.write(transcript) except OSError as ex: self.perror('Failed to save transcript: {}'.format(ex), traceback_war=False) else: # and let the user know what we did if len(history) > 1: plural = 'commands and their outputs' else: plural = 'command and its output' msg = '{} {} saved to transcript file {!r}' self.pfeedback(msg.format(len(history), plural, transcript_file))
[ "def", "_generate_transcript", "(", "self", ",", "history", ":", "List", "[", "Union", "[", "HistoryItem", ",", "str", "]", "]", ",", "transcript_file", ":", "str", ")", "->", "None", ":", "import", "io", "# Validate the transcript file path to make sure directory...
Generate a transcript file from a given history of commands.
[ "Generate", "a", "transcript", "file", "from", "a", "given", "history", "of", "commands", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3401-L3472
230,249
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_edit
def do_edit(self, args: argparse.Namespace) -> None: """Edit a file in a text editor""" if not self.editor: raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.") command = utils.quote_string_if_needed(os.path.expanduser(self.editor)) if args.file_path: command += " " + utils.quote_string_if_needed(os.path.expanduser(args.file_path)) self.do_shell(command)
python
def do_edit(self, args: argparse.Namespace) -> None: if not self.editor: raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.") command = utils.quote_string_if_needed(os.path.expanduser(self.editor)) if args.file_path: command += " " + utils.quote_string_if_needed(os.path.expanduser(args.file_path)) self.do_shell(command)
[ "def", "do_edit", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "if", "not", "self", ".", "editor", ":", "raise", "EnvironmentError", "(", "\"Please use 'set editor' to specify your text editing program of choice.\"", ")", "com...
Edit a file in a text editor
[ "Edit", "a", "file", "in", "a", "text", "editor" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3485-L3494
230,250
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.do_eos
def do_eos(self, _: argparse.Namespace) -> None: """Handle cleanup when a script has finished executing""" if self._script_dir: self._script_dir.pop()
python
def do_eos(self, _: argparse.Namespace) -> None: if self._script_dir: self._script_dir.pop()
[ "def", "do_eos", "(", "self", ",", "_", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "if", "self", ".", "_script_dir", ":", "self", ".", "_script_dir", ".", "pop", "(", ")" ]
Handle cleanup when a script has finished executing
[ "Handle", "cleanup", "when", "a", "script", "has", "finished", "executing" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3505-L3508
230,251
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.async_alert
def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: # pragma: no cover """ Display an important message to the user while they are at the prompt in between commands. To the user it appears as if an alert message is printed above the prompt and their current input text and cursor location is left alone. IMPORTANT: This function will not print an alert unless it can acquire self.terminal_lock to ensure a prompt is onscreen. Therefore it is best to acquire the lock before calling this function to guarantee the alert prints. :param alert_msg: the message to display to the user :param new_prompt: if you also want to change the prompt that is displayed, then include it here see async_update_prompt() docstring for guidance on updating a prompt :raises RuntimeError if called while another thread holds terminal_lock """ if not (vt100_support and self.use_rawinput): return import shutil import colorama.ansi as ansi from colorama import Cursor # Sanity check that can't fail if self.terminal_lock was acquired before calling this function if self.terminal_lock.acquire(blocking=False): # Figure out what prompt is displaying current_prompt = self.continuation_prompt if self.at_continuation_prompt else self.prompt # Only update terminal if there are changes update_terminal = False if alert_msg: alert_msg += '\n' update_terminal = True # Set the prompt if its changed if new_prompt is not None and new_prompt != self.prompt: self.prompt = new_prompt # If we aren't at a continuation prompt, then it's OK to update it if not self.at_continuation_prompt: rl_set_prompt(self.prompt) update_terminal = True if update_terminal: # Get the size of the terminal terminal_size = shutil.get_terminal_size() # Split the prompt lines since it can contain newline characters. prompt_lines = current_prompt.splitlines() # Calculate how many terminal lines are taken up by all prompt lines except for the last one. # That will be included in the input lines calculations since that is where the cursor is. num_prompt_terminal_lines = 0 for line in prompt_lines[:-1]: line_width = utils.ansi_safe_wcswidth(line) num_prompt_terminal_lines += int(line_width / terminal_size.columns) + 1 # Now calculate how many terminal lines are take up by the input last_prompt_line = prompt_lines[-1] last_prompt_line_width = utils.ansi_safe_wcswidth(last_prompt_line) input_width = last_prompt_line_width + utils.ansi_safe_wcswidth(readline.get_line_buffer()) num_input_terminal_lines = int(input_width / terminal_size.columns) + 1 # Get the cursor's offset from the beginning of the first input line cursor_input_offset = last_prompt_line_width + rl_get_point() # Calculate what input line the cursor is on cursor_input_line = int(cursor_input_offset / terminal_size.columns) + 1 # Create a string that when printed will clear all input lines and display the alert terminal_str = '' # Move the cursor down to the last input line if cursor_input_line != num_input_terminal_lines: terminal_str += Cursor.DOWN(num_input_terminal_lines - cursor_input_line) # Clear each line from the bottom up so that the cursor ends up on the first prompt line total_lines = num_prompt_terminal_lines + num_input_terminal_lines terminal_str += (ansi.clear_line() + Cursor.UP(1)) * (total_lines - 1) # Clear the first prompt line terminal_str += ansi.clear_line() # Move the cursor to the beginning of the first prompt line and print the alert terminal_str += '\r' + alert_msg if rl_type == RlType.GNU: sys.stderr.write(terminal_str) elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode.console.write(terminal_str) # Redraw the prompt and input lines rl_force_redisplay() self.terminal_lock.release() else: raise RuntimeError("another thread holds terminal_lock")
python
def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: # pragma: no cover if not (vt100_support and self.use_rawinput): return import shutil import colorama.ansi as ansi from colorama import Cursor # Sanity check that can't fail if self.terminal_lock was acquired before calling this function if self.terminal_lock.acquire(blocking=False): # Figure out what prompt is displaying current_prompt = self.continuation_prompt if self.at_continuation_prompt else self.prompt # Only update terminal if there are changes update_terminal = False if alert_msg: alert_msg += '\n' update_terminal = True # Set the prompt if its changed if new_prompt is not None and new_prompt != self.prompt: self.prompt = new_prompt # If we aren't at a continuation prompt, then it's OK to update it if not self.at_continuation_prompt: rl_set_prompt(self.prompt) update_terminal = True if update_terminal: # Get the size of the terminal terminal_size = shutil.get_terminal_size() # Split the prompt lines since it can contain newline characters. prompt_lines = current_prompt.splitlines() # Calculate how many terminal lines are taken up by all prompt lines except for the last one. # That will be included in the input lines calculations since that is where the cursor is. num_prompt_terminal_lines = 0 for line in prompt_lines[:-1]: line_width = utils.ansi_safe_wcswidth(line) num_prompt_terminal_lines += int(line_width / terminal_size.columns) + 1 # Now calculate how many terminal lines are take up by the input last_prompt_line = prompt_lines[-1] last_prompt_line_width = utils.ansi_safe_wcswidth(last_prompt_line) input_width = last_prompt_line_width + utils.ansi_safe_wcswidth(readline.get_line_buffer()) num_input_terminal_lines = int(input_width / terminal_size.columns) + 1 # Get the cursor's offset from the beginning of the first input line cursor_input_offset = last_prompt_line_width + rl_get_point() # Calculate what input line the cursor is on cursor_input_line = int(cursor_input_offset / terminal_size.columns) + 1 # Create a string that when printed will clear all input lines and display the alert terminal_str = '' # Move the cursor down to the last input line if cursor_input_line != num_input_terminal_lines: terminal_str += Cursor.DOWN(num_input_terminal_lines - cursor_input_line) # Clear each line from the bottom up so that the cursor ends up on the first prompt line total_lines = num_prompt_terminal_lines + num_input_terminal_lines terminal_str += (ansi.clear_line() + Cursor.UP(1)) * (total_lines - 1) # Clear the first prompt line terminal_str += ansi.clear_line() # Move the cursor to the beginning of the first prompt line and print the alert terminal_str += '\r' + alert_msg if rl_type == RlType.GNU: sys.stderr.write(terminal_str) elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode.console.write(terminal_str) # Redraw the prompt and input lines rl_force_redisplay() self.terminal_lock.release() else: raise RuntimeError("another thread holds terminal_lock")
[ "def", "async_alert", "(", "self", ",", "alert_msg", ":", "str", ",", "new_prompt", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "# pragma: no cover", "if", "not", "(", "vt100_support", "and", "self", ".", "use_rawinput", ")", "...
Display an important message to the user while they are at the prompt in between commands. To the user it appears as if an alert message is printed above the prompt and their current input text and cursor location is left alone. IMPORTANT: This function will not print an alert unless it can acquire self.terminal_lock to ensure a prompt is onscreen. Therefore it is best to acquire the lock before calling this function to guarantee the alert prints. :param alert_msg: the message to display to the user :param new_prompt: if you also want to change the prompt that is displayed, then include it here see async_update_prompt() docstring for guidance on updating a prompt :raises RuntimeError if called while another thread holds terminal_lock
[ "Display", "an", "important", "message", "to", "the", "user", "while", "they", "are", "at", "the", "prompt", "in", "between", "commands", ".", "To", "the", "user", "it", "appears", "as", "if", "an", "alert", "message", "is", "printed", "above", "the", "p...
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3611-L3712
230,252
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.set_window_title
def set_window_title(self, title: str) -> None: # pragma: no cover """ Set the terminal window title IMPORTANT: This function will not set the title unless it can acquire self.terminal_lock to avoid writing to stderr while a command is running. Therefore it is best to acquire the lock before calling this function to guarantee the title changes. :param title: the new window title :raises RuntimeError if called while another thread holds terminal_lock """ if not vt100_support: return # Sanity check that can't fail if self.terminal_lock was acquired before calling this function if self.terminal_lock.acquire(blocking=False): try: import colorama.ansi as ansi sys.stderr.write(ansi.set_title(title)) except AttributeError: # Debugging in Pycharm has issues with setting terminal title pass finally: self.terminal_lock.release() else: raise RuntimeError("another thread holds terminal_lock")
python
def set_window_title(self, title: str) -> None: # pragma: no cover if not vt100_support: return # Sanity check that can't fail if self.terminal_lock was acquired before calling this function if self.terminal_lock.acquire(blocking=False): try: import colorama.ansi as ansi sys.stderr.write(ansi.set_title(title)) except AttributeError: # Debugging in Pycharm has issues with setting terminal title pass finally: self.terminal_lock.release() else: raise RuntimeError("another thread holds terminal_lock")
[ "def", "set_window_title", "(", "self", ",", "title", ":", "str", ")", "->", "None", ":", "# pragma: no cover", "if", "not", "vt100_support", ":", "return", "# Sanity check that can't fail if self.terminal_lock was acquired before calling this function", "if", "self", ".", ...
Set the terminal window title IMPORTANT: This function will not set the title unless it can acquire self.terminal_lock to avoid writing to stderr while a command is running. Therefore it is best to acquire the lock before calling this function to guarantee the title changes. :param title: the new window title :raises RuntimeError if called while another thread holds terminal_lock
[ "Set", "the", "terminal", "window", "title" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3735-L3761
230,253
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._initialize_plugin_system
def _initialize_plugin_system(self) -> None: """Initialize the plugin system""" self._preloop_hooks = [] self._postloop_hooks = [] self._postparsing_hooks = [] self._precmd_hooks = [] self._postcmd_hooks = [] self._cmdfinalization_hooks = []
python
def _initialize_plugin_system(self) -> None: self._preloop_hooks = [] self._postloop_hooks = [] self._postparsing_hooks = [] self._precmd_hooks = [] self._postcmd_hooks = [] self._cmdfinalization_hooks = []
[ "def", "_initialize_plugin_system", "(", "self", ")", "->", "None", ":", "self", ".", "_preloop_hooks", "=", "[", "]", "self", ".", "_postloop_hooks", "=", "[", "]", "self", ".", "_postparsing_hooks", "=", "[", "]", "self", ".", "_precmd_hooks", "=", "[", ...
Initialize the plugin system
[ "Initialize", "the", "plugin", "system" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3935-L3942
230,254
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._validate_callable_param_count
def _validate_callable_param_count(cls, func: Callable, count: int) -> None: """Ensure a function has the given number of parameters.""" signature = inspect.signature(func) # validate that the callable has the right number of parameters nparam = len(signature.parameters) if nparam != count: raise TypeError('{} has {} positional arguments, expected {}'.format( func.__name__, nparam, count, ))
python
def _validate_callable_param_count(cls, func: Callable, count: int) -> None: signature = inspect.signature(func) # validate that the callable has the right number of parameters nparam = len(signature.parameters) if nparam != count: raise TypeError('{} has {} positional arguments, expected {}'.format( func.__name__, nparam, count, ))
[ "def", "_validate_callable_param_count", "(", "cls", ",", "func", ":", "Callable", ",", "count", ":", "int", ")", "->", "None", ":", "signature", "=", "inspect", ".", "signature", "(", "func", ")", "# validate that the callable has the right number of parameters", "...
Ensure a function has the given number of parameters.
[ "Ensure", "a", "function", "has", "the", "given", "number", "of", "parameters", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3945-L3955
230,255
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._validate_prepostloop_callable
def _validate_prepostloop_callable(cls, func: Callable[[None], None]) -> None: """Check parameter and return types for preloop and postloop hooks.""" cls._validate_callable_param_count(func, 0) # make sure there is no return notation signature = inspect.signature(func) if signature.return_annotation is not None: raise TypeError("{} must declare return a return type of 'None'".format( func.__name__, ))
python
def _validate_prepostloop_callable(cls, func: Callable[[None], None]) -> None: cls._validate_callable_param_count(func, 0) # make sure there is no return notation signature = inspect.signature(func) if signature.return_annotation is not None: raise TypeError("{} must declare return a return type of 'None'".format( func.__name__, ))
[ "def", "_validate_prepostloop_callable", "(", "cls", ",", "func", ":", "Callable", "[", "[", "None", "]", ",", "None", "]", ")", "->", "None", ":", "cls", ".", "_validate_callable_param_count", "(", "func", ",", "0", ")", "# make sure there is no return notation...
Check parameter and return types for preloop and postloop hooks.
[ "Check", "parameter", "and", "return", "types", "for", "preloop", "and", "postloop", "hooks", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3958-L3966
230,256
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_preloop_hook
def register_preloop_hook(self, func: Callable[[None], None]) -> None: """Register a function to be called at the beginning of the command loop.""" self._validate_prepostloop_callable(func) self._preloop_hooks.append(func)
python
def register_preloop_hook(self, func: Callable[[None], None]) -> None: self._validate_prepostloop_callable(func) self._preloop_hooks.append(func)
[ "def", "register_preloop_hook", "(", "self", ",", "func", ":", "Callable", "[", "[", "None", "]", ",", "None", "]", ")", "->", "None", ":", "self", ".", "_validate_prepostloop_callable", "(", "func", ")", "self", ".", "_preloop_hooks", ".", "append", "(", ...
Register a function to be called at the beginning of the command loop.
[ "Register", "a", "function", "to", "be", "called", "at", "the", "beginning", "of", "the", "command", "loop", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3968-L3971
230,257
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_postloop_hook
def register_postloop_hook(self, func: Callable[[None], None]) -> None: """Register a function to be called at the end of the command loop.""" self._validate_prepostloop_callable(func) self._postloop_hooks.append(func)
python
def register_postloop_hook(self, func: Callable[[None], None]) -> None: self._validate_prepostloop_callable(func) self._postloop_hooks.append(func)
[ "def", "register_postloop_hook", "(", "self", ",", "func", ":", "Callable", "[", "[", "None", "]", ",", "None", "]", ")", "->", "None", ":", "self", ".", "_validate_prepostloop_callable", "(", "func", ")", "self", ".", "_postloop_hooks", ".", "append", "("...
Register a function to be called at the end of the command loop.
[ "Register", "a", "function", "to", "be", "called", "at", "the", "end", "of", "the", "command", "loop", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3973-L3976
230,258
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_postparsing_hook
def register_postparsing_hook(self, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None: """Register a function to be called after parsing user input but before running the command""" self._validate_postparsing_callable(func) self._postparsing_hooks.append(func)
python
def register_postparsing_hook(self, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None: self._validate_postparsing_callable(func) self._postparsing_hooks.append(func)
[ "def", "register_postparsing_hook", "(", "self", ",", "func", ":", "Callable", "[", "[", "plugin", ".", "PostparsingData", "]", ",", "plugin", ".", "PostparsingData", "]", ")", "->", "None", ":", "self", ".", "_validate_postparsing_callable", "(", "func", ")",...
Register a function to be called after parsing user input but before running the command
[ "Register", "a", "function", "to", "be", "called", "after", "parsing", "user", "input", "but", "before", "running", "the", "command" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3993-L3996
230,259
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._validate_prepostcmd_hook
def _validate_prepostcmd_hook(cls, func: Callable, data_type: Type) -> None: """Check parameter and return types for pre and post command hooks.""" signature = inspect.signature(func) # validate that the callable has the right number of parameters cls._validate_callable_param_count(func, 1) # validate the parameter has the right annotation paramname = list(signature.parameters.keys())[0] param = signature.parameters[paramname] if param.annotation != data_type: raise TypeError('argument 1 of {} has incompatible type {}, expected {}'.format( func.__name__, param.annotation, data_type, )) # validate the return value has the right annotation if signature.return_annotation == signature.empty: raise TypeError('{} does not have a declared return type, expected {}'.format( func.__name__, data_type, )) if signature.return_annotation != data_type: raise TypeError('{} has incompatible return type {}, expected {}'.format( func.__name__, signature.return_annotation, data_type, ))
python
def _validate_prepostcmd_hook(cls, func: Callable, data_type: Type) -> None: signature = inspect.signature(func) # validate that the callable has the right number of parameters cls._validate_callable_param_count(func, 1) # validate the parameter has the right annotation paramname = list(signature.parameters.keys())[0] param = signature.parameters[paramname] if param.annotation != data_type: raise TypeError('argument 1 of {} has incompatible type {}, expected {}'.format( func.__name__, param.annotation, data_type, )) # validate the return value has the right annotation if signature.return_annotation == signature.empty: raise TypeError('{} does not have a declared return type, expected {}'.format( func.__name__, data_type, )) if signature.return_annotation != data_type: raise TypeError('{} has incompatible return type {}, expected {}'.format( func.__name__, signature.return_annotation, data_type, ))
[ "def", "_validate_prepostcmd_hook", "(", "cls", ",", "func", ":", "Callable", ",", "data_type", ":", "Type", ")", "->", "None", ":", "signature", "=", "inspect", ".", "signature", "(", "func", ")", "# validate that the callable has the right number of parameters", "...
Check parameter and return types for pre and post command hooks.
[ "Check", "parameter", "and", "return", "types", "for", "pre", "and", "post", "command", "hooks", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3999-L4024
230,260
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_precmd_hook
def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None: """Register a hook to be called before the command function.""" self._validate_prepostcmd_hook(func, plugin.PrecommandData) self._precmd_hooks.append(func)
python
def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None: self._validate_prepostcmd_hook(func, plugin.PrecommandData) self._precmd_hooks.append(func)
[ "def", "register_precmd_hook", "(", "self", ",", "func", ":", "Callable", "[", "[", "plugin", ".", "PrecommandData", "]", ",", "plugin", ".", "PrecommandData", "]", ")", "->", "None", ":", "self", ".", "_validate_prepostcmd_hook", "(", "func", ",", "plugin",...
Register a hook to be called before the command function.
[ "Register", "a", "hook", "to", "be", "called", "before", "the", "command", "function", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L4026-L4029
230,261
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_postcmd_hook
def register_postcmd_hook(self, func: Callable[[plugin.PostcommandData], plugin.PostcommandData]) -> None: """Register a hook to be called after the command function.""" self._validate_prepostcmd_hook(func, plugin.PostcommandData) self._postcmd_hooks.append(func)
python
def register_postcmd_hook(self, func: Callable[[plugin.PostcommandData], plugin.PostcommandData]) -> None: self._validate_prepostcmd_hook(func, plugin.PostcommandData) self._postcmd_hooks.append(func)
[ "def", "register_postcmd_hook", "(", "self", ",", "func", ":", "Callable", "[", "[", "plugin", ".", "PostcommandData", "]", ",", "plugin", ".", "PostcommandData", "]", ")", "->", "None", ":", "self", ".", "_validate_prepostcmd_hook", "(", "func", ",", "plugi...
Register a hook to be called after the command function.
[ "Register", "a", "hook", "to", "be", "called", "after", "the", "command", "function", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L4031-L4034
230,262
python-cmd2/cmd2
cmd2/cmd2.py
Cmd._validate_cmdfinalization_callable
def _validate_cmdfinalization_callable(cls, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: """Check parameter and return types for command finalization hooks.""" cls._validate_callable_param_count(func, 1) signature = inspect.signature(func) _, param = list(signature.parameters.items())[0] if param.annotation != plugin.CommandFinalizationData: raise TypeError("{} must have one parameter declared with type " "'cmd2.plugin.CommandFinalizationData'".format(func.__name__)) if signature.return_annotation != plugin.CommandFinalizationData: raise TypeError("{} must declare return a return type of " "'cmd2.plugin.CommandFinalizationData'".format(func.__name__))
python
def _validate_cmdfinalization_callable(cls, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: cls._validate_callable_param_count(func, 1) signature = inspect.signature(func) _, param = list(signature.parameters.items())[0] if param.annotation != plugin.CommandFinalizationData: raise TypeError("{} must have one parameter declared with type " "'cmd2.plugin.CommandFinalizationData'".format(func.__name__)) if signature.return_annotation != plugin.CommandFinalizationData: raise TypeError("{} must declare return a return type of " "'cmd2.plugin.CommandFinalizationData'".format(func.__name__))
[ "def", "_validate_cmdfinalization_callable", "(", "cls", ",", "func", ":", "Callable", "[", "[", "plugin", ".", "CommandFinalizationData", "]", ",", "plugin", ".", "CommandFinalizationData", "]", ")", "->", "None", ":", "cls", ".", "_validate_callable_param_count", ...
Check parameter and return types for command finalization hooks.
[ "Check", "parameter", "and", "return", "types", "for", "command", "finalization", "hooks", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L4037-L4048
230,263
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_cmdfinalization_hook
def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: """Register a hook to be called after a command is completed, whether it completes successfully or not.""" self._validate_cmdfinalization_callable(func) self._cmdfinalization_hooks.append(func)
python
def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: self._validate_cmdfinalization_callable(func) self._cmdfinalization_hooks.append(func)
[ "def", "register_cmdfinalization_hook", "(", "self", ",", "func", ":", "Callable", "[", "[", "plugin", ".", "CommandFinalizationData", "]", ",", "plugin", ".", "CommandFinalizationData", "]", ")", "->", "None", ":", "self", ".", "_validate_cmdfinalization_callable",...
Register a hook to be called after a command is completed, whether it completes successfully or not.
[ "Register", "a", "hook", "to", "be", "called", "after", "a", "command", "is", "completed", "whether", "it", "completes", "successfully", "or", "not", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L4050-L4054
230,264
python-cmd2/cmd2
cmd2/parsing.py
StatementParser.is_valid_command
def is_valid_command(self, word: str) -> Tuple[bool, str]: """Determine whether a word is a valid name for a command. Commands can not include redirection characters, whitespace, or termination characters. They also cannot start with a shortcut. If word is not a valid command, return False and error text This string is suitable for inclusion in an error message of your choice: valid, errmsg = statement_parser.is_valid_command('>') if not valid: errmsg = "Alias {}".format(errmsg) """ valid = False if not word: return False, 'cannot be an empty string' if word.startswith(constants.COMMENT_CHAR): return False, 'cannot start with the comment character' for (shortcut, _) in self.shortcuts: if word.startswith(shortcut): # Build an error string with all shortcuts listed errmsg = 'cannot start with a shortcut: ' errmsg += ', '.join(shortcut for (shortcut, _) in self.shortcuts) return False, errmsg errmsg = 'cannot contain: whitespace, quotes, ' errchars = [] errchars.extend(constants.REDIRECTION_CHARS) errchars.extend(self.terminators) errmsg += ', '.join([shlex.quote(x) for x in errchars]) match = self._command_pattern.search(word) if match: if word == match.group(1): valid = True errmsg = '' return valid, errmsg
python
def is_valid_command(self, word: str) -> Tuple[bool, str]: valid = False if not word: return False, 'cannot be an empty string' if word.startswith(constants.COMMENT_CHAR): return False, 'cannot start with the comment character' for (shortcut, _) in self.shortcuts: if word.startswith(shortcut): # Build an error string with all shortcuts listed errmsg = 'cannot start with a shortcut: ' errmsg += ', '.join(shortcut for (shortcut, _) in self.shortcuts) return False, errmsg errmsg = 'cannot contain: whitespace, quotes, ' errchars = [] errchars.extend(constants.REDIRECTION_CHARS) errchars.extend(self.terminators) errmsg += ', '.join([shlex.quote(x) for x in errchars]) match = self._command_pattern.search(word) if match: if word == match.group(1): valid = True errmsg = '' return valid, errmsg
[ "def", "is_valid_command", "(", "self", ",", "word", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "valid", "=", "False", "if", "not", "word", ":", "return", "False", ",", "'cannot be an empty string'", "if", "word", ".", "startswith...
Determine whether a word is a valid name for a command. Commands can not include redirection characters, whitespace, or termination characters. They also cannot start with a shortcut. If word is not a valid command, return False and error text This string is suitable for inclusion in an error message of your choice: valid, errmsg = statement_parser.is_valid_command('>') if not valid: errmsg = "Alias {}".format(errmsg)
[ "Determine", "whether", "a", "word", "is", "a", "valid", "name", "for", "a", "command", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L314-L355
230,265
python-cmd2/cmd2
cmd2/parsing.py
StatementParser.tokenize
def tokenize(self, line: str, expand: bool = True) -> List[str]: """ Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed :param line: the command line being lexed :param expand: If True, then aliases and shortcuts will be expanded. Set this to False if no expansion should occur because the command name is already known. Otherwise the command could be expanded if it matched an alias name. This is for cases where a do_* method was called manually (e.g do_help('alias'). :return: A list of tokens :raises ValueError if there are unclosed quotation marks. """ # expand shortcuts and aliases if expand: line = self._expand(line) # check if this line is a comment if line.lstrip().startswith(constants.COMMENT_CHAR): return [] # split on whitespace tokens = shlex_split(line) # custom lexing tokens = self._split_on_punctuation(tokens) return tokens
python
def tokenize(self, line: str, expand: bool = True) -> List[str]: # expand shortcuts and aliases if expand: line = self._expand(line) # check if this line is a comment if line.lstrip().startswith(constants.COMMENT_CHAR): return [] # split on whitespace tokens = shlex_split(line) # custom lexing tokens = self._split_on_punctuation(tokens) return tokens
[ "def", "tokenize", "(", "self", ",", "line", ":", "str", ",", "expand", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "# expand shortcuts and aliases", "if", "expand", ":", "line", "=", "self", ".", "_expand", "(", "line", ")", "...
Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed :param line: the command line being lexed :param expand: If True, then aliases and shortcuts will be expanded. Set this to False if no expansion should occur because the command name is already known. Otherwise the command could be expanded if it matched an alias name. This is for cases where a do_* method was called manually (e.g do_help('alias'). :return: A list of tokens :raises ValueError if there are unclosed quotation marks.
[ "Lex", "a", "string", "into", "a", "list", "of", "tokens", ".", "Shortcuts", "and", "aliases", "are", "expanded", "and", "comments", "are", "removed" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L357-L383
230,266
python-cmd2/cmd2
cmd2/parsing.py
StatementParser.parse
def parse(self, line: str, expand: bool = True) -> Statement: """ Tokenize the input and parse it into a Statement object, stripping comments, expanding aliases and shortcuts, and extracting output redirection directives. :param line: the command line being parsed :param expand: If True, then aliases and shortcuts will be expanded. Set this to False if no expansion should occur because the command name is already known. Otherwise the command could be expanded if it matched an alias name. This is for cases where a do_* method was called manually (e.g do_help('alias'). :return: A parsed Statement :raises ValueError if there are unclosed quotation marks """ # handle the special case/hardcoded terminator of a blank line # we have to do this before we tokenize because tokenizing # destroys all unquoted whitespace in the input terminator = '' if line[-1:] == constants.LINE_FEED: terminator = constants.LINE_FEED command = '' args = '' arg_list = [] # lex the input into a list of tokens tokens = self.tokenize(line, expand) # of the valid terminators, find the first one to occur in the input terminator_pos = len(tokens) + 1 for pos, cur_token in enumerate(tokens): for test_terminator in self.terminators: if cur_token.startswith(test_terminator): terminator_pos = pos terminator = test_terminator # break the inner loop, and we want to break the # outer loop too break else: # this else clause is only run if the inner loop # didn't execute a break. If it didn't, then # continue to the next iteration of the outer loop continue # inner loop was broken, break the outer break if terminator: if terminator == constants.LINE_FEED: terminator_pos = len(tokens) + 1 # everything before the first terminator is the command and the args (command, args) = self._command_and_args(tokens[:terminator_pos]) arg_list = tokens[1:terminator_pos] # we will set the suffix later # remove all the tokens before and including the terminator tokens = tokens[terminator_pos + 1:] else: (testcommand, testargs) = self._command_and_args(tokens) if testcommand in self.multiline_commands: # no terminator on this line but we have a multiline command # everything else on the line is part of the args # because redirectors can only be after a terminator command = testcommand args = testargs arg_list = tokens[1:] tokens = [] # check for a pipe to a shell process # if there is a pipe, everything after the pipe needs to be passed # to the shell, even redirected output # this allows '(Cmd) say hello | wc > countit.txt' try: # find the first pipe if it exists pipe_pos = tokens.index(constants.REDIRECTION_PIPE) # save everything after the first pipe as tokens pipe_to = tokens[pipe_pos + 1:] for pos, cur_token in enumerate(pipe_to): unquoted_token = utils.strip_quotes(cur_token) pipe_to[pos] = os.path.expanduser(unquoted_token) # remove all the tokens after the pipe tokens = tokens[:pipe_pos] except ValueError: # no pipe in the tokens pipe_to = [] # check for output redirect output = '' output_to = '' try: output_pos = tokens.index(constants.REDIRECTION_OUTPUT) output = constants.REDIRECTION_OUTPUT # Check if we are redirecting to a file if len(tokens) > output_pos + 1: unquoted_path = utils.strip_quotes(tokens[output_pos + 1]) output_to = os.path.expanduser(unquoted_path) # remove all the tokens after the output redirect tokens = tokens[:output_pos] except ValueError: pass try: output_pos = tokens.index(constants.REDIRECTION_APPEND) output = constants.REDIRECTION_APPEND # Check if we are redirecting to a file if len(tokens) > output_pos + 1: unquoted_path = utils.strip_quotes(tokens[output_pos + 1]) output_to = os.path.expanduser(unquoted_path) # remove all tokens after the output redirect tokens = tokens[:output_pos] except ValueError: pass if terminator: # whatever is left is the suffix suffix = ' '.join(tokens) else: # no terminator, so whatever is left is the command and the args suffix = '' if not command: # command could already have been set, if so, don't set it again (command, args) = self._command_and_args(tokens) arg_list = tokens[1:] # set multiline if command in self.multiline_commands: multiline_command = command else: multiline_command = '' # build the statement statement = Statement(args, raw=line, command=command, arg_list=arg_list, multiline_command=multiline_command, terminator=terminator, suffix=suffix, pipe_to=pipe_to, output=output, output_to=output_to, ) return statement
python
def parse(self, line: str, expand: bool = True) -> Statement: # handle the special case/hardcoded terminator of a blank line # we have to do this before we tokenize because tokenizing # destroys all unquoted whitespace in the input terminator = '' if line[-1:] == constants.LINE_FEED: terminator = constants.LINE_FEED command = '' args = '' arg_list = [] # lex the input into a list of tokens tokens = self.tokenize(line, expand) # of the valid terminators, find the first one to occur in the input terminator_pos = len(tokens) + 1 for pos, cur_token in enumerate(tokens): for test_terminator in self.terminators: if cur_token.startswith(test_terminator): terminator_pos = pos terminator = test_terminator # break the inner loop, and we want to break the # outer loop too break else: # this else clause is only run if the inner loop # didn't execute a break. If it didn't, then # continue to the next iteration of the outer loop continue # inner loop was broken, break the outer break if terminator: if terminator == constants.LINE_FEED: terminator_pos = len(tokens) + 1 # everything before the first terminator is the command and the args (command, args) = self._command_and_args(tokens[:terminator_pos]) arg_list = tokens[1:terminator_pos] # we will set the suffix later # remove all the tokens before and including the terminator tokens = tokens[terminator_pos + 1:] else: (testcommand, testargs) = self._command_and_args(tokens) if testcommand in self.multiline_commands: # no terminator on this line but we have a multiline command # everything else on the line is part of the args # because redirectors can only be after a terminator command = testcommand args = testargs arg_list = tokens[1:] tokens = [] # check for a pipe to a shell process # if there is a pipe, everything after the pipe needs to be passed # to the shell, even redirected output # this allows '(Cmd) say hello | wc > countit.txt' try: # find the first pipe if it exists pipe_pos = tokens.index(constants.REDIRECTION_PIPE) # save everything after the first pipe as tokens pipe_to = tokens[pipe_pos + 1:] for pos, cur_token in enumerate(pipe_to): unquoted_token = utils.strip_quotes(cur_token) pipe_to[pos] = os.path.expanduser(unquoted_token) # remove all the tokens after the pipe tokens = tokens[:pipe_pos] except ValueError: # no pipe in the tokens pipe_to = [] # check for output redirect output = '' output_to = '' try: output_pos = tokens.index(constants.REDIRECTION_OUTPUT) output = constants.REDIRECTION_OUTPUT # Check if we are redirecting to a file if len(tokens) > output_pos + 1: unquoted_path = utils.strip_quotes(tokens[output_pos + 1]) output_to = os.path.expanduser(unquoted_path) # remove all the tokens after the output redirect tokens = tokens[:output_pos] except ValueError: pass try: output_pos = tokens.index(constants.REDIRECTION_APPEND) output = constants.REDIRECTION_APPEND # Check if we are redirecting to a file if len(tokens) > output_pos + 1: unquoted_path = utils.strip_quotes(tokens[output_pos + 1]) output_to = os.path.expanduser(unquoted_path) # remove all tokens after the output redirect tokens = tokens[:output_pos] except ValueError: pass if terminator: # whatever is left is the suffix suffix = ' '.join(tokens) else: # no terminator, so whatever is left is the command and the args suffix = '' if not command: # command could already have been set, if so, don't set it again (command, args) = self._command_and_args(tokens) arg_list = tokens[1:] # set multiline if command in self.multiline_commands: multiline_command = command else: multiline_command = '' # build the statement statement = Statement(args, raw=line, command=command, arg_list=arg_list, multiline_command=multiline_command, terminator=terminator, suffix=suffix, pipe_to=pipe_to, output=output, output_to=output_to, ) return statement
[ "def", "parse", "(", "self", ",", "line", ":", "str", ",", "expand", ":", "bool", "=", "True", ")", "->", "Statement", ":", "# handle the special case/hardcoded terminator of a blank line", "# we have to do this before we tokenize because tokenizing", "# destroys all unquoted...
Tokenize the input and parse it into a Statement object, stripping comments, expanding aliases and shortcuts, and extracting output redirection directives. :param line: the command line being parsed :param expand: If True, then aliases and shortcuts will be expanded. Set this to False if no expansion should occur because the command name is already known. Otherwise the command could be expanded if it matched an alias name. This is for cases where a do_* method was called manually (e.g do_help('alias'). :return: A parsed Statement :raises ValueError if there are unclosed quotation marks
[ "Tokenize", "the", "input", "and", "parse", "it", "into", "a", "Statement", "object", "stripping", "comments", "expanding", "aliases", "and", "shortcuts", "and", "extracting", "output", "redirection", "directives", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L385-L533
230,267
python-cmd2/cmd2
cmd2/parsing.py
StatementParser.parse_command_only
def parse_command_only(self, rawinput: str) -> Statement: """Partially parse input into a Statement object. The command is identified, and shortcuts and aliases are expanded. Multiline commands are identified, but terminators and output redirection are not parsed. This method is used by tab completion code and therefore must not generate an exception if there are unclosed quotes. The `Statement` object returned by this method can at most contain values in the following attributes: - args - raw - command - multiline_command `Statement.args` includes all output redirection clauses and command terminators. Different from parse(), this method does not remove redundant whitespace within args. However, it does ensure args has no leading or trailing whitespace. """ # expand shortcuts and aliases line = self._expand(rawinput) command = '' args = '' match = self._command_pattern.search(line) if match: # we got a match, extract the command command = match.group(1) # take everything from the end of the first match group to # the end of the line as the arguments (stripping leading # and trailing spaces) args = line[match.end(1):].strip() # if the command is empty that means the input was either empty # or something weird like '>'. args should be empty if we couldn't # parse a command if not command or not args: args = '' # set multiline if command in self.multiline_commands: multiline_command = command else: multiline_command = '' # build the statement statement = Statement(args, raw=rawinput, command=command, multiline_command=multiline_command, ) return statement
python
def parse_command_only(self, rawinput: str) -> Statement: # expand shortcuts and aliases line = self._expand(rawinput) command = '' args = '' match = self._command_pattern.search(line) if match: # we got a match, extract the command command = match.group(1) # take everything from the end of the first match group to # the end of the line as the arguments (stripping leading # and trailing spaces) args = line[match.end(1):].strip() # if the command is empty that means the input was either empty # or something weird like '>'. args should be empty if we couldn't # parse a command if not command or not args: args = '' # set multiline if command in self.multiline_commands: multiline_command = command else: multiline_command = '' # build the statement statement = Statement(args, raw=rawinput, command=command, multiline_command=multiline_command, ) return statement
[ "def", "parse_command_only", "(", "self", ",", "rawinput", ":", "str", ")", "->", "Statement", ":", "# expand shortcuts and aliases", "line", "=", "self", ".", "_expand", "(", "rawinput", ")", "command", "=", "''", "args", "=", "''", "match", "=", "self", ...
Partially parse input into a Statement object. The command is identified, and shortcuts and aliases are expanded. Multiline commands are identified, but terminators and output redirection are not parsed. This method is used by tab completion code and therefore must not generate an exception if there are unclosed quotes. The `Statement` object returned by this method can at most contain values in the following attributes: - args - raw - command - multiline_command `Statement.args` includes all output redirection clauses and command terminators. Different from parse(), this method does not remove redundant whitespace within args. However, it does ensure args has no leading or trailing whitespace.
[ "Partially", "parse", "input", "into", "a", "Statement", "object", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L535-L591
230,268
python-cmd2/cmd2
cmd2/parsing.py
StatementParser._expand
def _expand(self, line: str) -> str: """Expand shortcuts and aliases""" # expand aliases # make a copy of aliases so we can edit it tmp_aliases = list(self.aliases.keys()) keep_expanding = bool(tmp_aliases) while keep_expanding: for cur_alias in tmp_aliases: keep_expanding = False # apply our regex to line match = self._command_pattern.search(line) if match: # we got a match, extract the command command = match.group(1) if command and command == cur_alias: # rebuild line with the expanded alias line = self.aliases[cur_alias] + match.group(2) + line[match.end(2):] tmp_aliases.remove(cur_alias) keep_expanding = bool(tmp_aliases) break # expand shortcuts for (shortcut, expansion) in self.shortcuts: if line.startswith(shortcut): # If the next character after the shortcut isn't a space, then insert one shortcut_len = len(shortcut) if len(line) == shortcut_len or line[shortcut_len] != ' ': expansion += ' ' # Expand the shortcut line = line.replace(shortcut, expansion, 1) break return line
python
def _expand(self, line: str) -> str: # expand aliases # make a copy of aliases so we can edit it tmp_aliases = list(self.aliases.keys()) keep_expanding = bool(tmp_aliases) while keep_expanding: for cur_alias in tmp_aliases: keep_expanding = False # apply our regex to line match = self._command_pattern.search(line) if match: # we got a match, extract the command command = match.group(1) if command and command == cur_alias: # rebuild line with the expanded alias line = self.aliases[cur_alias] + match.group(2) + line[match.end(2):] tmp_aliases.remove(cur_alias) keep_expanding = bool(tmp_aliases) break # expand shortcuts for (shortcut, expansion) in self.shortcuts: if line.startswith(shortcut): # If the next character after the shortcut isn't a space, then insert one shortcut_len = len(shortcut) if len(line) == shortcut_len or line[shortcut_len] != ' ': expansion += ' ' # Expand the shortcut line = line.replace(shortcut, expansion, 1) break return line
[ "def", "_expand", "(", "self", ",", "line", ":", "str", ")", "->", "str", ":", "# expand aliases", "# make a copy of aliases so we can edit it", "tmp_aliases", "=", "list", "(", "self", ".", "aliases", ".", "keys", "(", ")", ")", "keep_expanding", "=", "bool",...
Expand shortcuts and aliases
[ "Expand", "shortcuts", "and", "aliases" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L622-L655
230,269
python-cmd2/cmd2
cmd2/parsing.py
StatementParser._command_and_args
def _command_and_args(tokens: List[str]) -> Tuple[str, str]: """Given a list of tokens, return a tuple of the command and the args as a string. """ command = '' args = '' if tokens: command = tokens[0] if len(tokens) > 1: args = ' '.join(tokens[1:]) return command, args
python
def _command_and_args(tokens: List[str]) -> Tuple[str, str]: command = '' args = '' if tokens: command = tokens[0] if len(tokens) > 1: args = ' '.join(tokens[1:]) return command, args
[ "def", "_command_and_args", "(", "tokens", ":", "List", "[", "str", "]", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "command", "=", "''", "args", "=", "''", "if", "tokens", ":", "command", "=", "tokens", "[", "0", "]", "if", "len", "("...
Given a list of tokens, return a tuple of the command and the args as a string.
[ "Given", "a", "list", "of", "tokens", "return", "a", "tuple", "of", "the", "command", "and", "the", "args", "as", "a", "string", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L658-L671
230,270
python-cmd2/cmd2
cmd2/parsing.py
StatementParser._split_on_punctuation
def _split_on_punctuation(self, tokens: List[str]) -> List[str]: """Further splits tokens from a command line using punctuation characters Punctuation characters are treated as word breaks when they are in unquoted strings. Each run of punctuation characters is treated as a single token. :param tokens: the tokens as parsed by shlex :return: the punctuated tokens """ punctuation = [] punctuation.extend(self.terminators) if self.allow_redirection: punctuation.extend(constants.REDIRECTION_CHARS) punctuated_tokens = [] for cur_initial_token in tokens: # Save tokens up to 1 character in length or quoted tokens. No need to parse these. if len(cur_initial_token) <= 1 or cur_initial_token[0] in constants.QUOTES: punctuated_tokens.append(cur_initial_token) continue # Iterate over each character in this token cur_index = 0 cur_char = cur_initial_token[cur_index] # Keep track of the token we are building new_token = '' while True: if cur_char not in punctuation: # Keep appending to new_token until we hit a punctuation char while cur_char not in punctuation: new_token += cur_char cur_index += 1 if cur_index < len(cur_initial_token): cur_char = cur_initial_token[cur_index] else: break else: cur_punc = cur_char # Keep appending to new_token until we hit something other than cur_punc while cur_char == cur_punc: new_token += cur_char cur_index += 1 if cur_index < len(cur_initial_token): cur_char = cur_initial_token[cur_index] else: break # Save the new token punctuated_tokens.append(new_token) new_token = '' # Check if we've viewed all characters if cur_index >= len(cur_initial_token): break return punctuated_tokens
python
def _split_on_punctuation(self, tokens: List[str]) -> List[str]: punctuation = [] punctuation.extend(self.terminators) if self.allow_redirection: punctuation.extend(constants.REDIRECTION_CHARS) punctuated_tokens = [] for cur_initial_token in tokens: # Save tokens up to 1 character in length or quoted tokens. No need to parse these. if len(cur_initial_token) <= 1 or cur_initial_token[0] in constants.QUOTES: punctuated_tokens.append(cur_initial_token) continue # Iterate over each character in this token cur_index = 0 cur_char = cur_initial_token[cur_index] # Keep track of the token we are building new_token = '' while True: if cur_char not in punctuation: # Keep appending to new_token until we hit a punctuation char while cur_char not in punctuation: new_token += cur_char cur_index += 1 if cur_index < len(cur_initial_token): cur_char = cur_initial_token[cur_index] else: break else: cur_punc = cur_char # Keep appending to new_token until we hit something other than cur_punc while cur_char == cur_punc: new_token += cur_char cur_index += 1 if cur_index < len(cur_initial_token): cur_char = cur_initial_token[cur_index] else: break # Save the new token punctuated_tokens.append(new_token) new_token = '' # Check if we've viewed all characters if cur_index >= len(cur_initial_token): break return punctuated_tokens
[ "def", "_split_on_punctuation", "(", "self", ",", "tokens", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "punctuation", "=", "[", "]", "punctuation", ".", "extend", "(", "self", ".", "terminators", ")", "if", "self", ".", "a...
Further splits tokens from a command line using punctuation characters Punctuation characters are treated as word breaks when they are in unquoted strings. Each run of punctuation characters is treated as a single token. :param tokens: the tokens as parsed by shlex :return: the punctuated tokens
[ "Further", "splits", "tokens", "from", "a", "command", "line", "using", "punctuation", "characters" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/parsing.py#L673-L736
230,271
python-cmd2/cmd2
examples/arg_print.py
ArgumentAndOptionPrinter.do_aprint
def do_aprint(self, statement): """Print the argument string this basic command is called with.""" self.poutput('aprint was called with argument: {!r}'.format(statement)) self.poutput('statement.raw = {!r}'.format(statement.raw)) self.poutput('statement.argv = {!r}'.format(statement.argv)) self.poutput('statement.command = {!r}'.format(statement.command))
python
def do_aprint(self, statement): self.poutput('aprint was called with argument: {!r}'.format(statement)) self.poutput('statement.raw = {!r}'.format(statement.raw)) self.poutput('statement.argv = {!r}'.format(statement.argv)) self.poutput('statement.command = {!r}'.format(statement.command))
[ "def", "do_aprint", "(", "self", ",", "statement", ")", ":", "self", ".", "poutput", "(", "'aprint was called with argument: {!r}'", ".", "format", "(", "statement", ")", ")", "self", ".", "poutput", "(", "'statement.raw = {!r}'", ".", "format", "(", "statement"...
Print the argument string this basic command is called with.
[ "Print", "the", "argument", "string", "this", "basic", "command", "is", "called", "with", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/arg_print.py#L26-L31
230,272
python-cmd2/cmd2
examples/help_categories.py
HelpCategories.do_disable_commands
def do_disable_commands(self, _): """Disable the Application Management commands""" message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME, self.CMD_CAT_APP_MGMT) self.disable_category(self.CMD_CAT_APP_MGMT, message_to_print) self.poutput("The Application Management commands have been disabled")
python
def do_disable_commands(self, _): message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME, self.CMD_CAT_APP_MGMT) self.disable_category(self.CMD_CAT_APP_MGMT, message_to_print) self.poutput("The Application Management commands have been disabled")
[ "def", "do_disable_commands", "(", "self", ",", "_", ")", ":", "message_to_print", "=", "\"{} is not available while {} commands are disabled\"", ".", "format", "(", "COMMAND_NAME", ",", "self", ".", "CMD_CAT_APP_MGMT", ")", "self", ".", "disable_category", "(", "self...
Disable the Application Management commands
[ "Disable", "the", "Application", "Management", "commands" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/help_categories.py#L145-L150
230,273
python-cmd2/cmd2
cmd2/argparse_completer.py
register_custom_actions
def register_custom_actions(parser: argparse.ArgumentParser) -> None: """Register custom argument action types""" parser.register('action', None, _StoreRangeAction) parser.register('action', 'store', _StoreRangeAction) parser.register('action', 'append', _AppendRangeAction)
python
def register_custom_actions(parser: argparse.ArgumentParser) -> None: parser.register('action', None, _StoreRangeAction) parser.register('action', 'store', _StoreRangeAction) parser.register('action', 'append', _AppendRangeAction)
[ "def", "register_custom_actions", "(", "parser", ":", "argparse", ".", "ArgumentParser", ")", "->", "None", ":", "parser", ".", "register", "(", "'action'", ",", "None", ",", "_StoreRangeAction", ")", "parser", ".", "register", "(", "'action'", ",", "'store'",...
Register custom argument action types
[ "Register", "custom", "argument", "action", "types" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/argparse_completer.py#L206-L210
230,274
python-cmd2/cmd2
cmd2/argparse_completer.py
ACArgumentParser.error
def error(self, message: str) -> None: """Custom error override. Allows application to control the error being displayed by argparse""" if len(self._custom_error_message) > 0: message = self._custom_error_message self._custom_error_message = '' lines = message.split('\n') linum = 0 formatted_message = '' for line in lines: if linum == 0: formatted_message = 'Error: ' + line else: formatted_message += '\n ' + line linum += 1 sys.stderr.write(Fore.LIGHTRED_EX + '{}\n\n'.format(formatted_message) + Fore.RESET) # sys.stderr.write('{}\n\n'.format(formatted_message)) self.print_help() sys.exit(1)
python
def error(self, message: str) -> None: if len(self._custom_error_message) > 0: message = self._custom_error_message self._custom_error_message = '' lines = message.split('\n') linum = 0 formatted_message = '' for line in lines: if linum == 0: formatted_message = 'Error: ' + line else: formatted_message += '\n ' + line linum += 1 sys.stderr.write(Fore.LIGHTRED_EX + '{}\n\n'.format(formatted_message) + Fore.RESET) # sys.stderr.write('{}\n\n'.format(formatted_message)) self.print_help() sys.exit(1)
[ "def", "error", "(", "self", ",", "message", ":", "str", ")", "->", "None", ":", "if", "len", "(", "self", ".", "_custom_error_message", ")", ">", "0", ":", "message", "=", "self", ".", "_custom_error_message", "self", ".", "_custom_error_message", "=", ...
Custom error override. Allows application to control the error being displayed by argparse
[ "Custom", "error", "override", ".", "Allows", "application", "to", "control", "the", "error", "being", "displayed", "by", "argparse" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/argparse_completer.py#L1006-L1025
230,275
python-cmd2/cmd2
examples/tab_autocomp_dynamic.py
TabCompleteExample.instance_query_movie_ids
def instance_query_movie_ids(self) -> List[str]: """Demonstrates showing tabular hinting of tab completion information""" completions_with_desc = [] # Sort the movie id strings with a natural sort since they contain numbers for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS): if movie_id in self.MOVIE_DATABASE: movie_entry = self.MOVIE_DATABASE[movie_id] completions_with_desc.append(argparse_completer.CompletionItem(movie_id, movie_entry['title'])) # Mark that we already sorted the matches self.matches_sorted = True return completions_with_desc
python
def instance_query_movie_ids(self) -> List[str]: completions_with_desc = [] # Sort the movie id strings with a natural sort since they contain numbers for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS): if movie_id in self.MOVIE_DATABASE: movie_entry = self.MOVIE_DATABASE[movie_id] completions_with_desc.append(argparse_completer.CompletionItem(movie_id, movie_entry['title'])) # Mark that we already sorted the matches self.matches_sorted = True return completions_with_desc
[ "def", "instance_query_movie_ids", "(", "self", ")", "->", "List", "[", "str", "]", ":", "completions_with_desc", "=", "[", "]", "# Sort the movie id strings with a natural sort since they contain numbers", "for", "movie_id", "in", "utils", ".", "natural_sort", "(", "se...
Demonstrates showing tabular hinting of tab completion information
[ "Demonstrates", "showing", "tabular", "hinting", "of", "tab", "completion", "information" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/tab_autocomp_dynamic.py#L174-L186
230,276
python-cmd2/cmd2
examples/tab_autocomp_dynamic.py
TabCompleteExample.do_video
def do_video(self, args): """Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter""" func = getattr(args, 'func', None) if func is not None: # Call whatever subcommand function was selected func(self, args) else: # No subcommand was provided, so call help self.do_help('video')
python
def do_video(self, args): func = getattr(args, 'func', None) if func is not None: # Call whatever subcommand function was selected func(self, args) else: # No subcommand was provided, so call help self.do_help('video')
[ "def", "do_video", "(", "self", ",", "args", ")", ":", "func", "=", "getattr", "(", "args", ",", "'func'", ",", "None", ")", "if", "func", "is", "not", "None", ":", "# Call whatever subcommand function was selected", "func", "(", "self", ",", "args", ")", ...
Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter
[ "Video", "management", "command", "demonstrates", "multiple", "layers", "of", "sub", "-", "commands", "being", "handled", "by", "AutoCompleter" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/tab_autocomp_dynamic.py#L223-L231
230,277
python-cmd2/cmd2
examples/tab_autocompletion.py
TabCompleteExample.complete_media
def complete_media(self, text, line, begidx, endidx): """ Adds tab completion to media""" choices = {'actor': query_actors, # function 'director': TabCompleteExample.static_list_directors, # static list 'movie_file': (self.path_complete,) } completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser, self, arg_choices=choices) tokens, _ = self.tokens_for_completion(line, begidx, endidx) results = completer.complete_command(tokens, text, line, begidx, endidx) return results
python
def complete_media(self, text, line, begidx, endidx): choices = {'actor': query_actors, # function 'director': TabCompleteExample.static_list_directors, # static list 'movie_file': (self.path_complete,) } completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser, self, arg_choices=choices) tokens, _ = self.tokens_for_completion(line, begidx, endidx) results = completer.complete_command(tokens, text, line, begidx, endidx) return results
[ "def", "complete_media", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "choices", "=", "{", "'actor'", ":", "query_actors", ",", "# function", "'director'", ":", "TabCompleteExample", ".", "static_list_directors", ",", "# stati...
Adds tab completion to media
[ "Adds", "tab", "completion", "to", "media" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/tab_autocompletion.py#L378-L391
230,278
python-cmd2/cmd2
cmd2/history.py
HistoryItem.pr
def pr(self, script=False, expanded=False, verbose=False) -> str: """Represent a HistoryItem in a pretty fashion suitable for printing. If you pass verbose=True, script and expanded will be ignored :return: pretty print string version of a HistoryItem """ if verbose: ret_str = self.listformat.format(self.idx, str(self).rstrip()) if self != self.expanded: ret_str += self.ex_listformat.format(self.idx, self.expanded.rstrip()) else: if script: # display without entry numbers if expanded or self.statement.multiline_command: ret_str = self.expanded.rstrip() else: ret_str = str(self) else: # display a numbered list if expanded or self.statement.multiline_command: ret_str = self.listformat.format(self.idx, self.expanded.rstrip()) else: ret_str = self.listformat.format(self.idx, str(self).rstrip()) return ret_str
python
def pr(self, script=False, expanded=False, verbose=False) -> str: if verbose: ret_str = self.listformat.format(self.idx, str(self).rstrip()) if self != self.expanded: ret_str += self.ex_listformat.format(self.idx, self.expanded.rstrip()) else: if script: # display without entry numbers if expanded or self.statement.multiline_command: ret_str = self.expanded.rstrip() else: ret_str = str(self) else: # display a numbered list if expanded or self.statement.multiline_command: ret_str = self.listformat.format(self.idx, self.expanded.rstrip()) else: ret_str = self.listformat.format(self.idx, str(self).rstrip()) return ret_str
[ "def", "pr", "(", "self", ",", "script", "=", "False", ",", "expanded", "=", "False", ",", "verbose", "=", "False", ")", "->", "str", ":", "if", "verbose", ":", "ret_str", "=", "self", ".", "listformat", ".", "format", "(", "self", ".", "idx", ",",...
Represent a HistoryItem in a pretty fashion suitable for printing. If you pass verbose=True, script and expanded will be ignored :return: pretty print string version of a HistoryItem
[ "Represent", "a", "HistoryItem", "in", "a", "pretty", "fashion", "suitable", "for", "printing", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L35-L59
230,279
python-cmd2/cmd2
cmd2/history.py
History._zero_based_index
def _zero_based_index(self, onebased: Union[int, str]) -> int: """Convert a one-based index to a zero-based index.""" result = int(onebased) if result > 0: result -= 1 return result
python
def _zero_based_index(self, onebased: Union[int, str]) -> int: result = int(onebased) if result > 0: result -= 1 return result
[ "def", "_zero_based_index", "(", "self", ",", "onebased", ":", "Union", "[", "int", ",", "str", "]", ")", "->", "int", ":", "result", "=", "int", "(", "onebased", ")", "if", "result", ">", "0", ":", "result", "-=", "1", "return", "result" ]
Convert a one-based index to a zero-based index.
[ "Convert", "a", "one", "-", "based", "index", "to", "a", "zero", "-", "based", "index", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L76-L81
230,280
python-cmd2/cmd2
cmd2/history.py
History.append
def append(self, new: Statement) -> None: """Append a HistoryItem to end of the History list :param new: command line to convert to HistoryItem and add to the end of the History list """ new = HistoryItem(new) list.append(self, new) new.idx = len(self)
python
def append(self, new: Statement) -> None: new = HistoryItem(new) list.append(self, new) new.idx = len(self)
[ "def", "append", "(", "self", ",", "new", ":", "Statement", ")", "->", "None", ":", "new", "=", "HistoryItem", "(", "new", ")", "list", ".", "append", "(", "self", ",", "new", ")", "new", ".", "idx", "=", "len", "(", "self", ")" ]
Append a HistoryItem to end of the History list :param new: command line to convert to HistoryItem and add to the end of the History list
[ "Append", "a", "HistoryItem", "to", "end", "of", "the", "History", "list" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L83-L90
230,281
python-cmd2/cmd2
cmd2/history.py
History.get
def get(self, index: Union[int, str]) -> HistoryItem: """Get item from the History list using 1-based indexing. :param index: optional item to get (index as either integer or string) :return: a single HistoryItem """ index = int(index) if index == 0: raise IndexError('The first command in history is command 1.') elif index < 0: return self[index] else: return self[index - 1]
python
def get(self, index: Union[int, str]) -> HistoryItem: index = int(index) if index == 0: raise IndexError('The first command in history is command 1.') elif index < 0: return self[index] else: return self[index - 1]
[ "def", "get", "(", "self", ",", "index", ":", "Union", "[", "int", ",", "str", "]", ")", "->", "HistoryItem", ":", "index", "=", "int", "(", "index", ")", "if", "index", "==", "0", ":", "raise", "IndexError", "(", "'The first command in history is comman...
Get item from the History list using 1-based indexing. :param index: optional item to get (index as either integer or string) :return: a single HistoryItem
[ "Get", "item", "from", "the", "History", "list", "using", "1", "-", "based", "indexing", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L92-L104
230,282
python-cmd2/cmd2
cmd2/history.py
History.span
def span(self, span: str) -> List[HistoryItem]: """Return an index or slice of the History list, :param span: string containing an index or a slice :return: a list of HistoryItems This method can accommodate input in any of these forms: a -a a..b or a:b a.. or a: ..a or :a -a.. or -a: ..-a or :-a Different from native python indexing and slicing of arrays, this method uses 1-based array numbering. Users who are not programmers can't grok 0 based numbering. Programmers can usually grok either. Which reminds me, there are only two hard problems in programming: - naming - cache invalidation - off by one errors """ if span.lower() in ('*', '-', 'all'): span = ':' results = self.spanpattern.search(span) if not results: # our regex doesn't match the input, bail out raise ValueError('History indices must be positive or negative integers, and may not be zero.') sep = results.group('separator') start = results.group('start') if start: start = self._zero_based_index(start) end = results.group('end') if end: end = int(end) # modify end so it's inclusive of the last element if end == -1: # -1 as the end means include the last command in the array, which in pythonic # terms means to not provide an ending index. If you put -1 as the ending index # python excludes the last item in the list. end = None elif end < -1: # if the ending is smaller than -1, make it one larger so it includes # the element (python native indices exclude the last referenced element) end += 1 if start is not None and end is not None: # we have both start and end, return a slice of history result = self[start:end] elif start is not None and sep is not None: # take a slice of the array result = self[start:] elif end is not None and sep is not None: result = self[:end] elif start is not None: # there was no separator so it's either a posative or negative integer result = [self[start]] else: # we just have a separator, return the whole list result = self[:] return result
python
def span(self, span: str) -> List[HistoryItem]: if span.lower() in ('*', '-', 'all'): span = ':' results = self.spanpattern.search(span) if not results: # our regex doesn't match the input, bail out raise ValueError('History indices must be positive or negative integers, and may not be zero.') sep = results.group('separator') start = results.group('start') if start: start = self._zero_based_index(start) end = results.group('end') if end: end = int(end) # modify end so it's inclusive of the last element if end == -1: # -1 as the end means include the last command in the array, which in pythonic # terms means to not provide an ending index. If you put -1 as the ending index # python excludes the last item in the list. end = None elif end < -1: # if the ending is smaller than -1, make it one larger so it includes # the element (python native indices exclude the last referenced element) end += 1 if start is not None and end is not None: # we have both start and end, return a slice of history result = self[start:end] elif start is not None and sep is not None: # take a slice of the array result = self[start:] elif end is not None and sep is not None: result = self[:end] elif start is not None: # there was no separator so it's either a posative or negative integer result = [self[start]] else: # we just have a separator, return the whole list result = self[:] return result
[ "def", "span", "(", "self", ",", "span", ":", "str", ")", "->", "List", "[", "HistoryItem", "]", ":", "if", "span", ".", "lower", "(", ")", "in", "(", "'*'", ",", "'-'", ",", "'all'", ")", ":", "span", "=", "':'", "results", "=", "self", ".", ...
Return an index or slice of the History list, :param span: string containing an index or a slice :return: a list of HistoryItems This method can accommodate input in any of these forms: a -a a..b or a:b a.. or a: ..a or :a -a.. or -a: ..-a or :-a Different from native python indexing and slicing of arrays, this method uses 1-based array numbering. Users who are not programmers can't grok 0 based numbering. Programmers can usually grok either. Which reminds me, there are only two hard problems in programming: - naming - cache invalidation - off by one errors
[ "Return", "an", "index", "or", "slice", "of", "the", "History", "list" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L133-L198
230,283
python-cmd2/cmd2
cmd2/history.py
History.str_search
def str_search(self, search: str) -> List[HistoryItem]: """Find history items which contain a given string :param search: the string to search for :return: a list of history items, or an empty list if the string was not found """ def isin(history_item): """filter function for string search of history""" sloppy = utils.norm_fold(search) return sloppy in utils.norm_fold(history_item) or sloppy in utils.norm_fold(history_item.expanded) return [item for item in self if isin(item)]
python
def str_search(self, search: str) -> List[HistoryItem]: def isin(history_item): """filter function for string search of history""" sloppy = utils.norm_fold(search) return sloppy in utils.norm_fold(history_item) or sloppy in utils.norm_fold(history_item.expanded) return [item for item in self if isin(item)]
[ "def", "str_search", "(", "self", ",", "search", ":", "str", ")", "->", "List", "[", "HistoryItem", "]", ":", "def", "isin", "(", "history_item", ")", ":", "\"\"\"filter function for string search of history\"\"\"", "sloppy", "=", "utils", ".", "norm_fold", "(",...
Find history items which contain a given string :param search: the string to search for :return: a list of history items, or an empty list if the string was not found
[ "Find", "history", "items", "which", "contain", "a", "given", "string" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L200-L210
230,284
python-cmd2/cmd2
cmd2/history.py
History.regex_search
def regex_search(self, regex: str) -> List[HistoryItem]: """Find history items which match a given regular expression :param regex: the regular expression to search for. :return: a list of history items, or an empty list if the string was not found """ regex = regex.strip() if regex.startswith(r'/') and regex.endswith(r'/'): regex = regex[1:-1] finder = re.compile(regex, re.DOTALL | re.MULTILINE) def isin(hi): """filter function for doing a regular expression search of history""" return finder.search(hi) or finder.search(hi.expanded) return [itm for itm in self if isin(itm)]
python
def regex_search(self, regex: str) -> List[HistoryItem]: regex = regex.strip() if regex.startswith(r'/') and regex.endswith(r'/'): regex = regex[1:-1] finder = re.compile(regex, re.DOTALL | re.MULTILINE) def isin(hi): """filter function for doing a regular expression search of history""" return finder.search(hi) or finder.search(hi.expanded) return [itm for itm in self if isin(itm)]
[ "def", "regex_search", "(", "self", ",", "regex", ":", "str", ")", "->", "List", "[", "HistoryItem", "]", ":", "regex", "=", "regex", ".", "strip", "(", ")", "if", "regex", ".", "startswith", "(", "r'/'", ")", "and", "regex", ".", "endswith", "(", ...
Find history items which match a given regular expression :param regex: the regular expression to search for. :return: a list of history items, or an empty list if the string was not found
[ "Find", "history", "items", "which", "match", "a", "given", "regular", "expression" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L212-L226
230,285
python-cmd2/cmd2
examples/paged_output.py
PagedOutput.page_file
def page_file(self, file_path: str, chop: bool=False): """Helper method to prevent having too much duplicated code.""" filename = os.path.expanduser(file_path) try: with open(filename, 'r') as f: text = f.read() self.ppaged(text, chop=chop) except FileNotFoundError: self.perror('ERROR: file {!r} not found'.format(filename), traceback_war=False)
python
def page_file(self, file_path: str, chop: bool=False): filename = os.path.expanduser(file_path) try: with open(filename, 'r') as f: text = f.read() self.ppaged(text, chop=chop) except FileNotFoundError: self.perror('ERROR: file {!r} not found'.format(filename), traceback_war=False)
[ "def", "page_file", "(", "self", ",", "file_path", ":", "str", ",", "chop", ":", "bool", "=", "False", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "file_path", ")", "try", ":", "with", "open", "(", "filename", ",", "'r'", ...
Helper method to prevent having too much duplicated code.
[ "Helper", "method", "to", "prevent", "having", "too", "much", "duplicated", "code", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/paged_output.py#L17-L25
230,286
python-cmd2/cmd2
examples/paged_output.py
PagedOutput.do_page_wrap
def do_page_wrap(self, args: List[str]): """Read in a text file and display its output in a pager, wrapping long lines if they don't fit. Usage: page_wrap <file_path> """ if not args: self.perror('page_wrap requires a path to a file as an argument', traceback_war=False) return self.page_file(args[0], chop=False)
python
def do_page_wrap(self, args: List[str]): if not args: self.perror('page_wrap requires a path to a file as an argument', traceback_war=False) return self.page_file(args[0], chop=False)
[ "def", "do_page_wrap", "(", "self", ",", "args", ":", "List", "[", "str", "]", ")", ":", "if", "not", "args", ":", "self", ".", "perror", "(", "'page_wrap requires a path to a file as an argument'", ",", "traceback_war", "=", "False", ")", "return", "self", ...
Read in a text file and display its output in a pager, wrapping long lines if they don't fit. Usage: page_wrap <file_path>
[ "Read", "in", "a", "text", "file", "and", "display", "its", "output", "in", "a", "pager", "wrapping", "long", "lines", "if", "they", "don", "t", "fit", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/paged_output.py#L28-L36
230,287
python-cmd2/cmd2
examples/paged_output.py
PagedOutput.do_page_truncate
def do_page_truncate(self, args: List[str]): """Read in a text file and display its output in a pager, truncating long lines if they don't fit. Truncated lines can still be accessed by scrolling to the right using the arrow keys. Usage: page_chop <file_path> """ if not args: self.perror('page_truncate requires a path to a file as an argument', traceback_war=False) return self.page_file(args[0], chop=True)
python
def do_page_truncate(self, args: List[str]): if not args: self.perror('page_truncate requires a path to a file as an argument', traceback_war=False) return self.page_file(args[0], chop=True)
[ "def", "do_page_truncate", "(", "self", ",", "args", ":", "List", "[", "str", "]", ")", ":", "if", "not", "args", ":", "self", ".", "perror", "(", "'page_truncate requires a path to a file as an argument'", ",", "traceback_war", "=", "False", ")", "return", "s...
Read in a text file and display its output in a pager, truncating long lines if they don't fit. Truncated lines can still be accessed by scrolling to the right using the arrow keys. Usage: page_chop <file_path>
[ "Read", "in", "a", "text", "file", "and", "display", "its", "output", "in", "a", "pager", "truncating", "long", "lines", "if", "they", "don", "t", "fit", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/paged_output.py#L41-L51
230,288
python-cmd2/cmd2
cmd2/rl_utils.py
rl_force_redisplay
def rl_force_redisplay() -> None: # pragma: no cover """ Causes readline to display the prompt and input text wherever the cursor is and start reading input from this location. This is the proper way to restore the input line after printing to the screen """ if not sys.stdout.isatty(): return if rl_type == RlType.GNU: readline_lib.rl_forced_update_display() # After manually updating the display, readline asks that rl_display_fixed be set to 1 for efficiency display_fixed = ctypes.c_int.in_dll(readline_lib, "rl_display_fixed") display_fixed.value = 1 elif rl_type == RlType.PYREADLINE: # Call _print_prompt() first to set the new location of the prompt readline.rl.mode._print_prompt() readline.rl.mode._update_line()
python
def rl_force_redisplay() -> None: # pragma: no cover if not sys.stdout.isatty(): return if rl_type == RlType.GNU: readline_lib.rl_forced_update_display() # After manually updating the display, readline asks that rl_display_fixed be set to 1 for efficiency display_fixed = ctypes.c_int.in_dll(readline_lib, "rl_display_fixed") display_fixed.value = 1 elif rl_type == RlType.PYREADLINE: # Call _print_prompt() first to set the new location of the prompt readline.rl.mode._print_prompt() readline.rl.mode._update_line()
[ "def", "rl_force_redisplay", "(", ")", "->", "None", ":", "# pragma: no cover", "if", "not", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "return", "if", "rl_type", "==", "RlType", ".", "GNU", ":", "readline_lib", ".", "rl_forced_update_display", "(",...
Causes readline to display the prompt and input text wherever the cursor is and start reading input from this location. This is the proper way to restore the input line after printing to the screen
[ "Causes", "readline", "to", "display", "the", "prompt", "and", "input", "text", "wherever", "the", "cursor", "is", "and", "start", "reading", "input", "from", "this", "location", ".", "This", "is", "the", "proper", "way", "to", "restore", "the", "input", "...
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/rl_utils.py#L128-L147
230,289
python-cmd2/cmd2
cmd2/rl_utils.py
rl_get_point
def rl_get_point() -> int: # pragma: no cover """ Returns the offset of the current cursor position in rl_line_buffer """ if rl_type == RlType.GNU: return ctypes.c_int.in_dll(readline_lib, "rl_point").value elif rl_type == RlType.PYREADLINE: return readline.rl.mode.l_buffer.point else: return 0
python
def rl_get_point() -> int: # pragma: no cover if rl_type == RlType.GNU: return ctypes.c_int.in_dll(readline_lib, "rl_point").value elif rl_type == RlType.PYREADLINE: return readline.rl.mode.l_buffer.point else: return 0
[ "def", "rl_get_point", "(", ")", "->", "int", ":", "# pragma: no cover", "if", "rl_type", "==", "RlType", ".", "GNU", ":", "return", "ctypes", ".", "c_int", ".", "in_dll", "(", "readline_lib", ",", "\"rl_point\"", ")", ".", "value", "elif", "rl_type", "=="...
Returns the offset of the current cursor position in rl_line_buffer
[ "Returns", "the", "offset", "of", "the", "current", "cursor", "position", "in", "rl_line_buffer" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/rl_utils.py#L151-L162
230,290
python-cmd2/cmd2
cmd2/rl_utils.py
rl_make_safe_prompt
def rl_make_safe_prompt(prompt: str) -> str: # pragma: no cover """Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes. :param prompt: original prompt :return: prompt safe to pass to GNU Readline """ if rl_type == RlType.GNU: # start code to tell GNU Readline about beginning of invisible characters start = "\x01" # end code to tell GNU Readline about end of invisible characters end = "\x02" escaped = False result = "" for c in prompt: if c == "\x1b" and not escaped: result += start + c escaped = True elif c.isalpha() and escaped: result += c + end escaped = False else: result += c return result else: return prompt
python
def rl_make_safe_prompt(prompt: str) -> str: # pragma: no cover if rl_type == RlType.GNU: # start code to tell GNU Readline about beginning of invisible characters start = "\x01" # end code to tell GNU Readline about end of invisible characters end = "\x02" escaped = False result = "" for c in prompt: if c == "\x1b" and not escaped: result += start + c escaped = True elif c.isalpha() and escaped: result += c + end escaped = False else: result += c return result else: return prompt
[ "def", "rl_make_safe_prompt", "(", "prompt", ":", "str", ")", "->", "str", ":", "# pragma: no cover", "if", "rl_type", "==", "RlType", ".", "GNU", ":", "# start code to tell GNU Readline about beginning of invisible characters", "start", "=", "\"\\x01\"", "# end code to t...
Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes. :param prompt: original prompt :return: prompt safe to pass to GNU Readline
[ "Overcome", "bug", "in", "GNU", "Readline", "in", "relation", "to", "calculation", "of", "prompt", "length", "in", "presence", "of", "ANSI", "escape", "codes", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/rl_utils.py#L181-L210
230,291
python-cmd2/cmd2
examples/python_scripting.py
CmdLineApp._set_prompt
def _set_prompt(self): """Set prompt so it displays the current working directory.""" self.cwd = os.getcwd() self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET
python
def _set_prompt(self): self.cwd = os.getcwd() self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET
[ "def", "_set_prompt", "(", "self", ")", ":", "self", ".", "cwd", "=", "os", ".", "getcwd", "(", ")", "self", ".", "prompt", "=", "Fore", ".", "CYAN", "+", "'{!r} $ '", ".", "format", "(", "self", ".", "cwd", ")", "+", "Fore", ".", "RESET" ]
Set prompt so it displays the current working directory.
[ "Set", "prompt", "so", "it", "displays", "the", "current", "working", "directory", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/python_scripting.py#L35-L38
230,292
python-cmd2/cmd2
examples/python_scripting.py
CmdLineApp.postcmd
def postcmd(self, stop: bool, line: str) -> bool: """Hook method executed just after a command dispatch is finished. :param stop: if True, the command has indicated the application should exit :param line: the command line text for this command :return: if this is True, the application will exit after this command and the postloop() will run """ """Override this so prompt always displays cwd.""" self._set_prompt() return stop
python
def postcmd(self, stop: bool, line: str) -> bool: """Override this so prompt always displays cwd.""" self._set_prompt() return stop
[ "def", "postcmd", "(", "self", ",", "stop", ":", "bool", ",", "line", ":", "str", ")", "->", "bool", ":", "\"\"\"Override this so prompt always displays cwd.\"\"\"", "self", ".", "_set_prompt", "(", ")", "return", "stop" ]
Hook method executed just after a command dispatch is finished. :param stop: if True, the command has indicated the application should exit :param line: the command line text for this command :return: if this is True, the application will exit after this command and the postloop() will run
[ "Hook", "method", "executed", "just", "after", "a", "command", "dispatch", "is", "finished", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/python_scripting.py#L40-L49
230,293
python-cmd2/cmd2
examples/python_scripting.py
CmdLineApp.do_dir
def do_dir(self, args, unknown): """List contents of current directory.""" # No arguments for this command if unknown: self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help('dir') self._last_result = cmd2.CommandResult('', 'Bad arguments') return # Get the contents as a list contents = os.listdir(self.cwd) fmt = '{} ' if args.long: fmt = '{}\n' for f in contents: self.stdout.write(fmt.format(f)) self.stdout.write('\n') self._last_result = cmd2.CommandResult(data=contents)
python
def do_dir(self, args, unknown): # No arguments for this command if unknown: self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help('dir') self._last_result = cmd2.CommandResult('', 'Bad arguments') return # Get the contents as a list contents = os.listdir(self.cwd) fmt = '{} ' if args.long: fmt = '{}\n' for f in contents: self.stdout.write(fmt.format(f)) self.stdout.write('\n') self._last_result = cmd2.CommandResult(data=contents)
[ "def", "do_dir", "(", "self", ",", "args", ",", "unknown", ")", ":", "# No arguments for this command", "if", "unknown", ":", "self", ".", "perror", "(", "\"dir does not take any positional arguments:\"", ",", "traceback_war", "=", "False", ")", "self", ".", "do_h...
List contents of current directory.
[ "List", "contents", "of", "current", "directory", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/python_scripting.py#L97-L116
230,294
python-cmd2/cmd2
examples/table_display.py
pop_density
def pop_density(data: CityInfo) -> str: """Calculate the population density from the data entry""" if not isinstance(data, CityInfo): raise AttributeError("Argument to pop_density() must be an instance of CityInfo") return no_dec(data.get_population() / data.get_area())
python
def pop_density(data: CityInfo) -> str: if not isinstance(data, CityInfo): raise AttributeError("Argument to pop_density() must be an instance of CityInfo") return no_dec(data.get_population() / data.get_area())
[ "def", "pop_density", "(", "data", ":", "CityInfo", ")", "->", "str", ":", "if", "not", "isinstance", "(", "data", ",", "CityInfo", ")", ":", "raise", "AttributeError", "(", "\"Argument to pop_density() must be an instance of CityInfo\"", ")", "return", "no_dec", ...
Calculate the population density from the data entry
[ "Calculate", "the", "population", "density", "from", "the", "data", "entry" ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/table_display.py#L96-L100
230,295
python-cmd2/cmd2
examples/table_display.py
make_table_parser
def make_table_parser() -> cmd2.argparse_completer.ACArgumentParser: """Create a unique instance of an argparse Argument parser for processing table arguments. NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy of each other. For cases like that, you can create a function to return a unique instance of a parser, which is what is being done here. """ table_parser = cmd2.argparse_completer.ACArgumentParser() table_item_group = table_parser.add_mutually_exclusive_group() table_item_group.add_argument('-c', '--color', action='store_true', help='Enable color') table_item_group.add_argument('-f', '--fancy', action='store_true', help='Fancy Grid') table_item_group.add_argument('-s', '--sparse', action='store_true', help='Sparse Grid') return table_parser
python
def make_table_parser() -> cmd2.argparse_completer.ACArgumentParser: table_parser = cmd2.argparse_completer.ACArgumentParser() table_item_group = table_parser.add_mutually_exclusive_group() table_item_group.add_argument('-c', '--color', action='store_true', help='Enable color') table_item_group.add_argument('-f', '--fancy', action='store_true', help='Fancy Grid') table_item_group.add_argument('-s', '--sparse', action='store_true', help='Sparse Grid') return table_parser
[ "def", "make_table_parser", "(", ")", "->", "cmd2", ".", "argparse_completer", ".", "ACArgumentParser", ":", "table_parser", "=", "cmd2", ".", "argparse_completer", ".", "ACArgumentParser", "(", ")", "table_item_group", "=", "table_parser", ".", "add_mutually_exclusiv...
Create a unique instance of an argparse Argument parser for processing table arguments. NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy of each other. For cases like that, you can create a function to return a unique instance of a parser, which is what is being done here.
[ "Create", "a", "unique", "instance", "of", "an", "argparse", "Argument", "parser", "for", "processing", "table", "arguments", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/table_display.py#L144-L156
230,296
python-cmd2/cmd2
examples/table_display.py
TableDisplay.ptable
def ptable(self, rows, columns, grid_args, row_stylist): """Format tabular data for pretty-printing as a fixed-width table and then display it using a pager. :param rows: can be a list-of-lists (or another iterable of iterables), a two-dimensional NumPy array, or an Iterable of non-iterable objects :param columns: column headers and formatting options per column :param grid_args: argparse arguments for formatting the grid :param row_stylist: function to determine how each row gets styled """ if grid_args.color: grid = tf.AlternatingRowGrid(BACK_PRI, BACK_ALT) elif grid_args.fancy: grid = tf.FancyGrid() elif grid_args.sparse: grid = tf.SparseGrid() else: grid = None formatted_table = tf.generate_table(rows=rows, columns=columns, grid_style=grid, row_tagger=row_stylist) self.ppaged(formatted_table, chop=True)
python
def ptable(self, rows, columns, grid_args, row_stylist): if grid_args.color: grid = tf.AlternatingRowGrid(BACK_PRI, BACK_ALT) elif grid_args.fancy: grid = tf.FancyGrid() elif grid_args.sparse: grid = tf.SparseGrid() else: grid = None formatted_table = tf.generate_table(rows=rows, columns=columns, grid_style=grid, row_tagger=row_stylist) self.ppaged(formatted_table, chop=True)
[ "def", "ptable", "(", "self", ",", "rows", ",", "columns", ",", "grid_args", ",", "row_stylist", ")", ":", "if", "grid_args", ".", "color", ":", "grid", "=", "tf", ".", "AlternatingRowGrid", "(", "BACK_PRI", ",", "BACK_ALT", ")", "elif", "grid_args", "."...
Format tabular data for pretty-printing as a fixed-width table and then display it using a pager. :param rows: can be a list-of-lists (or another iterable of iterables), a two-dimensional NumPy array, or an Iterable of non-iterable objects :param columns: column headers and formatting options per column :param grid_args: argparse arguments for formatting the grid :param row_stylist: function to determine how each row gets styled
[ "Format", "tabular", "data", "for", "pretty", "-", "printing", "as", "a", "fixed", "-", "width", "table", "and", "then", "display", "it", "using", "a", "pager", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/table_display.py#L165-L184
230,297
python-cmd2/cmd2
examples/pirate.py
Pirate.postcmd
def postcmd(self, stop, line): """Runs right before a command is about to return.""" if self.gold != self.initial_gold: self.poutput('Now we gots {0} doubloons'.format(self.gold)) if self.gold < 0: self.poutput("Off to debtorrr's prison.") stop = True return stop
python
def postcmd(self, stop, line): if self.gold != self.initial_gold: self.poutput('Now we gots {0} doubloons'.format(self.gold)) if self.gold < 0: self.poutput("Off to debtorrr's prison.") stop = True return stop
[ "def", "postcmd", "(", "self", ",", "stop", ",", "line", ")", ":", "if", "self", ".", "gold", "!=", "self", ".", "initial_gold", ":", "self", ".", "poutput", "(", "'Now we gots {0} doubloons'", ".", "format", "(", "self", ".", "gold", ")", ")", "if", ...
Runs right before a command is about to return.
[ "Runs", "right", "before", "a", "command", "is", "about", "to", "return", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/pirate.py#L52-L59
230,298
python-cmd2/cmd2
examples/pirate.py
Pirate.do_sing
def do_sing(self, arg): """Sing a colorful song.""" color_escape = COLORS.get(self.songcolor, Fore.RESET) self.poutput(arg, color=color_escape)
python
def do_sing(self, arg): color_escape = COLORS.get(self.songcolor, Fore.RESET) self.poutput(arg, color=color_escape)
[ "def", "do_sing", "(", "self", ",", "arg", ")", ":", "color_escape", "=", "COLORS", ".", "get", "(", "self", ".", "songcolor", ",", "Fore", ".", "RESET", ")", "self", ".", "poutput", "(", "arg", ",", "color", "=", "color_escape", ")" ]
Sing a colorful song.
[ "Sing", "a", "colorful", "song", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/pirate.py#L82-L85
230,299
python-cmd2/cmd2
examples/pirate.py
Pirate.do_yo
def do_yo(self, args): """Compose a yo-ho-ho type chant with flexible options.""" chant = ['yo'] + ['ho'] * args.ho separator = ', ' if args.commas else ' ' chant = separator.join(chant) self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage))
python
def do_yo(self, args): chant = ['yo'] + ['ho'] * args.ho separator = ', ' if args.commas else ' ' chant = separator.join(chant) self.poutput('{0} and a bottle of {1}'.format(chant, args.beverage))
[ "def", "do_yo", "(", "self", ",", "args", ")", ":", "chant", "=", "[", "'yo'", "]", "+", "[", "'ho'", "]", "*", "args", ".", "ho", "separator", "=", "', '", "if", "args", ".", "commas", "else", "' '", "chant", "=", "separator", ".", "join", "(", ...
Compose a yo-ho-ho type chant with flexible options.
[ "Compose", "a", "yo", "-", "ho", "-", "ho", "type", "chant", "with", "flexible", "options", "." ]
b22c0bd891ed08c8b09df56df9d91f48166a5e2a
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/pirate.py#L93-L98