Parse a required local input name with argparse
argparse positional arguments are required unless their definition permits omission. Here, add_argument("input_name") defines one positional value, so calling the program as local-name notes.txt produces args.input_name == "notes.txt". The example passes a synthetic list to parse_args() instead of reading the process command line; that makes the demonstrated input and output deterministic while using the same parsing API a script uses normally.
The assertions establish that this particular input is stored under the expected Namespace attribute and retains its string value. They do not verify that a file exists, is readable, or is safe to open. A positional name is only command-line text. If the next step needs a local file, validate its location and handle OSError when opening it. Also note that a value beginning with - can be interpreted as an option in some command shapes; command-line design may need -- or a different interface for such names.
argparse has been included in the Python standard library since Python 3.2. ArgumentParser.add_argument() attaches the specification, and parse_args() returns the populated Namespace, as described in the official argparse documentation.
AI assistance disclosure: this article was drafted with AI assistance and should be checked in its target CLI context.
import argparse
parser = argparse.ArgumentParser(prog="local-name")
parser.add_argument("input_name", help="a local input name")
args = parser.parse_args(["notes.txt"])
assert args.input_name == "notes.txt"
assert isinstance(args.input_name, str)
print(f"input_name={args.input_name}")
input_name=notes.txt
Comments
Post a Comment