1
votes

How can I have argparse only parse commands that come after a positional argument?

Aka if I have the command pythonfile.py -d dir -e test pos_cmd_1 -d

How can I have it so that the first -d is parsed by argparse, and anything after the positional command is parsed by that command itself (read pos_cmd_1 -d as a single argument basically)

So that the argument list would be

  • pythonfile.py
  • -d dir
  • -e test
  • pos_cmd_1 -d -s -etc

So anything before the positional command would be optional. And anything after the positional command would be part of the positional command itself.

Edit: When trying to run the command with double dashes, it tells me that the arguments that come after aren't recognized.

pythonfile.py -d testdir -e test -- command -d -s

It says -d -s are unrecognized arguments instead of bundling them with the command.

2
how about ending the switches with double dash? pythonfile.py -d dir -e test -- pos_cmd_1 -d at least it's clear where options stop - Jean-François Fabre
Could you give some context: why do you think you want to do this? - jonrsharpe
@jonrsharpe writing a wrapper for docker-compose that lets me add custom extensibility, and some of the arguments flags overlap with those of the docker command. So like have -d be parsed as my command if it comes before the compose command (up/start/kill/etc) but if it comes after, it would be part of the docker command. So python.py -d test up -d where the second -d would be parsed by docker. - cclloyd
In that case use the --, which often appears for "...then pass these arguments to whatever that calls". - jonrsharpe
In my view, the utility should be invoked properly (i.e. according to its documented usage) from a shell. Use quoting or double dash for that prupose. Those are well-known standards that should be obeyed. Example: pythonfile.py -d dir -e test "pos_cmd_1 -d" - VPfB

2 Answers

1
votes

you can achieve this just by slightly changing your command line to

pythonfile.py -d dir -e test -- pos_cmd_1 -d

by adding --, you tell argparse to stop looking for options. So all remaining arguments are set in the positional argument list instead.

An alternative is quoting the rest of arguments:

pythonfile.py -d dir -e test "pos_cmd_1 -d"

and (because it creates just one positional argument) use argument parser again on the splitted string (not ideal if you want to pass quoted strings in those args)

The advantages of those approaches is that they're natively supported by argparse, getopt and also that is a standard mechanism that won't surprise the users of your command.

if you want to stick to your approach, maybe you could pre-process argument list to insert the double dash by detecting 2 non-option arguments in a row:

args = "-d dir -e test pos_cmd_1 -d".split()
oldarg=""
for i,a in enumerate(args):
    if oldarg and oldarg[0]!='-' and a[0]!='-':
        args.insert(i,'--')
        break
    oldarg = a

args is now: ['-d', 'dir', '-e', 'test', '--', 'pos_cmd_1', '-d']

0
votes

With the simple parser:

In [2]: p = argparse.ArgumentParser()
In [3]: p.add_argument('-d');
In [4]: p.add_argument('-e');
In [5]: p.parse_args('-d dir -e test pos_cmd_1 -d'.split())
usage: ipython3 [-h] [-d D] [-e E]
ipython3: error: argument -d: expected one argument

It tries to parse the last '-d' and hits an error. parse_known_args doesn't help.

With strings other than '-d' and '-e' parse_known_args works:

In [7]: p.parse_known_args('-d dir -e test pos_cmd_1 -s'.split())
Out[7]: (Namespace(d='dir', e='test'), ['pos_cmd_1', '-s'])

A positional with a REMAINDER nargs appears to work:

In [8]: a1 = p.add_argument('rest', nargs='...') # argparse.REMAINDER
In [9]: p.parse_args('-d dir -e test pos_cmd_1 -s'.split())
Out[9]: Namespace(d='dir', e='test', rest=['pos_cmd_1', '-s'])
In [10]: p.parse_args('-d dir -e test pos_cmd_1 -d'.split())
Out[10]: Namespace(d='dir', e='test', rest=['pos_cmd_1', '-d'])

REMAINDER is supposed to work much like the '--', capturing input for use by another parser or command.

It can have problems if it's expected to catch the whole commandline, as in:

In [12]: p.parse_args('-s pos_cmd_1 -d'.split())
usage: ipython3 [-h] [-d D] [-e E] ...
ipython3: error: unrecognized arguments: -s

https://docs.python.org/3/library/argparse.html#nargs