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

Though Python comes with (a few) 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('--'):
        elif x.startswith('-'):
    return [flags, named, args]

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

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

Output example:

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