Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check input arguments in a python script with CLI?

I'm writing a small script to learn Python. The script prints a chess tournament table for N players. It has a simple CLI with a single argument N. Now I'm trying the following approach:

import argparse

def parse_args(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Tournament tables")
    parser.add_argument('N', help="number of players (2 at least)", type=int)
    args = parser.parse_args(argv)
    if args.N < 2:
        parser.error("N must be 2 at least")
    return args.N

def main(n: int) -> None:
    print(F"Here will be the table for {n} players")

if __name__ == '__main__':
    main(parse_args())

But this seems to have a flaw. The function main doesn't check n for invalid input (as it's the job of CLI parser). So if somebody calls main directly from another module (a tester for example), he may call it with lets say 0, and the program most likely crashes.

How should I properly handle this issue?

I'm considering several possible ways, but not sure what is the best.

  1. Add a proper value checking and error handling to main. This option looks ugly to me, as it violates the DRY principle and forces main to double the job of CLI.

  2. Just document that main must take only n >= 2, and its behaviour is unpredicted otherwise. Possibly to combine with adding an assertion check to main, like this:

    assert n >= 2, "n must be 2 or more"

  3. Perhaps such a function should not be external at all? So the whole chosen idiom is wrong and the script's entry point should be rewritten another way.

  4. ???

like image 558
Phant Avatar asked Sep 03 '25 17:09

Phant


2 Answers

You could have main do all the checking aind raise ArgumentError if something is amiss. Then catch that exception and forward it to the parser for display. Something along these lines:

import argparse

def run_with_args(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Tournament tables")
    parser.add_argument('N', help="number of players (2 at least)", type=int)
    args = parser.parse_args(argv)
    try:
        main(args.N)
    except argparse.ArgumentError as ex:
        parser.error(str(ex))

def main(n: int) -> None:
    if N < 2:
        raise argparse.ArgumentError("N must be 2 at least")
    print(F"Here will be the table for {n} players")

if __name__ == '__main__':
    run_with_args()

If you don't want to expose argparse.ArgumentError to library users of main, you can also create a custom exception type instead of it.

like image 186
Thomas Avatar answered Sep 05 '25 15:09

Thomas


A common way of running argparse when wanting to test functions/CLI is to have the main function take a the sys.argv list and then call parse_args from within main like so:

arg.py

import argparse

def parse_args(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Tournament tables", prog="prog")
    parser.add_argument("N", help="number of players (2 at least)", type=int)
    args = parser.parse_args(argv)
    if args.N < 2:
        parser.error("N must be 2 at least")
    return args

def main(argv: list[str] | None = None) -> None:
    args = parse_args(argv)
    print(f"Here will be the table for {args.N} players")

if __name__ == "__main__":
    main()

This way a test can call main with a hypothetical CLI:

test_main.py

import pytest
from arg import main

def test_main(capsys):
    with pytest.raises(SystemExit):
        main(["0"])
    out, err = capsys.readouterr()
    assert err.splitlines()[-1] == "prog: error: N must be 2 at least"
like image 40
Alex Avatar answered Sep 05 '25 14:09

Alex