Command-Line Arguments Start as Text
Each command-line argument reaches an ordinary Python program as a string. A command's argument parser supplies types and reports invalid values.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Identify the shell's work
In a usual shell invocation, quoting can keep a filename with a space in one argument. A symbolic argument such as 007 remains text in sys.argv. Whether leading zeros are meaningful depends on the program. A badge identifier may preserve them and a copy count may be parsed into the integer seven. Names and meaning help convey which interpretation the code uses.
Give invalid input an outcome
A report command requiring a positive count can reject 0 and the text three with a short diagnostic. Treat malformed input and an unreadable source file as distinct cases when designing exit status and output. That distinction lets a caller repair the command without an interactive traceback.[1]
Trace the shell's work before parsing a number
Suppose a report accepts a count and a filename. A normal shell invocation can hand it two arguments, even when the filename contains a space, if the name is quoted under that shell's rules. The Python receiver still sees text for both supplied values. A numeric count written as 007 can parse to seven. A record identifier with the same spelling may need to retain its leading zeros. See shell argument formation for where argument boundaries come from.
Try supplying the count as 0, 2.5, and 7 under a positive-integer policy. Zero can be valid integer text and still fail the policy. The spelling with a decimal point fails an ordinary integer parser. Seven passes both. Parsing and domain validation gives the caller a distinct reason for each failure.
Verify the interface at the process boundary
Unit tests can call the argument parser with a list of strings. A command integration test can additionally verify the real invocation, stdout, stderr, and exit result. A case containing spaces distinguishes a lost argument boundary from a parser error. A case with a missing argument is also distinct from an explicitly supplied empty string.
When documenting a runnable example, name the shell or use an argument-array representation if quoting matters. Tell readers what each supplied value means and which are optional. Then verify an accepted example and at least one useful error so that somebody invoking the command can correct their input from the reported reason.