python - Simple example of how to define argument with argparse? -


this must super simple, i'm struggling official argparse docs - after 20 minutes of frustrated googling, i'm giving , asking here!

i'm working in python 2.7. want run django management command argument, this:

python manage.py my_command db_name='hello' 

...and inside script, access value of db_name.

here's i've tried:

def handle(self, *args, **options):     print args     print options 

this gives me

('db_name=mydb',) {'pythonpath': none, 'verbosity': u'1', 'traceback': none, 'no_color': false, 'settings': none} 

is there easy way (other string-parsing args - surely can't best way) value of db_name?

if willing make slight modification how call script, below work:

import argparse  parser = argparse.argumentparser() parser.add_argument('--db_name', action='store', dest='db_name',                     help='store database name') results = parser.parse_args() print "db_name:", results.db_name 

you need call this:

python script.py --db_name test 

notice have use traditional unix command line arguments (--name value), instead of name=value

the output of above script is:

python script.py --db_name test db_name: test 

the db_name value accessed results.db_name


you can access these arguments custom django management commands. utilizing example, believe work:

def add_arguments(self, parser):     # named (optional) arguments     parser.add_argument('--db_name',         action='store',         dest='db_name',         help='store database name')  def handle(self, *args, **options):     if options['db_name']:         # db_name 

in case, variable accessed in options['db_name']


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -