[Cialug] Python argparse question

Barry Von Ahsen barry at vonahsen.com
Thu Jan 8 00:05:30 UTC 2026


my first thought, consider -c/--command as a flag, then parse the first positional argument as the command as you were.  you can action='store_true' to do whatever logic you may need for the explicit case in your command parser method
```
def validate_command(str_command: str)
   if command:  #the confusingly named arg bool, not the arg to this method
       # do something slightly different because explicitly -c?
   else:
      sys.exec(str_command)
```

second thought, have both args, and send them through the same command parser method:

```
add_argument("-c","--command", ...)
add_argument("positional_command", ...)

args = parser.parse_args
if args.command:
  validate_command(command)
elif args.positional_command:
  validate_command(positional_command)

```
third thought:
I haven't used dest= can you use the same dest= on multiple arguments?


-barry





On Wednesday, January 7th, 2026 at 12:37, 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