tsaebeht
tsaebeht

Reputation: 1680

Unable to assign default values to arguments in Python argparse

I am using Python argparse to take in parameters through the CLI. I have tried using the following but when I don't give any one of the arguments, it gives the output as None. I want then default ones to be the ones provided in const=. Please take a look.

parser = argparse.ArgumentParser()
parser.add_argument('--input', nargs='?', const='testInput')
parser.add_argument('--target', nargs='?', const='testTarget')
parser.add_argument('--msg', nargs='?', const='helloFromTheOtherSide')
args = parser.parse_args()
print args.input

If I don't give input, it prints it as None as I said. I want it to print TestInput instead..

Upvotes: 0

Views: 206

Answers (2)

hpaulj
hpaulj

Reputation: 231738

With

parser.add_argument('--input', nargs='?', default='testInput', const='aConst')

you have a 3 way choice

prog                  # input='testInput'
prog --input          # input='aConst'
prog --input myfile   # input='myfile'

If you don't need that aConst option, omit the nargs='?'. Since it is a flagged argument it is already optional. It doesn't need the `?'.

parser.add_argument('--input', default='testInput')

Upvotes: 0

Roland Smith
Roland Smith

Reputation: 43573

Use the default argument:

parser = argparse.ArgumentParser()
parser.add_argument('--input', nargs='?', default='testInput')
parser.add_argument('--target', nargs='?', default='testTarget')
parser.add_argument('--msg', nargs='?', default='helloFromTheOtherSide')
args = parser.parse_args()
print args.input

Upvotes: 1

Related Questions