Skip to content

Using Arguments with argparse

Why argparse

It gives your scripts:

  • --help--help
  • typed arguments
  • clear usage patterns

Example

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()
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()

πŸ§ͺ Try It Yourself

Exercise 1 – List Files with os.listdir

Exercise 2 – Join Paths with os.path.join

Exercise 3 – Write and Read a File

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did