נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • sys.argv[0] הוא שם הסקריפטsys.argv[0] is the script name
  • כל השאר: מחרוזותThe rest: strings
  • ארגומנט חובה: add_argument("name")Required: add_argument("name")
  • אופציה: --times עם type=int ו-defaultOption: --times with type=int and default
  • -h / --help נוצר לבד-h / --help is made for you
  • help= לכל ארגומנטhelp= for each argument
  • add_subparsers(dest="command")add_subparsers(dest="command")
  • לכל פקודה ארגומנטים משלהEach command has its own arguments
  • 0 = הצליח, אחר = נכשל0 = success, anything else = failure

מונחיםTerms

  • ארגומנט שורת פקודהcommand-line argument: מילה שכותבים אחרי שם הסקריפט בטרמינל: python3 greet.py Noa. מגיעה לתוכנית ב-sys.argv.A word written after the script's name in the terminal: python3 greet.py Noa. Reaches the program in sys.argv.
  • argparseargparse: מודול סטנדרטי שמגדיר אילו ארגומנטים התוכנית מקבלת, ממיר טיפוסים, ויוצר --help אוטומטית.A standard module that defines which arguments a program takes, converts types, and makes --help automatically.
  • דגל (flag)flag: אופציה בלי ערך שמדליקה משהו: --shout. ב-argparse: action="store_true".An option without a value that switches something on: --shout. In argparse: action="store_true".
  • פקודת-משנהsubcommand: מילה ראשונה שבוחרת פעולה, כמו git commit או shelf add.A first word choosing an action, like git commit or shelf add.
  • קוד יציאהexit code: מספר שתוכנית מחזירה למערכת כשהיא נגמרת: 0 = הצליח, אחר = נכשל. sys.exit(1).A number a program hands back to the system when it ends: 0 = success, anything else = failure. sys.exit(1).
  • stderrstderr: ערוץ פלט נפרד להודעות שגיאה, כדי שלא יתערבבו בתוצאות. print(..., file=sys.stderr).A separate output channel for error messages, so they don't mix with results. print(..., file=sys.stderr).

Cheatsheet

argvargv
import sys

print(sys.argv)
print("args:", len(sys.argv) - 1)
argparseargparse
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()
פקודותCommands
import argparse
import json
import sys
from pathlib import Path

DATA = Path("shelf.json")
בדיקהTesting
import argparse

def build_parser():
    p = argparse.ArgumentParser(prog="timer")
    p.add_argument("minutes", type=int)
    p.add_argument("--label", default="focus")
    return p

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorמחזירים קוד יציאה עם print במקום sys.exit."Returning" an exit code with print instead of sys.exit.AssertionError: 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).
timerבדיקה שקוראת ל-parse_args() בלי רשימה.A test that calls parse_args() without a list.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"]).

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