Python Arguments With Argparse module: The Template I Use for CLI Scripting

steps

  1. import argparse module
  2. use if __name__ == "__main__": main() pattern to execute from terminal
  3. parse arguments within the main() function that has no parameters as all
  4. define an init_argparse() function:
  5. create a parser object by calling argparse.ArgumentParser()
  6. declare one or more arguments with parser.add_argument("--<long_param_name>")
  7. return parser
  8. parse args by creating an args object by calling parser.parse_args()
  9. define a function proper with param1, param2, ...
  10. call function_proper with params being assigned as attributes of an args object. e.g. function_proper(param1=args.param1, param2=args.param2)
  11. within a shell call the module with named arguments:
  • e.g. python foobar.py --param1="foo" --param2=="bar"

--

--

--

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Basics of Kotlin- Part 2

How to calculate the WIP limits of your Kanban board

Volunteering in 2022

You’re Being Watched!

How to Become a Mobile App Developer (A Complete Newbie Guide)

How to Scrape Fantasy Premier League (FPL) Player Data on a Mac using the API, Python and Cron

Chapter 10 — Customer Needs IV: Outcomes

Castcle Sprint Update #7

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

The Parameters And Usage Of Ranges In Python

10 Useful String Operations in Python

Reverse-Engineered “Wordle” with 10 lines of Python

6 Ways You Can Get Keys From a Python Dictionary