Understanding argument parsing with argparse in Python
Question: I am now starting exploring Python, and was testing how arguments can be
passed to a script with "argparse". The way I wrote a sample script was as
following, where arguments passed through flags -i and -o are compulsory and
flag -u is optional:

    
    
    #!/usr/bin/python
    
    import sys
    import argparse
    
    ## set usage options and define arguments
    usage = "usage: %prog [options]"
    parser = argparse.ArgumentParser(usage)
    
    parser.add_argument("-i",  action="store", dest="input", help="input file")
    parser.add_argument("-o",  action="store", dest="output", help="output file")
    parser.add_argument("-u", action="store_true", dest="isunfolded", default=False, help="optional flag")
    
    args = parser.parse_args()
    
    print len(sys.argv)  
    if len(sys.argv) < 2:
    #        parser.print_help()   
            print 'Incorrect number of params'
            exit()
    else:
            print "Correct number of params: ", len(sys.argv)
    

Running this script:

    
    
    > ./test-args.py -i a -o b
    

prints:

    
    
    5
    Correct number of params:  5
    

I understand the printing statement in the if conditional (5 is higher than
2), however, after reading the argparse documentation
(<https://docs.python.org/3/library/argparse.html>) I still don't quite
understand why -i and -o flags are counted as arguments. This behaviour seems
to be quite different from e.g. perl Getopt::Std, which I'm more used to.

So, the question is what is the best way of parsing arguments in Python and to
evaluate the presence of mandatory arguments (without using required=True)


Answer: It gives you 5 because `sys.argv` contains the raw input passed to python as
arguments (the script name and 4 arguments).

You can see `argparse` as an abstraction for this, so once you use it, you can
forget about `sys.argv`. In most cases it is better not to mix these two
methods.

`argparse` its a nice way to handle arguments, I don't quite get why you don't
want to use the `required` option when that's exactly the way to go. Another
alternative is to parse the `sys.argv` yourself (regex maybe?) and drop
`argparse` altogether.

