Skip to content

Instantly share code, notes, and snippets.

@abalter
Last active May 30, 2023 11:51
Show Gist options
  • Save abalter/605773b34a68bb370bf84007ee55a130 to your computer and use it in GitHub Desktop.
Save abalter/605773b34a68bb370bf84007ee55a130 to your computer and use it in GitHub Desktop.
Python Aargparsing Examples

http://stackoverflow.com/a/30493366/188963

Other answers do mention that argparse is the way to go for new Python, but do not give usage examples. For completeness, here is a short summary of how to use argparse:

1) Initialize

import argparse

# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')

2) Add Arguments

# Required positional argument
parser.add_argument('pos_arg', type=int,
                    help='A required integer positional argument')

# Optional positional argument
parser.add_argument('opt_pos_arg', type=int, nargs='?',
                    help='An optional integer positional argument')

# Optional argument
parser.add_argument('--opt_arg', type=int,
                    help='An optional integer argument')

# Switch
parser.add_argument('--switch', action='store_true',
                    help='A boolean switch')

3) Parse

args = parser.parse_args()

4) Access

print("Argument values:")
print(args.pos_arg)
print(args.opt_pos_arg)
print(args.opt_arg)
print(args.switch)

5) Check Values

if args.pos_arg > 10:
    parser.error("pos_arg cannot be larger than 10")

##Usage

Correct use:

$ ./app 1 2 --opt_arg 3 --switch

Argument values:
1
2
3
True

Incorrect arguments:

$ ./app foo 2 --opt_arg 3 --switch
usage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
app: error: argument pos_arg: invalid int value: 'foo'

$ ./app 11 2 --opt_arg 3
Argument values:
11
2
3
False
usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
convert: error: pos_arg cannot be larger than 10

Full help:

$ ./app -h

usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]

Optional app description

positional arguments:
  pos_arg            A required integer positional argument
  opt_pos_arg        An optional integer positional argument

optional arguments:
  -h, --help         show this help message and exit
  --opt_arg OPT_ARG  An optional integer argument
  --switch           A boolean switch

http://stackoverflow.com/questions/24180527/argparse-required-arguments-listed-under-optional-arguments

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT

Foo

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Output file name

required named arguments:
  -i INPUT, --input INPUT
                        Input file name

http://sw32.com/the-meaning-of-action-store_true-and-store_false-in-python-argparse-module/

If the correspond parameter does not exist, the value is opposite of store_true/store_false. If the parameter exists, the value is store_true/store_false. So we use use store_true in the most situation. return false if parameter doesn’t exist; return true if parameter exists. That’s what we want!

def fun4():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--p1', action='store_true')
    parser.add_argument('--p2', action='store_true')
    parser.add_argument('--p3', action='store_false')
    cmd =  '--p1'
    args = parser.parse_args(cmd.split())
    print(args)
    if args.p1:
        print('p1 good')
    else:
        print('p1 bad')
        
    
    
print('\n========Go!==========\n')
fun4()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment