I’m writing a Django App, where I am expecting to use many management.py 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 manage.py createdb user=some_user db_name=some_name
So far as I can tell, management.py 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:
try:
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?
Instead of rolling your own, you could use typical parameter style, and use something like
argparseto parse it:You’d just define your argument parser and then pass the
argsargument to itsparse_args()method.