Course outline

Python / Reliable programs / Lesson 14

Command-line interfaces and validation

Parse and validate Python command-line arguments with argparse.

About 18 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Parse typed arguments with argparse.
  • Test parsing separately from domain rules.
  • Define and test argument defaults, validation, output channels, and process statuses.
  • Separate a pure calculation test from process-level command wiring verification.

Define the interface

A command-line interface is an input boundary. Separate parsing from the calculation so a caller can test the computation without starting a process. Specify which arguments are required, how optional flags change behavior, and which inputs are rejected. A clear help message and predictable failure are part of the contract. Avoid reading unrelated global state in the core function; pass the validated values explicitly.

Parse arguments

ArgumentParser describes the accepted inputs. A positional argument is normally required, while an option has a name such as --count. The type parameter converts text before the program consumes it; choices can restrict the converted value. The example passes an explicit list to parse_args so it is deterministic in this lesson. In a real command, calling parse_args without that list reads the process arguments.

python Fixed argument example
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("count", type=int)
parser.add_argument("--unit", type=int, default=2)
args = parser.parse_args(["3", "--unit", "4"])
print(args.count * args.unit)
Expected output
12

The parser converts the two supplied numeric arguments to integers.

Validate domain rules

Parsing checks the shape and conversion of input, but a domain rule can require additional validation. An integer may parse successfully while being outside an allowed range. Keep the rule near the function that relies on it, and give callers an actionable error instead of silently changing the input. The example rejects negative quantities before multiplication; the zero case remains valid and produces zero.

python Validate before calculation
def total(count, unit):
    if count < 0:
        raise ValueError("count must be nonnegative")
    return count * unit

print(total(0, 4))
print(total(3, 4))
Expected output
0
12

Zero is valid; a negative count raises the documented error.

Outputs and status

Distinguish the result intended for another program from diagnostic information intended for a person. Decide what a successful exit means and make failures visible to the calling environment. argparse reports invalid arguments and normally exits with a nonzero status; do not catch that exit and pretend success. When integrating a command with scripts, avoid depending on incidental wording or machine-specific paths in error messages.

Test each boundary

Test the core function with valid, zero, and invalid inputs, then test parsing independently with a small fixed argument list. Include missing required values and invalid types, and check that the parser rejects them. For a full process test, run the same entry point users invoke and check its exit status and output. A unit test of the arithmetic alone cannot establish that the command-line wiring is correct.

Define a command as a contract

A command-line interface has inputs, outputs, and a termination status. Its contract should specify positional and optional arguments, defaults, accepted types and ranges, the meaning of output, and the behavior for invalid input. For a synthetic total command, count may be required and unit may default to two; count five then produces ten. A type conversion is not the same as a range rule: parsing -1 as an integer can succeed even when the domain requires a nonnegative count.

Separate a pure calculation from the entry point that parses arguments, calls the calculation, formats the result, and chooses a process status. That separation lets a unit test exercise arithmetic without starting a process, while an integration test verifies that the command passes the right parsed values and reports errors correctly. Importing the calculation module should not parse process arguments or perform unrelated output.

Parse arguments deliberately

argparse can define positional arguments, options, types, defaults, and help text. A positional argument is normally required unless configured otherwise; an optional flag can supply a default when omitted. The type callable converts a supplied string, and an invalid conversion causes argparse to report an error and exit with a nonzero status. Use explicit domain validation for requirements not captured by the conversion, such as a nonnegative range, and give a clear message without exposing unrelated data.

For a deterministic unit-level parsing example, pass a fixed list to parse_args rather than reading the current process arguments. The actual command uses process arguments and therefore needs a separate process-level check. Option spelling and defaults are part of the interface: changing them can break callers even when the arithmetic function is unchanged. Test omitted options, explicit overrides, missing required arguments, invalid types, and boundaries.

Distinguish output streams and status

A successful command commonly writes its result to standard output and exits with status zero; a rejected invocation should use its documented error channel and nonzero status. argparse normally writes usage errors to standard error and exits with status two. Programs can choose their own documented statuses for domain failures. Test the actual status as well as the message; a plausible error string accompanied by a success status can mislead a script that invokes the command.

