diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2019-06-16 14:41:49 -0400 |
---|---|---|
committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2019-06-16 14:41:49 -0400 |
commit | a9ce49bfc46610e03d62a1e4afbfdde9f5b0f7ee (patch) | |
tree | 14124a6a69003fccecdcc1d37e4f48c1f3630b63 /cmd2/utils.py | |
parent | c08f48e254be65b9899f4597cd88f479c6442646 (diff) | |
download | cmd2-git-a9ce49bfc46610e03d62a1e4afbfdde9f5b0f7ee.tar.gz |
Added center_text() utility function for centering text in a terminal along with unit tests for it
This function isn't used yet, but I have plans to use it when improving the output of transcript testing
Diffstat (limited to 'cmd2/utils.py')
-rw-r--r-- | cmd2/utils.py | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/cmd2/utils.py b/cmd2/utils.py index c8fb4aff..3e28641d 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -5,6 +5,7 @@ import collections import glob import os import re +import shutil import subprocess import sys import threading @@ -377,6 +378,21 @@ def get_exes_in_path(starts_with: str) -> List[str]: return list(exes_set) +def center_text(msg: str, *, pad: str = ' ') -> str: + """Centers text horizontally for display within the current terminal, optionally padding both sides. + + :param msg: message to display in the center + :param pad: (optional) if provided, the first character will be used to pad both sides of the message + :return: centered message, optionally padded on both sides with pad_char + """ + term_width = shutil.get_terminal_size().columns + surrounded_msg = ' {} '.format(msg) + if not pad: + pad = ' ' + fill_char = pad[:1] + return surrounded_msg.center(term_width, fill_char) + + class StdSim(object): """ Class to simulate behavior of sys.stdout or sys.stderr. |