A command-line argument is a value supplied when a script is run. It gives a command-line program input without changing its code—for example, a filename to process or a switch controlling its output. This differs from an argument passed to a Python function inside the program. section 11.1.2 section 11.5 section 3.4.6
Read arguments with sys.argv
Run `python script2.py arg1 arg2 3`. After `import sys`, printing `sys.argv` produces `['script2.py', 'arg1', 'arg2', '3']`. The script name is at index 0; supplied values follow it. Every item is a string, so convert `'3'` before using it as a number. In a notebook, prefix the command with `!`. section 11.1.2
For a small script, `sys.argv` gives direct access to the list. A controlling `main()` function can check the number and validity of arguments, translate them into the inputs its functions need, and give a useful message when input is wrong. section 11.1.2 section 11.3
For structured command lines, `argparse` handles positional arguments and prefixed options:
- Create an `ArgumentParser`, register arguments with `add_argument()`, then call `parse_args()`. Read the resulting namespace through attributes such as `args.indent`. section 11.1.5
- An unprefixed positional argument can be required and given a type, such as `type=int` for an indentation width. Prefixed options such as `-f` or `--file` are optional; a switch can use `action="store_false"` to change a default value. section 11.1.5
- The parser can generate usage information and reports missing required arguments or invalid input. section 11.1.5
Options and positionals together
With positional `indent` and `input_file` arguments plus `-x`, `-q`, and `-f` options, `python opts.py -x100 -q -f outfile 2 arg2` yields `indent=2`, `input_file='arg2'`, `filename='outfile'`, `xray='100'`, and `verbose=False`. Notice that `xray` remains a string, while the declared integer positional is converted. section 11.1.5
A filename need not always be supplied: a file-processing utility can read standard input when no filename argument is given. For a `wc`-style script, `python wc_redirect.py wc_redirect.py` names the file directly, while `python wc_redirect.py < wc_redirect.py` redirects it through standard input. If using `argparse`, make the filename optional to support both forms. section 13.10