Keep diagnostic output separate from machine-readable result output when other programs consume it. A caller may capture stdout and stderr independently using subprocess.run. Avoid matching every detail of a usage message if the contract only guarantees a stable category or key phrase, because formatting can depend on parser configuration or Python version. For a command that must provide a stable structured output, define and test that format explicitly.

Verify process wiring safely

A pure total function may return the correct value while the command passes the wrong argument, ignores an override, or mishandles an exception. Test the entry point in a fresh child process with a fixed synthetic argument list, capture its stdout, stderr, and return code, and compare them with the command contract. Use sys.executable to run the same interpreter for an isolated Python fixture rather than assuming a shell alias selects it. Pass a list of arguments to subprocess instead of constructing an untrusted shell command.

For a temporary script fixture, write only synthetic source inside a newly created temporary directory and clean it up afterward. A process test can verify that fixture’s wiring, but it does not establish that a different installed executable or deployment environment is correct. Test the real installed entry point in its target environment when that is part of the release contract. Never use real secrets or production data merely to demonstrate argument parsing.

Exercise valid and invalid boundaries

Use cases for the required positional argument, the default option, an explicit override, zero, a negative value if prohibited, malformed integer text, and a missing argument. Check whether the error occurs during argparse conversion or later domain validation. If a range error must leave state unchanged, verify that separately; these arithmetic examples have no persistent state. Keep each expected result independently calculable from the fixed inputs.

The complete examples below use Python 3.11-compatible standard-library code and synthetic argument lists. Expected parser failures are captured so their error categories and statuses are visible without relying on environment-specific usage text. Child-process examples use the current interpreter and fixed synthetic source. All outputs were checked locally in fresh processes; these examples demonstrate contracts without installing packages, invoking a shell, or accessing external services.

20 worked examples

1. Use a default option

Problem: Parse count five with the default unit and calculate the synthetic total.

  1. The positional argument converts the text 5 to integer five.
  2. The omitted unit uses default two, producing ten.
python Use a default option
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
p.add_argument("--unit", type=int, default=2)
a = p.parse_args(["5"])
print(a.count * a.unit)
Expected output
10

Why this result follows: The parser supplies the documented default unit before the calculation function is called.

2. Override an option

Problem: Parse a fixed count and explicit unit override before calculating the total.

  1. The positional count is five and the option supplies unit three.
  2. Multiplication produces fifteen instead of the default-based result.
python Override an option
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
p.add_argument("--unit", type=int, default=2)
a = p.parse_args(["5", "--unit", "3"])
print(a.count * a.unit)
Expected output
15

Why this result follows: An explicitly supplied option replaces its configured default for that particular parsed invocation.

3. Accept a zero boundary

Problem: Parse zero as a synthetic integer positional argument.

  1. The type conversion accepts the string 0 as integer zero.
  2. The parsed attribute therefore prints zero.
python Accept a zero boundary
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
a = p.parse_args(["0"])
print(a.count)
Expected output
0

Why this result follows: Integer conversion includes zero; any additional domain rule must be checked separately.

4. Separate parsing and range

Problem: Show that a negative integer can parse even when a domain may reject it.

  1. argparse converts the text -1 to an integer successfully.
  2. The later comparison detects that the parsed value is negative.
python Separate parsing and range
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
a = p.parse_args(["-1"])
print(a.count < 0)
Expected output
True

Why this result follows: A type converter validates syntax and type but does not automatically enforce a nonnegative range.

5. Reject malformed integer text

Problem: Capture the parser exit status for a nonnumeric synthetic count.

  1. The int converter rejects the text bad.
  2. argparse reports an error and raises SystemExit with status two.
python Reject malformed integer text
import argparse, contextlib, io
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
with contextlib.redirect_stderr(io.StringIO()):
    try:
        p.parse_args(["bad"])
    except SystemExit as exc:
        print(exc.code)
Expected output
2

Why this result follows: Parser conversion failure is observable through the resulting nonzero process exit status.

6. Reject a missing positional

