parse.parse_known_args
returns 2 values, the namespace
containing arguments that it knows about, and a list of the strings that it could not handle. I think that rest
list is what you want to pass on to the other program.
In other words:
[args1, rest] = parser1.parse_known_args() # or (sys.argv[1:])
args = parser2.parse_args(rest)
If you can't give parser2
an explicit list of arguments (e.g. it is coded as parse_args()
), then you need to do to do something like:
sys.argv[1:] = rest
I looked again at the internals of argparse
, _parse_known_args
. It iterates through the argument strings a couple of times. The loop that consumes strings uses a while start_index<max_index:
. start_index
is incremented by varying amounts depending on the nargs
of each argument. It does, in effect, point to the first string used for a particular argument (e.g. the -f
flag). But its value is not given to the action
function (which you can customize). Nor is it recorded anywhere. Strings that it can't handle are added to an extras
list. This is the 2nd value that parse_known_args
returns.