Pregunta

I would like to get/record the indexes into the sys.argv list as the options are parsed

I am trying to wrap another program with a python script. And in the wrapper script I am trying to parse the options that matter to the script and remove them from the argv list, so that I can pass the remainder of the arguments to the program being wrapped.

To do this, I am using parser.parse_known_args() so that I don't have to track every argument the program may support. just the ones that matter to the wrapper.

Now if the parsing recorded the indexes of arguments that need to be removed I could remove them after parsing and pass the remaining args to the wrapped program.

How do I record this information during parsing?

Not all arguments that is meaningful to the wrapper should be removed. So I need to be selective

¿Fue útil?

Solución

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.

Otros consejos

I am not familiar with parser.parse_known_args(). I am using Python 2.7 and there is no such function. What you could do though is save the original sys.argv in say arg_list and do

indices = [arg_list.index(a) for a in selected_arguments]

This will return a list of indices (the positions) of the selected arguments

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top