Problem: Capture the parser status when a required count argument is omitted.

  1. The fixed argument list contains no required positional count.
  2. argparse reports the missing argument and exits with status two.
python Reject a missing positional
import argparse, contextlib, io
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
with contextlib.redirect_stderr(io.StringIO()):
    try:
        p.parse_args([])
    except SystemExit as exc:
        print(exc.code)
Expected output
2

Why this result follows: A required positional argument is checked before a command can use its parsed value.

7. Parse a Boolean flag

Problem: Compare a flag’s value when omitted and when explicitly present.

  1. The store_true action defaults to False when the flag is absent.
  2. Supplying --verbose sets the parsed attribute to True.
python Parse a Boolean flag
import argparse
p = argparse.ArgumentParser()
p.add_argument("--verbose", action="store_true")
print(p.parse_args([]).verbose, p.parse_args(["--verbose"]).verbose)
Expected output
False True

Why this result follows: A flag action records its presence without requiring a separate option value string.

8. Restrict option choices

Problem: Parse a default mode and a valid explicit mode from synthetic arguments.

  1. Omitting the option uses safe as the configured default mode for this parse.
  2. Supplying --mode fast selects the other documented choice.
python Restrict option choices
import argparse
p = argparse.ArgumentParser()
p.add_argument("--mode", choices=["fast", "safe"], default="safe")
print(p.parse_args([]).mode, p.parse_args(["--mode", "fast"]).mode)
Expected output
safe fast

Why this result follows: The choices constraint limits accepted values while the default supplies an omitted option value.

9. Reject an unsupported choice

Problem: Capture the status when a synthetic option is outside its allowed choices.

  1. The supplied value other is not among fast and safe.
  2. argparse rejects it and exits with status two.
python Reject an unsupported choice
import argparse, contextlib, io
p = argparse.ArgumentParser()
p.add_argument("--mode", choices=["fast", "safe"])
with contextlib.redirect_stderr(io.StringIO()):
    try:
        p.parse_args(["--mode", "other"])
    except SystemExit as exc:
        print(exc.code)
Expected output
2

Why this result follows: A choices constraint reports unsupported values before the downstream command logic can run.

10. Parse zero or more items

Problem: Compare an empty positional collection with two supplied synthetic items.

  1. nargs="*" permits no positional items and returns an empty list.
  2. With two inputs it returns a and b in argument order.
python Parse zero or more items
import argparse
p = argparse.ArgumentParser()
p.add_argument("items", nargs="*")
print(p.parse_args([]).items, p.parse_args(["a", "b"]).items)
Expected output
[] ['a', 'b']

Why this result follows: A variable-length positional argument represents all of its parsed values as a list.

11. Collect repeated options

Problem: Collect two occurrences of the same synthetic option in order.

  1. The first --tag contributes a to the parsed list.
  2. The second occurrence contributes b after a in the parsed list.
python Collect repeated options
import argparse
p = argparse.ArgumentParser()
p.add_argument("--tag", action="append")
print(p.parse_args(["--tag", "a", "--tag", "b"]).tag)
Expected output
['a', 'b']

Why this result follows: The append action retains repeated option values rather than replacing the previous one.

12. Inspect a converted type

Problem: Verify the type of a positional argument after argparse conversion.

  1. The type callable int receives the synthetic string 5.
  2. The resulting parsed attribute is an integer.
python Inspect a converted type
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
a = p.parse_args(["5"])
print(type(a.count).__name__)
Expected output
int

Why this result follows: The type option converts an accepted argument before it is exposed on the namespace.

13. Inspect the error stream

Problem: Capture both the status and error-stream evidence for an invalid synthetic count.

  1. The parser writes its diagnostic to redirected standard error.
  2. It exits with status two and the captured text contains error:.
python Inspect the error stream
import argparse, contextlib, io
p = argparse.ArgumentParser(prog="demo")
p.add_argument("count", type=int)
err = io.StringIO()
with contextlib.redirect_stderr(err):
    try:
        p.parse_args(["bad"])
    except SystemExit as exc:
        status = exc.code
print(status, "error:" in err.getvalue())
Expected output
2 True

