נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
27
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

כלי שורת פקודה עם argparseCommand-line tools with argparse

ארגומנטים, תתי-פקודות, עזרה אוטומטית.

Arguments, sub-commands, automatic help.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

פרסר ראשוןA first parser

תזכורת: מה ביקשוReminder: the task

כתבו build_parser() שמחזירה ArgumentParser עם ארגומנט חובה city ואופציה --days (int, ברירת מחדל 3). הדפיסו את התוצאה של parse_args(["Haifa", "--days", "5"]).

Write build_parser() returning an ArgumentParser with a required city and a --days option (int, default 3). Print the result of parse_args(["Haifa", "--days", "5"]).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import argparse

def build_parser():
    p = argparse.ArgumentParser(prog="weather")
    p.add_argument("city")
    p.add_argument("--days", type=int, default=3)
    return p

args = build_parser().parse_args(["Haifa", "--days", "5"])
print(args.city, args.days)
פלטOutput
Haifa 5

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

דגליםFlags

תזכורת: מה ביקשוReminder: the task

הוסיפו לפרסר של מחשבון טיפ: amount (float), --percent (int, ברירת מחדל 12) ודגל --round. tip(argv) מחזירה את הטיפ (amount × percent / 100), ואם יש --round מעגלת למספר שלם, אחרת ל-2 ספרות.

Build a tip calculator parser: amount (float), --percent (int, default 12) and a --round flag. tip(argv) returns the tip (amount × percent / 100), rounded to a whole number with --round, otherwise to 2 places.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import argparse

def tip(argv):
    p = argparse.ArgumentParser(prog="tip")
    p.add_argument("amount", type=float)
    p.add_argument("--percent", type=int, default=12)
    p.add_argument("--round", action="store_true")
    a = p.parse_args(argv)
    value = a.amount * a.percent / 100
    return round(value) if a.round else round(value, 2)

print(tip(["187.5"]), tip(["187.5", "--percent", "15", "--round"]))
פלטOutput
22.5 28

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

choices ושגיאותchoices and errors

תזכורת: מה ביקשוReminder: the task

כתבו convert(argv) עם ארגומנטים value (float) ו---to עם choices=["km", "mi"] (חובה). היא מחזירה את הערך מומר (km→mi: ×0.621371, mi→km: ÷0.621371) מעוגל ל-2. בחירה לא חוקית צריכה לגרום ל-SystemExit.

Write convert(argv) with value (float) and --to with choices=["km", "mi"] (required). It returns the converted value (km→mi: ×0.621371, mi→km: ÷0.621371) rounded to 2. An invalid choice must cause SystemExit.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import argparse

def convert(argv):
    p = argparse.ArgumentParser(prog="convert")
    p.add_argument("value", type=float)
    p.add_argument("--to", choices=["km", "mi"], required=True)
    a = p.parse_args(argv)
    factor = 0.621371
    return round(a.value * factor if a.to == "mi" else a.value / factor, 2)

print(convert(["42.195", "--to", "mi"]), convert(["26.2", "--to", "km"]))
פלטOutput
26.22 42.16

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

פקודות-משנהSubcommands

תזכורת: מה ביקשוReminder: the task

כתבו main(argv) לכלי רשימת מטלות עם פקודות add TEXT ו-done N (N מספר שלם). היא מחזירה מחרוזת: added: TEXT או done: #N. השתמשו ב-subparsers עם dest="cmd" ו-required=True.

Write main(argv) for a to-do tool with commands add TEXT and done N (N an integer). It returns a string: added: TEXT or done: #N. Use subparsers with dest="cmd" and required=True.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import argparse

def main(argv):
    p = argparse.ArgumentParser(prog="todo")
    sub = p.add_subparsers(dest="cmd", required=True)
    sub.add_parser("add").add_argument("text")
    sub.add_parser("done").add_argument("n", type=int)
    a = p.parse_args(argv)
    if a.cmd == "add":
        return f"added: {a.text}"
    return f"done: #{a.n}"

print(main(["add", "read Dune"]))
print(main(["done", "3"]))
פלטOutput
added: read Dune
done: #3

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 27: shelf add / list / searchShelf, step 27: shelf add / list / search

תזכורת: מה ביקשוReminder: the task

השלימו את run(argv, books) (books היא רשימה שמתעדכנת במקום, במקום קובץ): add TITLE AUTHOR [--pages N] מוסיפה ומחזירה added: TITLE; list [--sort title|pages] מחזירה מחרוזת עם שורה לכל ספר TITLE (PAGES); search TEXT מחזירה את הכותרות שמכילות את הטקסט (בלי רגישות לאותיות) בשורות, או no matches.

Complete run(argv, books) (books is a list updated in place, instead of a file): add TITLE AUTHOR [--pages N] adds and returns added: TITLE; list [--sort title|pages] returns a string with a line per book TITLE (PAGES); search TEXT returns matching titles (case-insensitive) one per line, or no matches.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
shelf.py
import argparse

def run(argv, books):
    p = argparse.ArgumentParser(prog="shelf")
    sub = p.add_subparsers(dest="cmd", required=True)
    a = sub.add_parser("add")
    a.add_argument("title")
    a.add_argument("author")
    a.add_argument("--pages", type=int, default=0)
    ls = sub.add_parser("list")
    ls.add_argument("--sort", choices=["title", "pages"], default="title")
    sub.add_parser("search").add_argument("text")
    args = p.parse_args(argv)
    if args.cmd == "add":
        books.append({"title": args.title, "author": args.author, "pages": args.pages})
        return f"added: {args.title}"
    if args.cmd == "list":
        return "\n".join(f"{b['title']} ({b['pages']})" for b in sorted(books, key=lambda b: b[args.sort]))
    hits = [b["title"] for b in books if args.text.lower() in b["title"].lower()]
    return "\n".join(hits) or "no matches"

books = []
print(run(["add", "Emma", "Jane Austen", "--pages", "474"], books))
print(run(["add", "Dune", "Frank Herbert", "--pages", "412"], books))
print(run(["list", "--sort", "pages"], books))
print(run(["search", "EM"], books))
פלטOutput
added: Emma
added: Dune
Dune (412)
Emma (474)
Emma

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

פרסר משלכםYour own parser

תזכורת: מה ביקשוReminder: the task

בלי argparse: כתבו parse(argv, spec) ש-spec שלה הוא מילון אופציות → ברירת מחדל (למשל {"--days": 3, "--loud": False}). ערך בוליאני בברירת המחדל = דגל; אחרת האופציה לוקחת את המילה הבאה ומומרת לטיפוס של ברירת המחדל. מילים שאינן אופציות נאספות ל-"_". אופציה לא מוכרת: ValueError.

Without argparse: write parse(argv, spec) whose spec is a dict option → default (e.g. {"--days": 3, "--loud": False}). A boolean default = a flag; otherwise the option takes the next word, converted to the default's type. Non-option words are collected into "_". An unknown option: ValueError.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def parse(argv, spec):
    out = {k.lstrip("-"): v for k, v in spec.items()}
    out["_"] = []
    i = 0
    while i < len(argv):
        word = argv[i]
        if word.startswith("--"):
            if word not in spec:
                raise ValueError(f"unknown option {word}")
            default = spec[word]
            if isinstance(default, bool):
                out[word[2:]] = True
            else:
                i += 1
                out[word[2:]] = type(default)(argv[i])
        else:
            out["_"].append(word)
        i += 1
    return out

print(parse(["Haifa", "--days", "5", "--loud", "extra"], {"--days": 3, "--loud": False, "--unit": "C"}))
פלטOutput
{'days': 5, 'loud': True, 'unit': 'C', '_': ['Haifa', 'extra']}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

main עם קוד יציאהmain with an exit code

תזכורת: מה ביקשוReminder: the task

כתבו main(argv, out, err) לכלי check-isbn שמקבל ISBN אחד או יותר ובודק ISBN-13: 13 ספרות (מותר -), וספרת ביקורת נכונה (סכום הספרות כשכל ספרה במקום אי-זוגי ×1 ובמקום זוגי ×3 מתחלק ב-10). לכל ISBN תקין כותבים ל-out OK <isbn>, ולשגוי ל-err BAD <isbn>. מחזירים 0 אם כולם תקינים, אחרת 1.

Write main(argv, out, err) for a check-isbn tool taking one or more ISBNs and checking ISBN-13: 13 digits (dashes allowed), and a correct check digit (the digit sum with odd positions ×1 and even positions ×3 divides by 10). For each valid ISBN write OK <isbn> to out, for invalid write BAD <isbn> to err. Return 0 if all are valid, else 1.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import argparse
import sys

def valid(isbn):
    d = isbn.replace("-", "")
    return len(d) == 13 and d.isdigit() and sum(int(c) * (3 if i % 2 else 1) for i, c in enumerate(d)) % 10 == 0

def main(argv, out=sys.stdout, err=sys.stderr):
    p = argparse.ArgumentParser(prog="check-isbn")
    p.add_argument("isbn", nargs="+")
    a = p.parse_args(argv)
    code = 0
    for isbn in a.isbn:
        if valid(isbn):
            print(f"OK {isbn}", file=out)
        else:
            print(f"BAD {isbn}", file=err)
            code = 1
    return code

print("exit:", main(["978-0441172719", "9780141439587"], err=sys.stdout))
print("exit:", main(["9780441172710"], err=sys.stdout))
פלטOutput
OK 978-0441172719
OK 9780141439587
exit: 0
BAD 9780441172710
exit: 1

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich