PeterB
PeterB

Reputation: 166

How to convert python 3.6 config file into argparser code

I have a file.conf that I load into python with ConfigParser(). The conf file has the usual format (using opencv also):

[decorations]
timestamp_fg= 255,255,255
timestamp_bg= 0,0,0
font_scale = 1.5

The conf file is large. I would like a way to automatically generate python code for ArgumentParser() so I can single author the conf file, gen some code, and remove code I don't need:

parser = argparse.ArgumentParser()
parser.add_argument("-c","--config", help="full pathname to config file", type=str)
# etc.

I didn't find such a utility, but still only been in python for few months.

Upvotes: 1

Views: 373

Answers (2)

ti7
ti7

Reputation: 18846

While I'm not absolutely certain, I'd do one of two things

  • Create a function that accepts an ConfigParser object and converts it into Argparse's equivalent

    • amend tool
    • run normally
    • run the magic part that dumps the now parsed ConfigParser object as a big string of the Argparse commands in a new file for your viewing pleasure
  • Write a regex for it and do a direct conversion

    • write a new script
    • pass in path of config
    • run the magic part that dumps the now parsed ConfigParser object as a big string of the Argparse commands in a new file for your viewing pleasure

Simply using string.format() is probably fine

# make a template for your Argparse options
GENERIC_COMMAND = """\
parser.add_argument(
        "--{long_name}", "-{short_name}",
        default="{default}",
        help="help_text")"""

...
# parse ConfigParser to commands
commands = [
    {
        "long_name": "argumentA",
    },
    {
        "long_name": "argumentB",
        "help_text": "Do Thing B"
    },
...
]

commands_to_write_to_file = []
for command in commands:
    try:
        commands_to_write_to_file.append(
            GENERIC_COMMAND.format(**command))  # expand command to args
    except Exception as ex:
        print("Caught Exception".format(repr(ex)))

# to view your commands, you can write commands to file
# or try your luck with the help command
with open(out.txt, "w") as fh:
    fh.write("\n\n".join(commands_to_write_to_file))

Neither of these are great solutions, but I expect will get 90% of the work done easily, leaving good logging and yourself to find and convert the remaining few oddball commands.

Once you're happy with the output, you can get rid of your dump logic and fill argparse arguments directly with 'em instead

for command in commands:
    argparse.add_argument(**command)

Upvotes: 1

Wyrmwood
Wyrmwood

Reputation: 3599

I would checkout ConfigArgParse. That library allows for

a combination of command line args, config files, hard-coded defaults, and in some cases, environment variables

Upvotes: 0

Related Questions