{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"command-line-arguments","title":"Giving your script a proper command line","url":"https://addaly.com/learn/python-for-ai/command-line-arguments","position":29,"of":89,"minutes":8,"answer":"Arguments belong on the command line rather than in input() prompts, and argparse gives you conversion, validation, generated help and correct exit codes for about fifteen lines.","keyIdea":"Arguments belong on the command line rather than in `input()` prompts, and `argparse` gives you conversion, validation, generated help and correct exit codes for about fifteen lines."},"body":{"format":"markdown","text":"## `input()` is the wrong tool for a script\n\nA program that asks questions with `input()` cannot be scheduled, cannot be run by another program, and cannot be put in a pipeline. The moment a script is useful, somebody wants to run it on a timer or on fifty files, and interactive prompts stop that dead.\n\nThe values a run needs should arrive on the command line.\n\n## The crude version\n\n```python\nimport sys\n\npath = sys.argv[1]\nprint(f\"processing {path}\")\n```\n\n```bash\npython3 clean.py data/sales.csv\n```\n\n`sys.argv` is a list of strings. Position 0 is the script name, so real arguments start at 1. Everything is a string, including numbers.\n\nThis works and it stops working the moment you have two options, or an optional one, or want `--help`. Then you are writing an argument parser by hand, badly.\n\n## `argparse`, which ships with Python\n\n```python\nimport argparse\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Clean a sales export.\")\n    parser.add_argument(\"path\", help=\"input CSV\")\n    parser.add_argument(\"--out\", default=\"clean.csv\", help=\"output path\")\n    parser.add_argument(\"--limit\", type=int, help=\"stop after N rows\")\n    parser.add_argument(\"--dry-run\", action=\"store_true\",\n                        help=\"report what would change, write nothing\")\n    args = parser.parse_args()\n\n    print(args.path, args.out, args.limit, args.dry_run)\n\nif __name__ == \"__main__\":\n    main()\n```\n\nThat is the whole of it, and it gives you a great deal for fifteen lines:\n\n```bash\npython3 clean.py data/sales.csv --limit 100 --dry-run\npython3 clean.py --help\n```\n\n- `type=int` converts and rejects non-numbers with a clear message, rather than crashing later.\n- `action=\"store_true\"` makes a flag that is on when present, off when absent.\n- A missing required argument prints usage and exits with status 2, without a traceback.\n- `--help` is generated from what you already wrote. Nobody has to maintain it separately.\n- `--dry-run` in a hyphenated form becomes `args.dry_run`.\n\nA `--dry-run` flag on anything that writes, deletes or sends is worth building in from the start. It is the difference between testing on production data and destroying it.\n\n## Exit codes, because other programs are listening\n\nThis example takes the file path as its first command-line argument.\n\n```python\nimport sys\nfrom pathlib import Path\n\npath = Path(sys.argv[1])\nif not path.exists():\n    print(f\"no such file: {path}\", file=sys.stderr)\n    sys.exit(1)\n```\n\nBy convention, exit status 0 means success and anything else means failure. Shell scripts, CI systems and cron all read it. A script that prints \"ERROR\" and exits 0 will be treated as a success by everything that automates it.\n\nTwo details in that snippet. Errors go to **stderr**, not stdout, so that `python3 clean.py > out.csv` still shows you the error instead of burying it in the file. And an uncaught exception exits with status 1 automatically, which is fine: you do not need to wrap everything in `try` to get correct exit behaviour.\n\n## Reading from standard input\n\n```bash\ncat sales.csv | python3 clean.py -\n```\n\nTreating `-` as \"read stdin\" makes your script composable with every other command-line tool. `sys.stdin` behaves like an open file, so a loop over it works line by line:\n\n```python\nsource = sys.stdin if args.path == \"-\" else open(args.path)\n```\n\n## Restricting and grouping options\n\n```python\nparser.add_argument(\"--format\", choices=[\"csv\", \"json\"], default=\"csv\")\nparser.add_argument(\"--verbose\", \"-v\", action=\"count\", default=0)\nparser.add_argument(\"files\", nargs=\"+\", help=\"one or more inputs\")\n```\n\n`choices` rejects anything else with a message naming the valid values, so a typo fails at the door instead of three functions later. `action=\"count\"` gives the familiar `-v`, `-vv`, `-vvv` pattern, which maps neatly onto logging levels. `nargs=\"+\"` accepts one or more values. When a shell expands `*.csv` into file names before Python starts, this option lets the script accept the resulting list. Shells that do not expand the pattern pass its literal text instead.\n\nFor a tool that grows several distinct jobs, `parser.add_subparsers()` gives you `mytool clean` and `mytool report` with separate options each, in the style of `git`. Reach for it when a single flat option list starts having options that only make sense together.\n\n## The alternatives, and whether you need them\n\n`click` and `typer` are free third-party libraries that build the parser from a function signature and type hints, which is nicer for a complex tool with subcommands. `argparse` needs no installation, works everywhere, and handles everything up to moderate complexity.\n\nFor a script somebody else has to install, prefer the standard library. Every dependency is a thing that must be present on the machine where the script eventually runs, and that machine is often not yours.\n\n## Try this now\n\nTake a script you wrote earlier that has a hard-coded file path. Give it an `argparse` interface with the path as a positional argument, a `--limit` with `type=int`, and a `--dry-run`. Then run it with `--help` and read what you get for free, and run it with a missing file to check the exit code with `echo $?`."},"check":{"question":"A nightly job runs `python3 clean.py` and the operations team reports it as green every night, though the output file has been empty for a week. The script prints \"ERROR: source missing\" and stops. Why did nothing notice?","options":[{"text":"The message went to stdout, which cron discards, so it should have been logged to a file instead.","correct":false,"tempting":"Fixes the visibility of the message but leaves the scheduler still seeing a successful run."},{"text":"The script printed and returned normally, so it exited with status 0, which every scheduler reads as success.","correct":true},{"text":"`argparse` swallowed the failure because no arguments were supplied, and it exits 0 when it prints usage.","correct":false,"tempting":"Half-remembers argparse behaviour; it exits with status 2 on a usage error, which a scheduler would flag."},{"text":"Cron only reports failures when a traceback is printed, so the error needed to be raised rather than printed.","correct":false,"tempting":"Attributes the detection to the traceback text rather than to the exit status, which is what schedulers actually read."}]},"prev":{"slug":"pure-functions","title":"Side effects, and why some functions are easy to test","url":"https://addaly.com/learn/python-for-ai/pure-functions"},"next":{"slug":"reading-errors","title":"Reading an error message properly","url":"https://addaly.com/learn/python-for-ai/reading-errors"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Giving your script a proper command line', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/command-line-arguments (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Giving your script a proper command line","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"Arguments belong on the command line rather than in `input()` prompts, and `argparse` gives you conversion, validation, generated help and correct exit codes for about fifteen lines.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"input-is-the-wrong-tool-for-a-script","runs":[{"text":"input()","code":true},{"text":" is the wrong tool for a script"}]},{"t":"p","runs":[{"text":"A program that asks questions with "},{"text":"input()","code":true},{"text":" cannot be scheduled, cannot be run by another program, and cannot be put in a pipeline. The moment a script is useful, somebody wants to run it on a timer or on fifty files, and interactive prompts stop that dead."}]},{"t":"p","runs":[{"text":"The values a run needs should arrive on the command line."}]},{"t":"h2","id":"the-crude-version","runs":[{"text":"The crude version"}]},{"t":"code","lang":"python","label":"Python","text":"import sys\n\npath = sys.argv[1]\nprint(f\"processing {path}\")"},{"t":"code","lang":"bash","label":"Bash","text":"python3 clean.py data/sales.csv"},{"t":"p","runs":[{"text":"sys.argv","code":true},{"text":" is a list of strings. Position 0 is the script name, so real arguments start at 1. Everything is a string, including numbers."}]},{"t":"p","runs":[{"text":"This works and it stops working the moment you have two options, or an optional one, or want "},{"text":"--help","code":true},{"text":". Then you are writing an argument parser by hand, badly."}]},{"t":"h2","id":"argparse-which-ships-with-python","runs":[{"text":"argparse","code":true},{"text":", which ships with Python"}]},{"t":"code","lang":"python","label":"Python","text":"import argparse\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Clean a sales export.\")\n    parser.add_argument(\"path\", help=\"input CSV\")\n    parser.add_argument(\"--out\", default=\"clean.csv\", help=\"output path\")\n    parser.add_argument(\"--limit\", type=int, help=\"stop after N rows\")\n    parser.add_argument(\"--dry-run\", action=\"store_true\",\n                        help=\"report what would change, write nothing\")\n    args = parser.parse_args()\n\n    print(args.path, args.out, args.limit, args.dry_run)\n\nif __name__ == \"__main__\":\n    main()"},{"t":"p","runs":[{"text":"That is the whole of it, and it gives you a great deal for fifteen lines:"}]},{"t":"code","lang":"bash","label":"Bash","text":"python3 clean.py data/sales.csv --limit 100 --dry-run\npython3 clean.py --help"},{"t":"ul","items":[[{"text":"type=int","code":true},{"text":" converts and rejects non-numbers with a clear message, rather than crashing later."}],[{"text":"action=\"store_true\"","code":true},{"text":" makes a flag that is on when present, off when absent."}],[{"text":"A missing required argument prints usage and exits with status 2, without a traceback."}],[{"text":"--help","code":true},{"text":" is generated from what you already wrote. Nobody has to maintain it separately."}],[{"text":"--dry-run","code":true},{"text":" in a hyphenated form becomes "},{"text":"args.dry_run","code":true},{"text":"."}]]},{"t":"p","runs":[{"text":"A "},{"text":"--dry-run","code":true},{"text":" flag on anything that writes, deletes or sends is worth building in from the start. It is the difference between testing on production data and destroying it."}]},{"t":"h2","id":"exit-codes-because-other-programs-are-listening","runs":[{"text":"Exit codes, because other programs are listening"}]},{"t":"p","runs":[{"text":"This example takes the file path as its first command-line argument."}]},{"t":"code","lang":"python","label":"Python","text":"import sys\nfrom pathlib import Path\n\npath = Path(sys.argv[1])\nif not path.exists():\n    print(f\"no such file: {path}\", file=sys.stderr)\n    sys.exit(1)"},{"t":"p","runs":[{"text":"By convention, exit status 0 means success and anything else means failure. Shell scripts, CI systems and cron all read it. A script that prints “ERROR” and exits 0 will be treated as a success by everything that automates it."}]},{"t":"p","runs":[{"text":"Two details in that snippet. Errors go to "},{"text":"stderr","b":true},{"text":", not stdout, so that "},{"text":"python3 clean.py > out.csv","code":true},{"text":" still shows you the error instead of burying it in the file. And an uncaught exception exits with status 1 automatically, which is fine: you do not need to wrap everything in "},{"text":"try","code":true},{"text":" to get correct exit behaviour."}]},{"t":"h2","id":"reading-from-standard-input","runs":[{"text":"Reading from standard input"}]},{"t":"code","lang":"bash","label":"Bash","text":"cat sales.csv | python3 clean.py -"},{"t":"p","runs":[{"text":"Treating "},{"text":"-","code":true},{"text":" as “read stdin” makes your script composable with every other command-line tool. "},{"text":"sys.stdin","code":true},{"text":" behaves like an open file, so a loop over it works line by line:"}]},{"t":"code","lang":"python","label":"Python","text":"source = sys.stdin if args.path == \"-\" else open(args.path)"},{"t":"h2","id":"restricting-and-grouping-options","runs":[{"text":"Restricting and grouping options"}]},{"t":"code","lang":"python","label":"Python","text":"parser.add_argument(\"--format\", choices=[\"csv\", \"json\"], default=\"csv\")\nparser.add_argument(\"--verbose\", \"-v\", action=\"count\", default=0)\nparser.add_argument(\"files\", nargs=\"+\", help=\"one or more inputs\")"},{"t":"p","runs":[{"text":"choices","code":true},{"text":" rejects anything else with a message naming the valid values, so a typo fails at the door instead of three functions later. "},{"text":"action=\"count\"","code":true},{"text":" gives the familiar "},{"text":"-v","code":true},{"text":", "},{"text":"-vv","code":true},{"text":", "},{"text":"-vvv","code":true},{"text":" pattern, which maps neatly onto logging levels. "},{"text":"nargs=\"+\"","code":true},{"text":" accepts one or more values. When a shell expands "},{"text":"*.csv","code":true},{"text":" into file names before Python starts, this option lets the script accept the resulting list. Shells that do not expand the pattern pass its literal text instead."}]},{"t":"p","runs":[{"text":"For a tool that grows several distinct jobs, "},{"text":"parser.add_subparsers()","code":true},{"text":" gives you "},{"text":"mytool clean","code":true},{"text":" and "},{"text":"mytool report","code":true},{"text":" with separate options each, in the style of "},{"text":"git","code":true},{"text":". Reach for it when a single flat option list starts having options that only make sense together."}]},{"t":"h2","id":"the-alternatives-and-whether-you-need-them","runs":[{"text":"The alternatives, and whether you need them"}]},{"t":"p","runs":[{"text":"click","code":true},{"text":" and "},{"text":"typer","code":true},{"text":" are free third-party libraries that build the parser from a function signature and type hints, which is nicer for a complex tool with subcommands. "},{"text":"argparse","code":true},{"text":" needs no installation, works everywhere, and handles everything up to moderate complexity."}]},{"t":"p","runs":[{"text":"For a script somebody else has to install, prefer the standard library. Every dependency is a thing that must be present on the machine where the script eventually runs, and that machine is often not yours."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Take a script you wrote earlier that has a hard-coded file path. Give it an "},{"text":"argparse","code":true},{"text":" interface with the path as a positional argument, a "},{"text":"--limit","code":true},{"text":" with "},{"text":"type=int","code":true},{"text":", and a "},{"text":"--dry-run","code":true},{"text":". Then run it with "},{"text":"--help","code":true},{"text":" and read what you get for free, and run it with a missing file to check the exit code with "},{"text":"echo $?","code":true},{"text":"."}]}],"check":{"question":[{"text":"A nightly job runs "},{"text":"python3 clean.py","code":true},{"text":" and the operations team reports it as green every night, though the output file has been empty for a week. The script prints “ERROR: source missing” and stops. Why did nothing notice?"}],"options":[{"text":[{"text":"The message went to stdout, which cron discards, so it should have been logged to a file instead."}],"correct":false,"tempting":[{"text":"Fixes the visibility of the message but leaves the scheduler still seeing a successful run."}]},{"text":[{"text":"The script printed and returned normally, so it exited with status 0, which every scheduler reads as success."}],"correct":true,"tempting":null},{"text":[{"text":"argparse","code":true},{"text":" swallowed the failure because no arguments were supplied, and it exits 0 when it prints usage."}],"correct":false,"tempting":[{"text":"Half-remembers argparse behaviour; it exits with status 2 on a usage error, which a scheduler would flag."}]},{"text":[{"text":"Cron only reports failures when a traceback is printed, so the error needed to be raised rather than printed."}],"correct":false,"tempting":[{"text":"Attributes the detection to the traceback text rather than to the exit status, which is what schedulers actually read."}]}],"order":[0,3,2,1],"why":null},"prev":{"slug":"pure-functions","title":"Side effects, and why some functions are easy to test","minutes":8},"next":{"slug":"reading-errors","title":"Reading an error message properly","minutes":9}}}