From c0fe871b33dcef3f862490461dd46547aa55f72a Mon Sep 17 00:00:00 2001 From: liuyang1 Date: Wed, 13 Jun 2018 18:56:54 +0800 Subject: [PATCH] fix except case - when redirect stdout to pipe but not tty, it throw exception. - when have no content, it throw exception. - remove reductant newline at end of file --- bin/cheat | 7 ++++--- cheat/utils.py | 10 ++++++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/bin/cheat b/bin/cheat index 9213639..0b8cc7c 100755 --- a/bin/cheat +++ b/bin/cheat @@ -34,6 +34,7 @@ Examples: cheat -s ssh """ +from __future__ import print_function # require the dependencies from cheat import sheets, sheet from cheat.utils import colorize @@ -50,7 +51,7 @@ if __name__ == '__main__': # list cheatsheets elif options['--list']: - print(sheets.list()) + print(sheets.list(), end="") # create/edit cheatsheet elif options['--edit']: @@ -58,8 +59,8 @@ if __name__ == '__main__': # search among the cheatsheets elif options['--search']: - print(colorize(sheets.search(options['']))) + print(colorize(sheets.search(options[''])), end="") # print the cheatsheet else: - print(colorize(sheet.read(options['']))) + print(colorize(sheet.read(options[''])), end="") diff --git a/cheat/utils.py b/cheat/utils.py index e8c850d..8b3d540 100644 --- a/cheat/utils.py +++ b/cheat/utils.py @@ -10,6 +10,9 @@ def colorize(sheet_content): # only colorize if so configured if not 'CHEATCOLORS' in os.environ: return sheet_content + # only colorize if stdout is tty + if not sys.stdout.isatty(): + return sheet_content try: from pygments import highlight @@ -20,8 +23,11 @@ def colorize(sheet_content): except ImportError: return sheet_content - first_line = sheet_content.splitlines()[0] - lexer = get_lexer_by_name('bash') + lines = sheet_content.splitlines() + if len(lines) == 0: + return "" + first_line = lines[0] + lexer = get_lexer_by_name('bash') if first_line.startswith('```'): sheet_content = '\n'.join(sheet_content.split('\n')[1:-2]) try: