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 coffeeWas this page helpful?
Let us know how we did
