0

I am running into a weird problem with args.parse in python 3.4 and I need some help. I am just starting with python, so it may be something stupid.

I am passing an argument

parser.add_argument('-solr', type=str, default='http://localhost:8983/solr/', nargs='+', help='Address of Solr server (ex: http://192.168.137.128:8983/solr/)')

It should be just one argument, all the time. If I actually pass the argument, it will get stored as an array and I will need to access it via args.solr[0]. However, if I don't pass any arguments to it, the default value will be used, but it will be stored as string, thus, args.solr[0] will be 'h'.

What gives? I've tried to play around with nargs, but even setting it to 1 doesn't seem to change anything.

Thanks in advance

2 Answers 2

1

Use nargs = '?'. It stopped taking the input as an array.

parser.add_argument('--solr', type=str, default='http://localhost:8983/solr/',nargs='?',help='Address of Solr server (ex: http://192.168.137.128:8983/solr/)')

Sign up to request clarification or add additional context in comments.

1 Comment

nargs='?' is more useful on positionals than optionals - unless you want --solr without any argument to mean something.
0

Since your argument is flagged (name starts with -) you don't need to set nargs at all - use its default None. It is optional (not required) unless you use the flag string.

parser.add_argument('--solr', default='http://localhost:8983/solr/', 
    help='Address of Solr server (ex: %(default)s)')

With this, sample inputs produce:

In [51]: parser.parse_args([])
Out[51]: Namespace(solr='http://localhost:8983/solr/')

In [52]: parser.parse_args(['--solr','test'])
Out[52]: Namespace(solr='test')

In [50]: parser.print_help()
usage: ipython [-h] [--solr SOLR]

optional arguments:
  -h, --help   show this help message and exit
  --solr SOLR  Address of Solr server (ex: http://localhost:8983/solr/)

With longer optional names, a -- is better than -. The default type is str, so you don't need to specify that. I've added %(default)s to the help, so you don't have to repeat the default value.

If you do want the result to be a list, e.g. ['test'], use nargs=1 and put the default in a list as well, e.g. default=['http...'].

Comments

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.