0

Is there any equivalent in Click (https://click.palletsprojects.com/) for the fromfile_prefix_chars option that is available in the argparse library?

I sometimes have lot of arguments to hand over to a Click based application and - especially when using file paths - may reach some Windows limits. Therefore, when using argparse, the solution was to use the fromfile_prefix_chars option. However, we will move to Click now.

Is there any equivalent available or is it possible to replicate this functionality in Click?

Many thanks for your help.

Best regards, gpxricky

gpxricky
  • 1
  • 1

1 Answers1

0

Yes, there is. You can use default_map to override defaults

You could do it in various ways:

Pass file with python dictionary

You could parse a python dictionary with ast.literal_eval:

import ast
import click
import os


@click.group()
@click.pass_context
def main(ctx):
    config = os.getenv('CLICK_CONFIG_FILE', './click_config')
    if os.path.exists(config):
        with open(config) as f:
            ctx.default_map = ast.literal_eval(f.read())


@main.command()
@click.option("--param", default=2)
def test(param):
    print(param)


if __name__ == '__main__':
     main()

Let's assume we have two config files:

# click_config
{
    'test': {'param': 3}
}
# config_click
{
    'test': {'param': 4}
}

Now, here is what happens when you call your command:

# Highest precedence, overrides any config file
$ python main.py test --param 1
1
# No config file exists. Takes the default, defined in the command
$ python main.py test 
2
# Default config file exists, overrides default to 3
$ python main.py test 
3
# Custom config file provided, overrides default to 4
$ CLICK_CONFIG_FILE=./config_click python main.py test 
4
# Again. The command line has the highest precedence:
$ CLICK_CONFIG_FILE=./config_click python main.py test --param 1
1

Pass yaml config file

You could follow this answer here to do the same thing with yaml.

Pass ini file

Here you can find an article explaining how to adopt ini files.

Use an extension (the config format is again ini)

Check this out.

wankata
  • 855
  • 4
  • 12