Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

subcommands and nargs > 1 #275

Open
fopina opened this issue Jul 14, 2022 · 3 comments
Open

subcommands and nargs > 1 #275

fopina opened this issue Jul 14, 2022 · 3 comments

Comments

@fopina
Copy link

fopina commented Jul 14, 2022

These lines: here and here

These always place env and config file variables at the end of argv, when any config used has nargs > 1.

While it does not make any difference in most cases, it does when subparsers are used.

If parent parser has one of these flags and it is used via env/configfile, it is moved to the end of argv, after the subparser, making them options of the subparser, not the parent one (and failing to parse args).

Not sure I understand the reason behind this logic so unable to propose a fix / submit PR.

I assume best way would be to rebuild argv based on all the parser definitions rather than assuming where to put the flags

@tbooth
Copy link

tbooth commented Nov 23, 2022

I've just discovered the same bug after 2 hours of head scratching. I was having trouble running snakemake and I tracked the problem down to this module. Here's the simplest script I could make that shows the issue:

import configargparse
import os

# Set a single env var as config
os.environ['FOO'] = "configured_value"

# The first iteration works fine. The second not so much.
for f_nargs in [None, '?']:

    p = configargparse.ArgParser()
    p.add('--foo', '-f', nargs=f_nargs, env_var='FOO', required=False)
    p.add('bar', nargs='*')

    options = p.parse_args(['--', 'arg1', 'arg2'])
    print("when f_nargs is {!r}".format(f_nargs))
    print(options)
    print("----------")

And here's what I get when I run it:

when f_nargs is None
Namespace(foo='configured_value', bar=['arg1', 'arg2'])
----------
when f_nargs is '?'
Namespace(foo=None, bar=['arg1', 'arg2', '-f=configured_value'])
----------

Not good!

@fopina
Copy link
Author

fopina commented Nov 23, 2022

I think this is one hard to tackle, at least for env.

The easiest way I worked around it was to have different env prefixes setup for the different parsers.
That worked nicely and doesn't look bad.

Not sure how the library could handle it with same prefix as env won't be ordered, so when parent parser and subcommand do share a flag with same name, it's impossible to know which to map the env value.

@John15321
Copy link

Shouldnt this be closed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants