2

I am trying to make use of an argument handler that I wrote using argparse from within another python script. I would like to call it by passing it a list of arguments. Here is a simple example:

def argHandler(argv):

    import argparse

    parser = argparse.ArgumentParser(description='Test argument parser')

    parser.add_argument('foo', action='store',type=str)
    parser.add_argument('bar', action='store',type=str)
    parser.add_argument('-nee','--knightssaynee',action='store',type=str)

    args = parser.parse_args()

    return args.foo, args.bar, args.nee

if __name__=='__main__':

    argList = ['arg1','arg2','-nee','arg3']

    print argHandler(argList)

This returns a:

usage: scratch.py [-h] [-nee KNIGHTSSAYNEE] foo bar
scratch.py: error: too few arguments

It seems to me that the function that I define should take a list of arguments and flags, and return a namespace. Am I wrong?

2 Answers 2

3

You need to pass those arguments to the parser.parse_args() method:

args = parser.parse_args(argv)

From the ArgumentParser.parse_args() documentation:

ArgumentParser.parse_args(args=None, namespace=None)

[...]

By default, the argument strings are taken from sys.argv [...]

Note the args argument there. You may want to make the argv argument to your argHandler() function default to None as well; that way you don't have to pass in an argument and end up with the same default None value:

def argHandler(argv=None):
Sign up to request clarification or add additional context in comments.

1 Comment

That worked! Thanks, I just needed to change: args = parser.parse_args() to args = parser.parse_args(argv) in my code
-1

another way i get input to program is from json file with key value pair and using json load library to load contents of file as json object.

1 Comment

And this has to do what exactly with the question?

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.