def show_pager(formatted_text, encoding='UTF-8'): """ Print a large text to the terminal using a pager. :param formatted_text: The text to print to the terminal (a string). :param encoding: The name of the text encoding used to encode the formatted text if the formatted text is a Unicode string (a string). The use of a pager helps to avoid the wall of text effect where the user has to scroll up to see where the output began (not very user friendly). If :data:`sys.stdout` is not connected to a terminal (see :func:`connected_to_terminal()`) then the text is printed directly without invoking a pager. If the given text contains ANSI escape sequences the command ``less --RAW-CONTROL-CHARS`` is used, otherwise ``$PAGER`` is used (if ``$PAGER`` isn't set the command ``less`` is used). """ if connected_to_terminal(sys.stdout): if ANSI_CSI in formatted_text: pager_command = ['less', '--RAW-CONTROL-CHARS'] else: pager_command = [os.environ.get('PAGER', 'less')] if is_unicode(formatted_text): formatted_text = formatted_text.encode(encoding) pager = subprocess.Popen(pager_command, stdin=subprocess.PIPE) pager.communicate(input=formatted_text) else: print(formatted_text)
def show_pager(formatted_text, encoding=DEFAULT_ENCODING): """ Print a large text to the terminal using a pager. :param formatted_text: The text to print to the terminal (a string). :param encoding: The name of the text encoding used to encode the formatted text if the formatted text is a Unicode string (a string, defaults to :data:`DEFAULT_ENCODING`). When :func:`connected_to_terminal()` returns :data:`True` a pager is used to show the text on the terminal, otherwise the text is printed directly without invoking a pager. The use of a pager helps to avoid the wall of text effect where the user has to scroll up to see where the output began (not very user friendly). Refer to :func:`get_pager_command()` for details about the command line that's used to invoke the pager. """ if connected_to_terminal(): command_line = get_pager_command(formatted_text) pager = subprocess.Popen(command_line, stdin=subprocess.PIPE) if is_unicode(formatted_text): formatted_text = formatted_text.encode(encoding) pager.communicate(input=formatted_text) else: output(formatted_text)