Sam Hammamy Sam Hammamy - 1 year ago 81
Python Question

Python arguments and keyword-arguments best practices

I'm writing a Django App, where I am expecting to use many commands. I like the idea of python functions having parameters with default values, where you define the param as:

def function(param1=value1)

So I'm writing my management commands such that you input as follows:

python createdb user=some_user db_name=some_name

So far as I can tell, commands don't accept this type of argument list, so I've created a helper to do the following:

def process_args(args=None):
kwargs = {}
if not args:
return kwargs
for i in args:
k,v = i.split('=')
kwargs[k] = v
except ValueError, ve:
raise CommandError("Please Enter All Arguments as key=value. e.g. user=admin")
return kwargs

Is there a better way to do this?

Answer Source

Instead of rolling your own, you could use typical parameter style, and use something like argparse to parse it:

python createdb --user=some_user --db_name=some_name

You'd just define your argument parser and then pass the args argument to its parse_args() method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download