Attempting to pass an undetermined amount of integers using argparse. When I input: py main.py 3 2
%%writefile main.py import sorthelper import argparse integers = 0 #top-level parser creation parser = argparse.ArgumentParser("For sorting integers") nargs = '+' #-> gathers cmd line arguments into a list args = parser.add_argument('-f', metavar='N', type=int, nargs='+', help='yada yada yada') args = parser.parse_args() print(sorthelper.sortNumbers(args)) %%writefile sorthelper.py def sortNumbers(args): sorted(args)
Error Namespace Argument is not iterable
I think is is because I am passing an argument that is not of the correct type. After reading through all the documentation I could find I cannot figure out how to make this work. I want the program to sort the numbers I am passing.
Advertisement
Answer
parser.parse_args()
returns a Namespace
object, which is an object whose attributes represent the flags that were parsed. It is not iterable.
It seems like you want to get the command-line arguments given after -f
, in which case you would take that particular flag out of the Namespace
object:
print(sorthelper.sortNumbers(args.f))
Also, your code as you currently have it will print None
, because sortNumbers()
doesn’t return anything. The built-in sorted()
function does not sort in place (though list.sort()
does, if you want to use that), so you have to actually do
def sortNumbers(args): return sorted(args)