Skip to content

Using Arguments with argparse

diagram what argparse does before your code runs mermaid
The parser is not just a way to read sys.argv -- it validates, converts and, when something is wrong, exits. That last part surprises people: a bad value does not raise an exception you can catch in the ordinary way, it prints usage and terminates with status 2.

It gives your scripts:

  • --help
  • typed arguments
  • clear usage patterns
argparse_example.py
import argparse
 
 
def build_parser():
    p = argparse.ArgumentParser(description="Example automation CLI")
    p.add_argument("--dry-run", action="store_true", help="Don’t change files")
    p.add_argument("--source", required=True, help="Source folder")
    return p
 
 
def main():
    args = build_parser().parse_args()
    print("source:", args.source)
    print("dry_run:", args.dry_run)
 
 
if __name__ == "__main__":
    main()

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading