כלי שורת פקודה עם argparseCommand-line tools with argparse
ארגומנטים, תתי-פקודות, עזרה אוטומטית.
Arguments, sub-commands, automatic help.
01sys.argv: המילים שאחרי השםsys.argv: the words after the name
כלים אמיתיים מקבלים הוראות בשורה אחת: git commit -m "...". כל מה שכותבים אחרי שם הסקריפט מגיע לרשימה sys.argv כארגומנטים, תמיד כמחרוזות. הנה סקריפט קטן, והרצה אמיתית שלו בטרמינל:
Real tools take instructions in one line: git commit -m "...". Whatever you write after the script name arrives in the list sys.argv as arguments, always as strings. Here's a small script, and a real run of it in the terminal:
import sys
print(sys.argv)
print("args:", len(sys.argv) - 1)python3 show_args.py add "The Hobbit" --pages 310['show_args.py', 'add', 'The Hobbit', '--pages', '310'] args: 4
ארגומנטים הם כמו הזמנה בטלפון לפיצרייה: "משפחתית, זיתים, בלי בצל". הסקריפט שומע את המילים ומחליט מה לעשות.
Arguments are like phoning in a pizza order: "family size, olives, no onion". The script hears the words and decides what to do.
קוראים את sys.argv[1] כשהמשתמש לא כתב כלום.
Reading sys.argv[1] when the user typed nothing.
python3 hello.pyTraceback (most recent call last):
File "/Users/you/python-course/hello.py", line 2, in <module>
print("Hello,", sys.argv[1])
~~~~~~~~^^^
IndexError: list index out of rangeIndexError: list index out of range: אין ארגומנט ראשון. במקום לבדוק ביד כל מקרה, משתמשים ב-argparse, שמסביר למשתמש מה חסר.IndexError: list index out of range: there's no first argument. Instead of checking every case by hand, use argparse, which tells the user what's missing.sys.argv הוא רשימה של מחרוזות. כאן מדמים אותה.
sys.argv is a list of strings. Here we pretend one.
argv = ["greet.py", "Noa", "3"]
name = argv[1]
times = int(argv[2])
for _ in range(times):
print("Hi", name)Hi Noa Hi Noa Hi Noa
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02argparseargparse
argparse עושה את העבודה הקשה: מגדירים מה התוכנית מקבלת, והוא מפרק את המילים, ממיר טיפוסים, מכניס ברירות מחדל, ומחזיר אובייקט args עם תכונה לכל ארגומנט. אופציות מתחילות ב---, ודגל הוא אופציה בלי ערך.
argparse does the hard work: you define what the program accepts, and it splits the words, converts types, fills in defaults, and returns an args object with an attribute per argument. Options start with --, and a flag is an option without a value.
import argparse
parser = argparse.ArgumentParser(description="Say hello")
parser.add_argument("name", help="who to greet")
parser.add_argument("--times", type=int, default=1, help="how many times")
parser.add_argument("--shout", action="store_true", help="use capital letters")
args = parser.parse_args()
text = f"Hello, {args.name}!"
if args.shout:
text = text.upper()
for _ in range(args.times):
print(text)python3 greet.py Noa
python3 greet.py Noa --times 2 --shout$ python3 greet.py Noa Hello, Noa! $ python3 greet.py Noa --times 2 --shout HELLO, NOA! HELLO, NOA!
argparse הוא כמו מלצר מקצועי: הוא מקבל את ההזמנה, מוודא שהיא הגיונית, ושואל "כמה?" כשחסר פרט, לפני שהיא מגיעה למטבח.
argparse is like a professional waiter: takes the order, checks it makes sense, and asks "how many?" when a detail is missing, before it reaches the kitchen.
ערך שאינו מספר לאופציה עם type=int.
A non-number for an option with type=int.
python3 greet.py Noa --times manyusage: greet.py [-h] [--times TIMES] [--shout] name greet.py: error: argument --times: invalid int value: 'many'
greet.py: error: argument --times: invalid int value: 'many': argparse עצר ואמר בדיוק מה לא בסדר, לפני שהקוד שלנו רץ בכלל.greet.py: error: argument --times: invalid int value: 'many': argparse stopped and said exactly what's wrong, before our code even ran.03--help בחינם--help for free
כל מה שכתבתם ב-help= וב-description= הופך למסך עזרה מסודר, בלי שורת קוד נוספת. כך כלי משרת גם אתכם בעוד חודש, כששכחתם את השמות המדויקים.
Everything you wrote in help= and description= becomes a tidy help screen, without another line of code. That way a tool serves you a month from now too, when you've forgotten the exact names.
python3 greet.py --helpusage: greet.py [-h] [--times TIMES] [--shout] name Say hello positional arguments: name who to greet options: -h, --help show this help message and exit --times TIMES how many times --shout use capital letters
--help הוא כמו הוראות ההפעלה שמודבקות על המכונה עצמה: לא צריך לחפש את החוברת.
--help is like the operating instructions stuck on the machine itself: no hunting for the manual.
שוכחים ארגומנט חובה.
Leaving out a required argument.
python3 greet.py --shoutusage: greet.py [-h] [--times TIMES] [--shout] name greet.py: error: the following arguments are required: name
greet.py: error: the following arguments are required: name: argparse מראה את שורת השימוש ומה חסר. התוכנית נגמרת עם קוד 2.greet.py: error: the following arguments are required: name: argparse shows the usage line and what's missing. The program ends with code 2.04פקודות-משנהSubcommands
כלים גדולים בנויים מפקודות-משנה: git add, git commit. ב-argparse יוצרים subparsers, ולכל פקודה parser משלה עם ארגומנטים משלה. הטריק set_defaults(func=cmd_add) שומר בתוך args את הפונקציה שצריך להריץ, וכך main נשאר קצר. הנה כלי המדף המלא (shelf.py):
Big tools are built from subcommands: git add, git commit. In argparse you create subparsers, each command with its own parser and arguments. The trick set_defaults(func=cmd_add) stores in args the function to run, so main stays short. Here's the full shelf tool (shelf.py):
import argparse
import json
import sys
from pathlib import Path
DATA = Path("shelf.json")
def load():
return json.loads(DATA.read_text(encoding="utf-8")) if DATA.exists() else []
def save(books):
DATA.write_text(json.dumps(books, indent=2, ensure_ascii=False), encoding="utf-8")
def cmd_add(args):
books = load()
books.append({"title": args.title, "author": args.author, "pages": args.pages})
save(books)
print(f"added: {args.title}")
def cmd_list(args):
books = sorted(load(), key=lambda b: b[args.sort])
for b in books:
print(f"{b['title']:<12} {b['author']:<16} {b['pages']:>4}")
def cmd_search(args):
hits = [b for b in load() if args.text.lower() in (b["title"] + b["author"]).lower()]
for b in hits:
print(b["title"])
if not hits:
print("no matches", file=sys.stderr)
return 1
return 0
def build_parser():
p = argparse.ArgumentParser(prog="shelf", description="Your personal library")
sub = p.add_subparsers(dest="command", required=True)
a = sub.add_parser("add", help="add a book")
a.add_argument("title")
a.add_argument("author")
a.add_argument("--pages", type=int, default=0)
a.set_defaults(func=cmd_add)
ls = sub.add_parser("list", help="list books")
ls.add_argument("--sort", choices=["title", "author", "pages"], default="title")
ls.set_defaults(func=cmd_list)
s = sub.add_parser("search", help="search title or author")
s.add_argument("text")
s.set_defaults(func=cmd_search)
return p
def main(argv=None):
args = build_parser().parse_args(argv)
return args.func(args) or 0
if __name__ == "__main__":
sys.exit(main())python3 shelf.py add Dune "Frank Herbert" --pages 412
python3 shelf.py add Matilda "Roald Dahl" --pages 240
python3 shelf.py add Emma "Jane Austen" --pages 474
python3 shelf.py list --sort pages
python3 shelf.py search dahl$ python3 shelf.py add Dune "Frank Herbert" --pages 412 added: Dune $ python3 shelf.py add Matilda "Roald Dahl" --pages 240 added: Matilda $ python3 shelf.py add Emma "Jane Austen" --pages 474 added: Emma $ python3 shelf.py list --sort pages Matilda Roald Dahl 240 Dune Frank Herbert 412 Emma Jane Austen 474 $ python3 shelf.py search dahl Matilda
פקודות-משנה הן כמו שלט מגירות בארון כלים: "מברגים", "פטישים". כל מגירה מסודרת לפי הצורך שלה.
Subcommands are like the labels on a tool chest's drawers: "screwdrivers", "hammers". Each drawer is organised for its own needs.
בחירה שאינה ברשימת ה-choices.
A choice that isn't in the choices list.
python3 shelf.py list --sort yearusage: shelf list [-h] [--sort {title,author,pages}]
shelf list: error: argument --sort: invalid choice: 'year' (choose from 'title', 'author', 'pages')shelf list: error: argument --sort: invalid choice: 'year': choices= מגביל ערכים, ו-argparse מציג את האפשרויות החוקיות.shelf list: error: argument --sort: invalid choice: 'year': choices= limits the values, and argparse shows the valid ones.05קוד יציאה ו-stderrExit codes and stderr
כל תוכנית מחזירה קוד יציאה. סקריפטים אחרים (וגם GitHub Actions) בודקים אותו: 0 אומר שהכול עבר. הודעות שגיאה כותבים ל-stderr, כך שאם מישהו מפנה את הפלט לקובץ, השגיאות עדיין מופיעות על המסך. בטרמינל, echo $? מראה את הקוד של הפקודה האחרונה:
Every program returns an exit code. Other scripts (and GitHub Actions) check it: 0 means all went well. Write error messages to stderr, so if someone redirects output to a file, errors still show on screen. In the terminal, echo $? shows the last command's code:
python3 shelf.py search zzz
echo "exit code: $?"
python3 shelf.py search dune > found.txt
echo "exit code: $?"
cat found.txt$ python3 shelf.py search zzz no matches $ echo "exit code: $?" exit code: 1 $ python3 shelf.py search dune > found.txt $ echo "exit code: $?" exit code: 0 $ cat found.txt Dune
קוד יציאה הוא כמו אגודל למעלה או למטה בסוף משימה: מי שמחכה בתור לא צריך לקרוא את כל הדוח כדי לדעת אם להמשיך.
An exit code is like a thumbs-up or thumbs-down at the end of a task: whoever's waiting doesn't need to read the whole report to know whether to continue.
מחזירים קוד יציאה עם print במקום sys.exit.
"Returning" an exit code with print instead of sys.exit.
import subprocess, sys
r = subprocess.run([sys.executable, "-c", "print(1)"])
assert r.returncode == 1, f"the program printed 1 but its exit code is {r.returncode}"1
Traceback (most recent call last):
File "/Users/you/python-course/exit.py", line 3, in <module>
assert r.returncode == 1, f"the program printed 1 but its exit code is {r.returncode}"
^^^^^^^^^^^^^^^^^
AssertionError: the program printed 1 but its exit code is 0AssertionError: the program printed 1 but its exit code is 0: print רק כותב טקסט. קוד יציאה קובעים עם sys.exit(1).AssertionError: the program printed 1 but its exit code is 0: print just writes text. Set the exit code with sys.exit(1).06לבדוק כלי שורת פקודהTesting a command-line tool
הטריק שהופך כלי לבדיק: main(argv=None). כש-argv הוא None, argparse קורא את sys.argv האמיתי; בבדיקה מעבירים רשימה. כך בודקים את כל הכלי עם pytest בלי לפתוח טרמינל. גם בתרגילים כאן תשתמשו בזה:
The trick that makes a tool testable: main(argv=None). When argv is None, argparse reads the real sys.argv; in a test you pass a list. That way you test the whole tool with pytest without opening a terminal. The exercises here use it too:
import argparse
def build_parser():
p = argparse.ArgumentParser(prog="timer")
p.add_argument("minutes", type=int)
p.add_argument("--label", default="focus")
return p
args = build_parser().parse_args(["25", "--label", "reading"])
print(args.minutes + 5, args.label)
print(vars(build_parser().parse_args(["10"])))30 reading
{'minutes': 10, 'label': 'focus'}לבדוק עם רשימה זה כמו לבדוק מכונת משקאות עם מטבעות דמה: אותה מכונה, בלי לבזבז כסף אמיתי.
Testing with a list is like testing a vending machine with token coins: same machine, without spending real money.
בדיקה שקוראת ל-parse_args() בלי רשימה.
A test that calls parse_args() without a list.
import argparse, sys
sys.argv = ["pytest", "-q"]
p = argparse.ArgumentParser(prog="timer")
p.add_argument("minutes", type=int)
p.parse_args()usage: timer [-h] minutes timer: error: the following arguments are required: minutes
SystemExit: 2: בלי רשימה, argparse קורא את sys.argv של pytest (כאן -q), לא מוצא את minutes ויוצא. מעבירים רשימה מפורשת: parse_args(["25"]).SystemExit: 2: without a list, argparse reads pytest's own sys.argv (here -q), finds no minutes and exits. Pass an explicit list: parse_args(["25"]).סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.