0

I'm attempting to allow an optional argument that takes a single command line argument of a filename:

parser.add_argument('--somefile', nargs=1, type=argparse.FileType('r'),
                     required=False, default='defaultfile.json')

The problem is when I specify a file using the --somefile foo.json I get back a handle in a list:

args.somefile=[<_io.TextIOWrapper name='foo.json' mode='r' encoding='UTF-8'>]

When I don't specify it and want the default, I get back a handle, but not in a list:

args.somefile=<_io.TextIOWrapper name='defaultfile.json' mode='r' encoding='UTF-8'>

How do I get args.somefile to return the same type of structure (handle either in a list or not in a list) consistently?

1 Answer 1

1

Remove nargs argument.

Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.

UPDATE on comment

Removing nargs=1 would eliminate the requirement to specify the filename argument.

Lets check:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--somefile', type=argparse.FileType('r'), required=False, default='/tmp/data.json')
_StoreAction(option_strings=['--somefile'], dest='somefile', nargs=None, const=None, default='/tmp/data.json', type=FileType('r'), choices=None, help=None, metavar=None)
>>> args = parser.parse_args(['--somefile',])
usage: [-h] [--somefile SOMEFILE]
: error: argument --somefile: expected one argument
Sign up to request clarification or add additional context in comments.

3 Comments

Removing nargs=1 would eliminate the requirement to specify the filename argument.
@Omniver, no, its not. Check it by yourself.
Thank you. I did not read far enough in the documentation. 'nargs - The number of command-line arguments that should be consumed.' Later though: 'ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.