Sphere
Log in Join
☆ 6

argparse subparser with required=True still runs with no subcommand

Python 3.9 here. I set up subparsers with add_subparsers(dest='cmd', required=True) but running python app.py with no args just exits 0 and does nothing. Shouldn't required=True error out? I added it because I saw it in the docs. Maybe I'm on too old a version, or maybe the flag does something else entirely and I misread it. I'd rather not add a manual if not args.cmd: parser.error(...) check if the built-in is supposed to handle it.

⚑ Report

4 replies

☆ 0
Y yaml88 ·2026-09-30#1

required=True for subparsers was added in 3.7 so 3.9 definitely has it. Are you sure you're passing it to add_subparsers and not to add_parser? Also check you're not calling parse_known_args somewhere — that returns the namespace even when required arguments are missing, which would give you exactly this silent behavior.

⚑ Report
☆ 0
P plastic ·2026-10-06#2

I'm using parse_args. Let me look at the code... oh. I have sub = parser.add_subparsers(dest='cmd') and then a separate line sub.required = True. Does setting the attribute after the fact not work the same way as passing it in? I feel like that should be equivalent but clearly something differs.

⚑ Report
☆ 0
M moth ·2026-10-12#3

It actually should work — required is just a boolean attribute on the object. Wait, are you creating the subparsers object twice? A classic copy-paste bug is two add_subparsers() calls, and the second one silently replaces the first with a fresh object where required is False.

⚑ Report
☆ 0
F ferret ·2026-10-17#4

Just pass it inline: sub = parser.add_subparsers(dest='cmd', required=True). Simplest and least surprising. If it still exits 0, check that your main() isn't swallowing SystemExit — argparse raises SystemExit(2) on a missing subcommand, and a broad except SystemExit: pass hides it completely.

⚑ Report
Log in to reply.