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.

2 comments:

  1. I’ve been browsing on-line greater than three hours today, but I never discovered any attention-grabbing article like yours. It is beautiful worth sufficient for me. Personally, if all webmasters and bloggers made good content material as you did, the net will be a lot more helpful than ever before.

    Online Training in Chennai

    ReplyDelete
  2. your trends and solutions are really super thus i got more information from your blog and it is really helpful and i got more information thanks for sharing these valuable information.

    Informatica Training in Chennai

    ReplyDelete