Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output color using argparse in python if any errors happen?

Tags:

python-3.x

Is there a way to make argparse to output error or warning with colors of red or orange?

I know there are some OS standard colors can be used directly, like "\033[38;5;196m" (red-like) or "\033[38;5;208m" (orange-like), but is there a way to use them or something similar into argparse? Messages with different colors are really helpful for people to recognize if any thing happens.

like image 647
delusionxb Avatar asked Nov 07 '17 10:11

delusionxb


People also ask

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is action Store_true in Argparse?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.

How do I make Argparse argument optional in Python?

Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .

What does Argparse parse_args return?

Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.


1 Answers

I just thought of the same question and decided I would poke around the argparse module because the output was kinda weird (On Linux, the words 'error' and 'usage' are usually capitalized, and I also wanted errors to be printed in bold red throughout my program, including when command line arguments were checked.) Here is my code for some nicer looking output, tested using Python 3.6.3 (I really just included more colors as an example here, when in practice you should only need the bold red for errors).

import argparse
import sys
from gettext import gettext

class ColoredArgParser(argparse.ArgumentParser):

    # color_dict is a class attribute, here we avoid compatibility
    # issues by attempting to override the __init__ method
    # RED : Error, GREEN : Okay, YELLOW : Warning, Blue: Help/Info 
    color_dict = {'RED' : '1;31', 'GREEN' : '1;32', 
                  'YELLOW' : '1;33', 'BLUE' : '1;36'}

    def print_usage(self, file = None):
        if file is None:
            file = sys.stdout
        self._print_message(self.format_usage()[0].upper() + 
                            self.format_usage()[1:],
                            file, self.color_dict['YELLOW'])

    def print_help(self, file = None):
        if file is None:
            file = sys.stdout
        self._print_message(self.format_help()[0].upper() +
                            self.format_help()[1:],
                            file, self.color_dict['BLUE'])

    def _print_message(self, message, file = None, color = None):
        if message:
            if file is None:
                file = sys.stderr
            # Print messages in bold, colored text if color is given.
            if color is None:
                file.write(message)
            else:
                # \x1b[ is the ANSI Control Sequence Introducer (CSI)
                file.write('\x1b[' + color + 'm' + message.strip() + '\x1b[0m\n')

    def exit(self, status = 0, message = None):
        if message:
            self._print_message(message, sys.stderr, self.color_dict['RED'])
        sys.exit(status)

    def error(self, message):
        self.print_usage(sys.stderr)
        args = {'prog' : self.prog, 'message': message}
        self.exit(2, gettext('%(prog)s: Error: %(message)s\n') % args)
like image 112
Nicholas Stommel Avatar answered Sep 30 '22 12:09

Nicholas Stommel