Why this result follows: A command contract can check status and error channel separately from normal output.

14. Test the pure calculation

Problem: Calculate a synthetic total independently of any argument parser or process.

  1. The function receives count five and unit two directly.
  2. Their product is ten, which the program displays as its result.
python Test the pure calculation
def total(count, unit):
    return count * unit
print(total(5, 2))
Expected output
10

Why this result follows: Separating arithmetic permits a focused test that does not exercise command wiring.

15. Check a successful child process

Problem: Run a fixed synthetic Python command and inspect its status and streams.

  1. The child prints ten to standard output and exits normally.
  2. The parent captures status zero, output 10, and empty standard error.
python Check a successful child process
import subprocess, sys
r = subprocess.run([sys.executable, "-c", "print(5 * 2)"], capture_output=True, text=True)
print(r.returncode, r.stdout.strip(), repr(r.stderr))
Expected output
0 10 ''

Why this result follows: A process test observes the actual exit status and separate output streams.

16. Check a failing child process

Problem: Run a fixed child that writes a diagnostic and exits with a nonzero status.

  1. The child writes bad to standard error and exits with status three.
  2. The parent captures empty standard output and the diagnostic separately.
python Check a failing child process
import subprocess, sys
r = subprocess.run([sys.executable, "-c", "import sys; print(\"bad\", file=sys.stderr); sys.exit(3)"], capture_output=True, text=True)
print(r.returncode, repr(r.stdout), r.stderr.strip())
Expected output
3 '' bad

Why this result follows: The return code and streams expose failure without relying on a shell command string.

17. Validate before calculation

Problem: Apply a nonnegative domain check to a valid parsed synthetic count.

  1. The parser converts five to an integer.
  2. The range check passes, and multiplying by two produces ten.
python Validate before calculation
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
a = p.parse_args(["5"])
if a.count < 0:
    raise ValueError("count must be nonnegative")
print(a.count * 2)
Expected output
10

Why this result follows: A domain check after conversion enforces a rule beyond the argument’s integer syntax.

18. Report a domain failure

Problem: Reject a parsed negative count with a specific synthetic domain message.

  1. The integer conversion succeeds for negative one.
  2. The separate range check raises and reports the documented ValueError.
python Report a domain failure
import argparse
p = argparse.ArgumentParser()
p.add_argument("count", type=int)
a = p.parse_args(["-1"])
try:
    if a.count < 0:
        raise ValueError("count must be nonnegative")
except ValueError as exc:
    print(exc)
Expected output
count must be nonnegative

Why this result follows: Separating domain validation avoids confusing an accepted integer syntax with an allowed count.

19. Inspect help behavior

Problem: Capture the help exit status and a stable usage marker for a synthetic parser.

  1. argparse writes help to standard output and exits successfully.
  2. The captured output includes usage: and the exit status is zero.
python Inspect help behavior
import argparse, contextlib, io
p = argparse.ArgumentParser(prog="demo")
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
    try:
        p.parse_args(["--help"])
    except SystemExit as exc:
        status = exc.code
print(status, "usage:" in buf.getvalue())
Expected output
0 True

Why this result follows: Help is a successful informational path that is distinct from invalid-argument parser errors.

20. Compare default and override

Problem: Inspect the same option when omitted and when supplied explicitly.

  1. The omitted option receives the configured default two.
  2. The explicit value four is converted and used in the second parse.
python Compare default and override
import argparse
p = argparse.ArgumentParser()
p.add_argument("--unit", type=int, default=2)
print(p.parse_args([]).unit, p.parse_args(["--unit", "4"]).unit)
Expected output
2 4

Why this result follows: Testing both paths verifies that the default does not mask an explicit override.

Common errors and fixes

A required argument is missing

Why it happens
The positional argument was omitted.
How to fix it
Provide the documented value.
Prevent it next time
Consult the command help.

An invalid integer is rejected

Why it happens
Text cannot be converted to int.
How to fix it
Supply an integer in the accepted format.
Prevent it next time
Test conversion errors explicitly.

A negative count reaches arithmetic

