נבנה על ידיBuilt by Ariel Yohimovich
sys.argv[0] הוא שם הסקריפטsys.argv[0] is the script namegit 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:add_argument("name")Required: add_argument("name")--times עם type=int ו-defaultOption: --times with type=int and defaultaction="store_true"Flag: action="store_true"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.-h / --help נוצר לבד-h / --help is made for youhelp= לכל ארגומנטhelp= for each argumentdescription= למעלהdescription= at the tophelp= וב-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.add_subparsers(dest="command")add_subparsers(dest="command")set_defaults(func=...) מחבר פקודה לפונקציהset_defaults(func=...) links a command to a functiongit 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):sys.exit(main())sys.exit(main())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:main(argv=None) מקבל רשימהmain(argv=None) takes a listparse_args(["add", "Dune"]) בלי טרמינלparse_args(["add", "Dune"]) without a terminalmain(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, sys
sys.argv = ["pytest", "-q"]
p = argparse.ArgumentParser(prog="timer")
p.add_argument("minutes", type=int)
p.parse_args()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 nameadd_argument("name")Required: add_argument("name")--times עם type=int ו-defaultOption: --times with type=int and defaultaction="store_true"Flag: action="store_true"-h / --help נוצר לבד-h / --help is made for youhelp= לכל ארגומנטhelp= for each argumentdescription= למעלהdescription= at the topadd_subparsers(dest="command")add_subparsers(dest="command")set_defaults(func=...) מחבר פקודה לפונקציהset_defaults(func=...) links a command to a functionsys.exit(main())sys.exit(main())main(argv=None) מקבל רשימהmain(argv=None) takes a listparse_args(["add", "Dune"]) בלי טרמינלparse_args(["add", "Dune"]) without a terminalsys.argv[0] הוא שם הסקריפטsys.argv[0] is the script nameadd_argument("name")Required: add_argument("name")-h / --help נוצר לבד-h / --help is made for youadd_subparsers(dest="command")add_subparsers(dest="command")main(argv=None) מקבל רשימהmain(argv=None) takes a listנבנה על ידיBuilt by Ariel Yohimovich