Pylerno
English

Command-line interfaces

Provide discoverable options and clear failure behavior.

On this page

The concept

argparse defines an interface in one place, generates --help, converts values, and reports invalid syntax. A useful CLI names its options clearly and validates domain rules after parsing. stdout is for normal results; stderr is for diagnostics. Exit code zero indicates success, while nonzero codes allow scripts to detect failure.

The greeting example is intentionally small. Run it with --name Sara --times 2, then try --times 0 and --help. The final TaskFlow project extends the same boundary design to persistent data and subcommands.

Worked example

Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.

sh
python3 08_professional_workflow/67_cli_design/lesson.py
python
import argparse


def main():
    parser = argparse.ArgumentParser(description="A greeting program")
    parser.add_argument("--name", default="Guest", help="User name")
    parser.add_argument("--times", type=int, default=1, help="Number of repetitions")
    args = parser.parse_args()
    if not 1 <= args.times <= 10:
        parser.error("--times must be between 1 and 10")
    for _ in range(args.times):
        print(f"Hello {args.name}")


if __name__ == "__main__":
    main()

Trace the result

  1. The parser declares defaults and numeric conversion.
  2. The explicit range check rejects repetition counts outside 1 through 10.
  3. Only validated input reaches the greeting loop.
text
Hello Guest
Line-by-line walkthrough

Line 1: import argparse

Load argparse (command-line parsing and usage errors). Importing makes these names available; it is not a call to every function in the module.

Lines 4–12: def main():

Define the function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.

Line 5: parser = argparse.ArgumentParser(description="A greeting program")

Evaluate argparse.ArgumentParser(description='A greeting program'), then bind or update parser with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Line 6: parser.add_argument("--name", default="Guest", help="User name")

Call parser.add_argument with the displayed arguments. This call may have an effect even when its return value is not assigned.

Line 7: parser.add_argument("--times", type=int, default=1, help="Number of repetitions")

Call parser.add_argument with the displayed arguments. This call may have an effect even when its return value is not assigned.

Line 8: args = parser.parse_args()

Evaluate parser.parse_args(), then bind or update args with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Lines 9–10: if not 1 <= args.times <= 10:

Evaluate not 1 <= args.times <= 10. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.

Line 10: parser.error("--times must be between 1 and 10")

Call parser.error with the displayed arguments. This call may have an effect even when its return value is not assigned.

Lines 11–12: for _ in range(args.times):

Obtain each item from range(args.times) and bind it to _ before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Line 12: print(f"Hello {args.name}")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 15–16: if __name__ == "__main__":

Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.

Line 16: main()

Call main with the displayed arguments. This call may have an effect even when its return value is not assigned.

Common mistake

An ordinary usage mistake should produce a helpful message, not an unexplained traceback or a false success exit.

Check your understanding

Which argparse type converts the command-line value "7" into an integer?

Choose one answer

Search documentation

Share this page