vlad
vlad

Reputation: 811

Set argparse argument as default switch

My test.py file has these instructions:

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--parameter", default="latest")
parser.add_argument("-q", "--query")

I want to make possible to run the script without explicitly setting the switch for "query" argument ("-q" or "--query"), i.e. if I call:

python test.py something

"something" to be automatically assigned as query argument.

Is that possible?

Upvotes: 1

Views: 1050

Answers (2)

hpaulj
hpaulj

Reputation: 231355

With a dest value, the optional argument can set the same attribute as the positional:

parser = argparse.ArgumentParser()
parser.add_argument("-q", "--query", dest='query_string')
parser.add_argument("query_string", nargs='?', default='default')
args = parser.parse_args()

print parser.parse_args('other'.split())
# Namespace(query_string='other')    # the positional value

print parser.parse_args('-q other'.split())
# Namespace(query_string='default')   # the positional default

print parser.parse_args('more -q other'.split())
# Namespace(query_string='other')    # the optional's value

You can use the same dest for multiple arguments. But nuances on how '?' positionals are handled produce seemingly unpredictable results.

In the '-q other' case, the namespace value is first set to 'other', but then it is overwritten by the positional default when the positional is 'parsed' at the end.

In the 'more -q other' example, the positional value 'more' is set, and then overwritten by the '-q' value.

Upvotes: 2

user3467349
user3467349

Reputation: 3191

Something like this would work:

import argparse 

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--parameter", default="latest")
parser.add_argument("-q", "--query")
parser.add_argument("query_string",nargs='?', default=False)

args = parser.parse_args()

if args.parameter: 
   print("zoinks a parameter! %s" %args.parameter)
if args.query or args.query_string: 
   print("making a query %s" % (args.query or args.query_string)) 

Upvotes: 1

Related Questions