Friday, February 20, 2015

Use both optional arguments and positional arguments in Python apps

Normally python scripts accept arguments from command line, and in Python you can achieve that by using ArgumentParser.

e.g. Your Python script named MyApp and it accepts 4 arguments (foo1, foo2, foo3 and foo4) from command line, then your code will be something like:

parser.add_argument(
            '--foo1',
            help="xxxxx"
        )
parser.add_argument(
            '--foo2',
            help="xxxxxx"
        )
parser.add_argument(
            '--foo3',
            help="xxxxxx"
        )
parser.add_argument(
            '--foo4',
            help="xxxxxx"
        )

And all these 4 arguments are optional, if in the case of foo1 is required, you can set required=True.

parser.add_argument(
            '--foo1',
            required=True,
            help="xxxxx"
        )

This works, but its not a good solution (more details can be found https://docs.python.org/3/library/argparse.html#required).

So, set foo1 as positional argument might be better, and you can do like:

parser.add_argument(
            'foo1',
            help="xxxxx"
        )
parser.add_argument(
            '--foo2',
            help="xxxxxx"
        )
parser.add_argument(
            '--foo3',
            help="xxxxxx"
        )
parser.add_argument(
            '--foo4',
            help="xxxxxx"
        )

Then your python script can be ran: python -m MyApp value1 --foo2=value2 --foo3=value3 --foo4=value4.