[Tutor] argparse: how to use the returned Namespace object?

Mac Ryan quasipedia at gmail.com
Fri Nov 5 00:20:50 CET 2010


Hi,

	I'm writing a small command line utility using the argparse module (I
am on python 2.6.6 so that's not in the standard lib, but this should
not play any role in my problem, I believe).

	My goal is to use a class that I already wrote and cannot change for a
GUI app, as a command utility, so I would like to simply have the CLI as
a wrapping layer, without changing the pre-existing code.

	The code I want to reuse, accept all keywords arguments, so I wrote my
parser in such a way that it returns keywords/values in a compatible way
to my method signatures. Example:

Let the signature of one of my functions be:

	def do_stuff(overwrite=False, verbose=False):
		do-some-stuff-here

I wrote the parser in such a way that issuing:

	utilityname dostuff --overwrite --verbose

I get at the end of the parsing process a variable "args" that looks
like this:

	Namespace(command=dostuff, overwrite=True, verbose=True)

Now, I tried to do the following:

	command = args.command
	del args.command
	command(**args)

But that doesn't work because the Namespace implementation of the
argparse result is an object which is not iterable. Of course if I use:

	args.command(overwrite=args.overwrite, verbose=args.verbose)

I get the system working, but the fact is that each command calls a
different function / method, each of them with a different signature.

My question boils down to: how can I expand the Namespace object in
order to get a list of keyword arguments?

Thank you for your time,
Mac.



More information about the Tutor mailing list