[Cialug] Python argparse question
kristau
kristau at protonmail.com
Wed Jan 7 23:54:32 UTC 2026
Spit-balling an idea here:
Make -c/--command optional instead of required
Call parse_args() with made up positionals
If -c/--command is defined, then call parse_args() again, replacing the first positional with the contents of -c/--command
Else, call parse_args() expecting the 1st positional to be the command and 2nd positional to be the path
Either way, use the positional values in the main part of the script, ignoring -c/--command, because you will have copied it into the positional
I don't think this will work with the append action on -c/--command. Also, the first call to parse_args() *might* clobber to original values with the bogus ones? I'll leave testing this idea up to you, but I'd love to hear whether or not it works!
Thanks!
kristau
On Wednesday, January 7th, 2026 at 12:37 PM, Todd Walton <tdwalton at gmail.com> wrote:
> From the ripgrep man page:
>
> rg [OPTIONS] PATTERN [PATH...]
> rg [OPTIONS] -e PATTERN... [PATH...]
>
> So pattern always comes first, path second, and pattern is either the first
> positional argument, or it's made explicit with "-e". How do I do that with
> argparse in Python? My script takes a command to run in each subdirectory
> of a given directory. So like:
>
> myscript.py 'git status' ~/gitrepos
> myscript.py 'git status'
> myscript.py -c 'git status' .
>
> I currently have this:
>
> parser.add_argument(
> "directory",
> nargs='?',
> default=os.getcwd(),
> help="Root directory to search for git repositories",
> )
>
> parser.add_argument(
> "-c",
> "--command",
> action="append",
> dest="commands",
> required=True,
> help="Command to run in each repo (can be specified multiple
> times)",
> )
>
> --
> Todd
> _______________________________________________
> Cialug mailing list
> Cialug at cialug.org
> https://www.cialug.org/cgi-bin/mailman/listinfo/cialug
More information about the Cialug
mailing list