Why it happens
Type conversion did not enforce the domain rule.
How to fix it
Validate the count before calculation.
Prevent it next time
Test both zero and negative counts.

20 practice exercises

1. Parse count 5 with the default unit 2. What total results?

Show hint

Use the configured unit default when the option is omitted.

Show worked solution

The parsed count is five and the default unit is two, so multiplication produces ten.

The parser converts count 5 to an integer and supplies the default unit 2. Multiplying 5 by 2 gives the total 10. A separate test can verify that an explicit unit overrides the default.

Check your solution

  • The parsed count is 5 and default unit is 2
  • The resulting total is 10

2. Why test the real command after testing the total function?

Show hint

A correct calculation can still be connected incorrectly by the command.

Show worked solution

The command can still select the wrong argument or mishandle an error even if arithmetic is correct. A process test verifies the wiring and exit status.

A process test checks argument parsing, the values passed to the calculation, formatted output, error handling, and exit status. The pure function test alone does not verify those entry-point behaviors.

Check your solution

  • The real command receives the intended arguments
  • Output streams and exit status match the contract

3. Parse count 6 with a default unit of 2 and calculate the expected synthetic total.

Show hint

Multiply the parsed count by the omitted option’s default.

Show worked solution

The count is 6 and the omitted unit receives its default 2. The total is 6 * 2 = 12. A test should assert the parsed default and the result separately.

Check your solution

  • The unit defaults to 2
  • The total is 12

4. Parse count 6 with an explicit --unit 3 and calculate the resulting synthetic total.

Show hint

An explicit option overrides its configured default.

Show worked solution

The parser obtains count 6 and unit 3 from the fixed arguments. Their product is 18. This case verifies that the override reaches the calculation instead of being ignored. Check the behavior against the stated command contract.

Check your solution

  • The parsed unit is 3
  • The total is 18

5. Explain why parsing "-1" as int does not establish that it is a valid nonnegative count.

Show hint

Type conversion and domain validation are distinct stages.

Show worked solution

The int conversion succeeds and produces -1. A separate nonnegative rule rejects that value after parsing. Test both the conversion result and the domain failure so the command reports the correct reason.

Check your solution

  • Integer parsing succeeds
  • The nonnegative range check rejects -1

6. A required positional count is omitted. Describe argparse’s usual status and error channel.

Show hint

Missing required arguments are parser usage errors.

Show worked solution

argparse reports the missing positional argument on standard error and exits with status 2 by default. A process test should check the nonzero status and a stable diagnostic marker rather than a full usage layout.

Check your solution

  • The exit status is 2
  • The diagnostic is written to standard error

7. A count argument is "bad" and has type=int. Identify the failing stage and status.

Show hint

The int converter cannot parse the supplied text.

Show worked solution

The conversion fails inside argparse, which reports an argument error and normally exits with status 2. Domain range validation is not reached because no valid integer count was produced. Check the behavior against the stated command contract.

Check your solution

  • The failure is argument conversion
  • The default parser status is 2

8. Define a --verbose flag and state its values when omitted and when present.

Show hint

Use argparse action="store_true".

Show worked solution

With action="store_true", the parsed value defaults to False when --verbose is absent and becomes True when it is present. Test both invocations so the presence behavior and default are visible.

Check your solution

  • The omitted flag is False
  • The present flag is True

9. An option --mode accepts only "fast" or "safe". What happens for "other"?

Show hint

Use the choices constraint for the documented alternatives.

Show worked solution

argparse rejects "other" because it is not one of the declared choices. By default it writes a usage error to standard error and exits with status 2 before command logic uses the mode.

Check your solution

  • other is rejected
  • The parser reports a nonzero status

10. A positional argument uses nargs="*". Predict its parsed values for no items and for a b.

Show hint

The parser collects zero or more values into a list.

Show worked solution

The empty argument list produces []. Supplying a and b produces ["a", "b"] in that order. This makes the empty-input policy explicit instead of assuming at least one item. Check the behavior against the stated command contract.

Check your solution

  • No items gives []
  • Two items give ["a", "b"]

11. A --tag option uses action="append". Predict the result of --tag x --tag y.

