Using Arguments with argparse
flowchart TD
A["sys.argv"] --> B["parser.parse_args()"]
B --> C{"a required positional missing?"}
C -->|yes| D["print usage, SystemExit(2)"]
C -->|no| E{"does each value fit its type=?"}
E -->|no| D
E -->|yes| F["build a Namespace"]
F --> G["--dry-run becomes ns.dry_run"]
F --> H["-n '3' becomes the int 3"]
G --> I["your script runs, with values already validated"]
H --> I
J["-h / --help"] --> K["print help, SystemExit(0)"]
Why argparse
Section titled “Why argparse”It gives your scripts:
--help- typed arguments
- clear usage patterns
Example
Section titled “Example”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
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading