Harvey
Harvey

Reputation: 637

argparse is not returning expected value for store_true

I'm running Python 3.6.8 :: Anaconda custom (64-bit) and getting strange results from argparse. Despite the -x, the value of trainandexecute=False

def get_parameters():
    startup = '-x -b'
    sys.argv = startup.split(' ')
    ap = argparse.ArgumentParser()
    ap.add_argument('-x',       '--trainandexecute', action='store_true')
    ap.add_argument('-b',       '--debug',           action='store_true')
    ap.add_argument('-d',       '--rundate',         action='store')
    print(ap.parse_args())
    return vars(ap.parse_args())
get_parameters()

This returns the following output. Notet that trainandexecute=False despite the -x flag.

Namespace(debug=True, execute=False, train=False, trainandexecute=False)
{'train': False,
 'execute': False,
 'trainandexecute': False,
 'debug': True}

However, this test works in the next Jupyter cell and that it is not my environment:

def get_test_parameters():
    startup = '-b -x'
    sys.argv = startup.split(' ')
    print(sys.argv)
    ap = argparse.ArgumentParser()
    ap.add_argument('-x',       '--x',         action='store_true')
    ap.add_argument('-b',       '--debug',     action='store_true')
    print(ap.parse_args())
    return vars(ap.parse_args())

So the output of:

get_test_parameters()

is:

['-b', '-x']                   # print(sys.argv)
Namespace(debug=False, x=True) # print(ap.parse_args())
{'x': True, 'debug': False}    # return vars(ap.parse_args())

I'm bifflesnickered...

Upvotes: 3

Views: 195

Answers (2)

hpaulj
hpaulj

Reputation: 231665

Here's a better test framework:

def get_parameters(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('-x',       '--trainandexecute', action='store_true')
    ap.add_argument('-b',       '--debug',           action='store_true')
    ap.add_argument('-d',       '--rundate',         action='store')
    args = ap.parse_args(argv))     # if None, parses sys.argv[1:]
    print(args)
    return vars(args)

get_parameters('-x -b'.split())

You can modify sys.argv[1:] instead. By passing argv through your function, you can test several ways.

Upvotes: 1

DYZ
DYZ

Reputation: 57105

Your error is in this line:

sys.argv = startup.split(' ')

The first value in sys.argv is treated as the name of the script, not as an option. Try running ap.parse_args(startup.split()) - and you will see the right answer.

Incidentally, do not pass any parameters to split(). If you pass " " and you have more than one consecutive space, the result of the split will have empty strings.

Upvotes: 3

Related Questions