Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: Does it have to return a list?

I am trying to obtain a string of numbers from argparse. It's optional whether or not the argument -n is provided.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-n', nargs=1) # -n is optional but must come with one and only one argument
args = parser.parse_args()
test = args.n
if test != 'None':
    print("hi " + test) 

The program fails when I do not provide "-n argument", but works fine when I do.

Traceback (most recent call last):
  File "parse_args_test.py", line 7, in <module>
    print("hi " + test) 
TypeError: Can't convert 'NoneType' object to str implicitly

How can I fix this?

like image 515
imagineerThat Avatar asked Jul 02 '26 02:07

imagineerThat


1 Answers

Regarding the question from the title, when nargs is used, the returned value of args.n is a list (even if the nargs=1 is used). So when only 1 argument is expected, you may decide to not use nargs at all to avoid returning a list.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-n')
args = parser.parse_args()
test = args.n
if test:
    print("hi " + test) 
like image 51
michalmonday Avatar answered Jul 04 '26 18:07

michalmonday