<< Back to posts

Python Argparse Cheatsheet

Posted on June 16, 2023 • Tags: python cli argparse

Basic argparse template for a Python 3 program named program.py:

Template

import argparse

def parse_args(args):
  parser = argparse.ArgumentParser(
      description="This is my program"
  )

  # Required positional args (no '--')
  parser.add_argument("path_to_file", type=str, default="/file/path/", help="Path to logs")
  
  # Optional keyword args (yes '--')
  ## String
  parser.add_argument("--str_flag", type=str, default='random', help="Split strategy")
  ## Float
  parser.add_argument("--float_flag", type=float, default=0.4, help="Percent in train split")
  ## Boolean flag
  parser.add_argument("--bool_flag", action='store_true', default=False, help="If set, run eval")

  # Required keyword args (yes '--' and `required=True`)
  ## String
  parser.add_argument("--required_flag", required=True, type=str, default='name', help="Run name")

  # Multiple choice
  choices = [ 'low', 'medium', 'high']
  parser.add_argument("--choice", choices=choices, default='yes', help="Confidence")



if __name__ == '__main__':
  parse_args(args)
  ...

Running

Run program.py from the command line as follows:

python3 program.py logs.txt \
  --str_flag random \
  --float_flag 0.8 \
  --bool_flag \
  --required_flag trial_10 \
  --choice medium

Usage

Later in program.py, we can use the arguments as follows:

path_to_file: str = args.path_to_file # "logs.txt"
split_strat: str = args.str_flag # "random"
train_percent: float = args.float_flag # 0.8
is_eval: bool = args.bool_flag # True
name: str = args.required_flag # "trial_10"
choice: str = args.choice # "medium"

References

  • https://mkaz.blog/code/python-argparse-cookbook/