def perror(msg: Any, *, end: str = '\n', apply_style: bool = True) -> None: """Override perror() method from `cmd2.Cmd` Use colorama native approach for styling the text instead of `cmd2.ansi` methods :param msg: message to print (anything convertible to a str with '{}'.format() is OK) :param end: string appended after the end of the message, default a newline :param apply_style: If True, then ansi.style_error will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True. """ if apply_style: final_msg = "{}{}{}{}".format(Fore.RED, Back.YELLOW, msg, Style.RESET_ALL) else: final_msg = "{}".format(msg) ansi.ansi_aware_write(sys.stderr, final_msg + end)
import sys from cmd2 import ansi, style if len(sys.argv) > 1: directory = sys.argv[1] print('Using specified directory: {!r}'.format(directory)) else: directory = 'foobar' print('Using default directory: {!r}'.format(directory)) # Keep track of where we started - NOTE: cwd was added to self.py_locals dictionary so we can access it original_dir = cwd() # Try to change to the specified directory cd_result = app('cd {}'.format(directory)) # Conditionally do something based on the results of the last command if cd_result: print('\nContents of directory {!r}:'.format(directory)) dir_result = app('dir -l') print('{}\n'.format(dir_result.data)) # Change back to where we were print('Changing back to original directory: {!r}'.format(original_dir)) app('cd {}'.format(original_dir)) else: # cd command failed, print a warning print('Failed to change directory to {!r}'.format(directory)) ansi.ansi_aware_write(sys.stderr, style(cd_result.stderr, fg='red'))