Skip to content

Instantly share code, notes, and snippets.

@cellularmitosis
Last active April 10, 2025 18:37
Show Gist options
  • Save cellularmitosis/eb6c3343212e83a6a41bdd59252c8999 to your computer and use it in GitHub Desktop.
Save cellularmitosis/eb6c3343212e83a6a41bdd59252c8999 to your computer and use it in GitHub Desktop.
A simple Python function to parse command line arguments

Blog 2025/4/10

<- previous | index | next ->

A simple Python function to parse command line arguments

Python's argparse has a bit of a learning curve, and for simple programs it can be a bit cumbersome.

Here's a simple function which parses flags, options and args. Easy to understand, simple to extend.

#!/usr/bin/env python3

import sys

def parse_command_line():
    """Parse the command line, returning flags, options, and args.
    Flags don't expect an argument, e.g. '--verbose'.
    Options expect an argument, e.g. '--output file.txt'.
    Args are everything left over after parsing flags and options.
    """
    # flags don't expect an argument:
    flag_names = set(['--verbose','--help'])
    # options expect a argument:
    option_names = set(['--output','--target'])
    flags = set()
    options = {}
    args = []
    i = 1
    while i < len(sys.argv):
        arg = sys.argv[i]
        if arg in flag_names:
            flags.add(arg)
        elif arg in option_names:
            i += 1
            if i >= len(sys.argv):
                sys.stderr.write(f"Error: option '{arg}' expects an argument.\n")
                sys.exit(1)
            arg2 = sys.argv[i]
            options[arg] = arg2
        else:
            args.append(arg)
        i += 1
        continue
    return (flags, options, args)

if __name__ == "__main__":
    (flags, options, args) = parse_command_line()
    print(f"flags: {flags}")
    print(f"options: {options}")
    print(f"args: {args}")

demo:

$ ./cmdline.py input1.c --verbose --output output.txt input2.c input3.c
flags: {'--verbose'}
options: {'--output': 'output.txt'}
args: ['input1.c', 'input2.c', 'input3.c']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment