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

חזרה למפגשBack
PythonPython

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

מפגש 27: ארגומנטים, תתי-פקודות, עזרה אוטומטית.Session 27: Arguments, sub-commands, automatic help.

מה נעשה היוםToday's plan

  • argvargv
  • argparseargparse
  • עזרהHelp
  • פקודותCommands
  • יציאהExit
  • בדיקהTesting
נושאTopic 1

argvargv

sys.argv: המילים שאחרי השםsys.argv: the words after the name

  • sys.argv[0] הוא שם הסקריפטsys.argv[0] is the script name
  • כל השאר: מחרוזותThe rest: strings
  • ידני = שבירBy hand = fragile

אנלוגיהAnalogy

ארגומנטים הם כמו הזמנה בטלפון לפיצרייה: "משפחתית, זיתים, בלי בצל". הסקריפט שומע את המילים ומחליט מה לעשות.Arguments are like phoning in a pizza order: "family size, olives, no onion". The script hears the words and decides what to do.
נושאTopic 2

argparseargparse

argparseargparse

  • ארגומנט חובה: add_argument("name")Required: add_argument("name")
  • אופציה: --times עם type=int ו-defaultOption: --times with type=int and default
  • דגל: action="store_true"Flag: action="store_true"

אנלוגיהAnalogy

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.
נושאTopic 3

עזרהHelp

--help בחינם--help for free

  • -h / --help נוצר לבד-h / --help is made for you
  • help= לכל ארגומנטhelp= for each argument
  • description= למעלהdescription= at the top

אנלוגיהAnalogy

--help הוא כמו הוראות ההפעלה שמודבקות על המכונה עצמה: לא צריך לחפש את החוברת.--help is like the operating instructions stuck on the machine itself: no hunting for the manual.
נושאTopic 4

פקודותCommands

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

  • add_subparsers(dest="command")add_subparsers(dest="command")
  • לכל פקודה ארגומנטים משלהEach command has its own arguments
  • set_defaults(func=...) מחבר פקודה לפונקציהset_defaults(func=...) links a command to a function

אנלוגיהAnalogy

פקודות-משנה הן כמו שלט מגירות בארון כלים: "מברגים", "פטישים". כל מגירה מסודרת לפי הצורך שלה.Subcommands are like the labels on a tool chest's drawers: "screwdrivers", "hammers". Each drawer is organised for its own needs.
נושאTopic 5

יציאהExit

קוד יציאה ו-stderrExit codes and stderr

אנלוגיהAnalogy

קוד יציאה הוא כמו אגודל למעלה או למטה בסוף משימה: מי שמחכה בתור לא צריך לקרוא את כל הדוח כדי לדעת אם להמשיך.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.
נושאTopic 6

בדיקהTesting

לבדוק כלי שורת פקודהTesting a command-line tool

  • main(argv=None) מקבל רשימהmain(argv=None) takes a list
  • parse_args(["add", "Dune"]) בלי טרמינלparse_args(["add", "Dune"]) without a terminal
  • pytest על הלוגיקהpytest on the logic

אנלוגיהAnalogy

לבדוק עם רשימה זה כמו לבדוק מכונת משקאות עם מטבעות דמה: אותה מכונה, בלי לבזבז כסף אמיתי.Testing with a list is like testing a vending machine with token coins: same machine, without spending real money.

טעות נפוצהCommon mistake

test_cli.py
import argparse, sys
sys.argv = ["pytest", "-q"]
p = argparse.ArgumentParser(prog="timer")
p.add_argument("minutes", type=int)
p.parse_args()
מה Python עונהWhat Python says
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"]).

sys.argv[0] הוא שם הסקריפטsys.argv[0] is the script name

כל השאר: מחרוזותThe rest: strings

ידני = שבירBy hand = fragile

ארגומנט חובה: add_argument("name")Required: add_argument("name")

אופציה: --times עם type=int ו-defaultOption: --times with type=int and default

דגל: action="store_true"Flag: action="store_true"

-h / --help נוצר לבד-h / --help is made for you

help= לכל ארגומנטhelp= for each argument

description= למעלהdescription= at the top

add_subparsers(dest="command")add_subparsers(dest="command")

לכל פקודה ארגומנטים משלהEach command has its own arguments

set_defaults(func=...) מחבר פקודה לפונקציהset_defaults(func=...) links a command to a function

0 = הצליח, אחר = נכשל0 = success, anything else = failure

sys.exit(main())sys.exit(main())

הודעות שגיאה ל-stderrError messages to stderr

main(argv=None) מקבל רשימהmain(argv=None) takes a list

parse_args(["add", "Dune"]) בלי טרמינלparse_args(["add", "Dune"]) without a terminal

מה למדנוWhat we learned

  • sys.argv[0] הוא שם הסקריפטsys.argv[0] is the script name
  • ארגומנט חובה: add_argument("name")Required: add_argument("name")
  • -h / --help נוצר לבד-h / --help is made for you
  • add_subparsers(dest="command")add_subparsers(dest="command")
  • 0 = הצליח, אחר = נכשל0 = success, anything else = failure
  • main(argv=None) מקבל רשימהmain(argv=None) takes a list

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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