Show hint

Each occurrence contributes one value to a list.

Show worked solution

The parsed tag attribute is ["x", "y"]. The append action retains both supplied values in argument order rather than replacing the first with the second. Check the behavior against the stated command contract.

Check your solution

  • Both tags are retained
  • Their order is x then y

12. Explain why a pure total function test cannot by itself verify the actual command entry point.

Show hint

The command still has parsing, wiring, output, and status behavior.

Show worked solution

The calculation may be correct while the entry point passes the wrong argument or mishandles an error. Run a process test with fixed arguments and check its output streams and exit status separately.

Check your solution

  • The pure calculation is tested independently
  • The process test checks wiring and status

13. A successful child process prints 12 to stdout and exits zero. State the process assertions.

Show hint

Capture stdout, stderr, and return code separately.

Show worked solution

Assert that the return code is 0 and stdout contains the expected result 12, allowing only the documented newline. If the contract requires no diagnostics, also assert that stderr is empty.

Check your solution

  • The return code is 0
  • stdout is 12 and stderr follows the contract

14. A failing child writes "invalid" to stderr and exits 3. What should a caller observe?

Show hint

A nonzero status signals failure independently of the message.

Show worked solution

The caller should see return code 3 and the diagnostic on stderr. If stdout is reserved for successful machine-readable results, it should also be empty for this failure case. Check the behavior against the stated command contract.

Check your solution

  • The return code is 3
  • The diagnostic is on stderr

15. Describe a safe subprocess invocation for a synthetic Python command with fixed arguments.

Show hint

Pass an argument list and use the current interpreter executable.

Show worked solution

Use subprocess.run([sys.executable, "-c", source], capture_output=True, text=True) with fixed synthetic source. Passing a list avoids constructing a shell command string and lets the test inspect output and return code. Check the behavior against the stated command contract.

Check your solution

  • The current interpreter is selected explicitly
  • The arguments are passed as a list

16. Explain why command result output and diagnostics should be separated when another program consumes output.

Show hint

Consider a caller that expects a machine-readable result on stdout.

Show worked solution

A diagnostic mixed into stdout can corrupt the data another program parses. Define the result format on stdout and use the documented error channel for diagnostics, then test both streams and the status.

Check your solution

  • stdout follows the result format
  • diagnostics use the documented error channel

17. A --unit option defaults to 2. Choose tests for omitted and explicit values and expected results.

Show hint

Exercise both the default and an override.

Show worked solution

For count 5, omit --unit and expect total 10. Then supply --unit 4 and expect total 20. Together the cases show that the default works and the override reaches the calculation.

Check your solution

  • The omitted option produces 10
  • The override produces 20

18. Explain what a --help invocation normally writes and which argparse status it uses.

Show hint

Help is an informational path rather than an argument error.

Show worked solution

argparse normally writes help to standard output and exits with status 0. A focused test can check the status and a stable usage marker without matching every formatting detail of the help text.

Check your solution

  • The help status is 0
  • The help output contains a usage marker

19. A command parses count -2 but requires a nonnegative value. Describe a clear validation response.

Show hint

Check the domain rule after integer conversion.

Show worked solution

After parsing -2 successfully, reject it with a documented nonzero status and a message such as "count must be nonnegative" on the error channel. Do not describe it as invalid integer syntax.

Check your solution

  • The integer syntax is accepted
  • The domain rule rejects the negative count

20. Describe an isolated process test for a temporary command script without using production data.

Show hint

Create the script in a temporary directory with synthetic source and inputs.

Show worked solution

Write a minimal script in TemporaryDirectory, invoke it with sys.executable and a fixed argument list, capture its streams and status, and assert the documented result. The context removes the fixture afterward.

Check your solution

  • The fixture uses a temporary directory
  • The test checks output and exit status

Key takeaways

  • Parsing and domain validation are distinct checks.
  • Test the entry point as well as the pure calculation.
  • Successful type conversion does not automatically enforce domain ranges.
  • Command output, diagnostics, and exit status are separate observable contract elements.
  • A process test checks wiring that a pure function test cannot establish.

Official references