1

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.

user1740117
  • 33
  • 1
  • 3
  • 7
  • `sorthelper.sortNumber(args)` should call the imported function and pass it the `args` variable. It's no different from calling any other imported function. – hpaulj Apr 07 '21 at 23:35
  • 1
    What's your question? Please [edit] to clarify. See [ask] for tips. For example, if you're looking for debugging help, you need to provide a [mre]. – wjandrea Apr 08 '21 at 01:40
  • 1
    Okay so. 1) If you weren't using argparse, and instead wanted to use specific hard-coded values to call `sortNumbers`, would you be able to do that? 2) Did you try checking, after `args = parser.parse_args()`, what `args` actually looks like? Did you try reading the documentation to see how it's supposed to work? 3) Okay, now put it together - get the information out of `args`, and use it to make a call to `sortNumbers`. *Where exactly are you stuck*? – Karl Knechtel Apr 08 '21 at 04:26
  • Where you put `args.func(args)`, *what are you expecting this to mean*? Again, try looking at the documentation. What kind of thing is `args`? What data does it contain? How can you get the necessary information out of it, according to the documentation? – Karl Knechtel Apr 08 '21 at 04:28

1 Answers1

5

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)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • Thanks for your assistance with argparse. You were able to help me finally move on from that. I had trouble later with printing the function but I finally managed. I ended up using: `answer = sorthelper.sortNumbers(args.f) print(answer)` – user1740117 Apr 09 '21 at 17:10