Python Intermediate Lesson 9: Command-Line Tools With argparse

Python Intermediate Lesson 9: Command-Line Tools With argparse 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 9 of 10

Advertisement

Instead of editing the script every time someone wants a different filter, give it options:

python sales.py --status Overdue
python sales.py --rep Neha --month 2026-07
python sales.py --help
import argparse
ap = argparse.ArgumentParser(description="Sales totals from sales.csv")
ap.add_argument("--status", choices=["Paid", "Pending", "Overdue"])
ap.add_argument("--rep")
ap.add_argument("--month", help="YYYY-MM")
a = ap.parse_args()
if a.status: rows = [r for r in rows if r["status"] == a.status]

argparse writes the --help text and rejects invalid choices with a clear message, for free.

Run it on a schedule

  1. Make run-report.bat: cd /d D:\sales-report && .venv\Scripts\python.exe report.py --month %1 >> log.txt 2>&1
  2. Task Scheduler > Create Basic Task > Monthly > Start a program > the .bat file.
  3. Tick “Run whether user is logged on or not” for unattended runs.
πŸ’‘ Put the main code in def main(argv=None) and call main() under if __name__ == "__main__":. Then you can test it with main(["--status", "Overdue"]), as the lesson script does.

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 4 KB)

  • 🐍
    Lesson 9 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 1 KB
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 253 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *