Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to get all default values from argparse

When module optparse is used, then I can get all default values for all command line arguments like this:

import optparse

if __name__ == '__main__':
    parser = optparse.OptionParser(usage='pokus --help')
    parser.add_option("-d", "--debug", action='store_true', dest="debug",
                      default=False, help='Enabling debugging.')
    options, args = parser.parse_args()
    print(parser.defaults)

Since optparse is deprecated it is wise to rewrite your code to use argparse module. However I can't find any way how to get all default values of all command line arguments added to parser object:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(usage='pokus --help')
    parser.add_argument("-d", "--debug", action='store_true', dest='debug',
                        default=False, help='Enabling debugging.')   
    args = parser.parse_args()
    # <---- How to get default values for all arguments here?
    # Not: vars(args)

I want to get all default values when I run program with (./app.py -d) or without any command line argument (./app.py).

like image 876
JiriHnidek Avatar asked Jun 14 '17 10:06

JiriHnidek


1 Answers

Somewhat late to the party, but this is a function (with bonus unittest) that I've used in a couple of cases to get hold of the default arguments without having to parse first (parsing first can be annoying if you have required arguments that aren't available yet)

def get_argparse_defaults(parser):
    defaults = {}
    for action in parser._actions:
        if not action.required and action.dest != "help":
            defaults[action.dest] = action.default
    return defaults

def get_argparse_required(parser):
    required = []
    for action in parser._actions:
        if action.required:
            required.append(action.dest)
    return required

parser = argparse.ArgumentParser()
optional_defaults_dict = get_argparse_defaults(parser)
required_list = get_argparse_required(parser)

class TestDefaultArgs(unittest.TestCase):

    def test_get_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('positional_arg')
        parser.add_argument('--required_option', required=True)
        parser.add_argument('--optional_with_default', required=False, default="default_value")
        parser.add_argument('--optional_without_default', required=False)

        required_args = get_argparse_required(parser)
        self.assertEqual(['positional_arg', 'required_option'], required_args)


        default_args = get_argparse_defaults(parser)
        self.assertEqual({'optional_with_default': 'default_value',
                          'optional_without_default': None},
                         default_args)
like image 146
David258 Avatar answered Nov 05 '22 19:11

David258