Some Python Examples
← prev | next →     Top-level ToC     /parsing-args.html     (printable version)

Though Python comes with standard modules to do this, here’s a qnd way to parse args to your script:

import sys

def parse_args(stuff):
    """Returns a 3-element tuple of flags (ex. "-v"), named options ("--foo=bar"),
and other args passed to the script ("a b c"). The named options get parsed out
as pairs ("--foo=bar" --> `["foo", "bar"]`)."""
    flags = []
    named = []
    args  = []
    for x in stuff:
        if x.startswith('--'):
            named.append(x[2:].split('='))
        elif x.startswith('-'):
            flags.append(x[1:])
        else:
            args.append(x)
    return [flags, named, args]

f, n, a = parse_args(sys.argv[1:])

print('flags:', f)
print('named:', n)
print('args: ', a)

Output example:

$ ./foo.py -a -b --foo=bar --baz=moo aa bb
flags: ['a', 'b']
named: [['foo', 'bar'], ['baz', 'moo']]
args:  ['aa', 'bb']