Reputation: 121
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?
Upvotes: 2
Views: 1197
Reputation: 56
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.
Upvotes: -1
Reputation: 1124558
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):
Upvotes: 3