buhtz
buhtz

Reputation: 12172

optional parameter without a switch with Pythons argparse

(Please feel free to edit the title to make it better to understand.)

I want to call (on bash) a Python script in this two ways without any error.

./arg.py
./arg.py TEST

It means that the parameter (here with the value TEST) should be optional. With argparse I only know a way to create optional paramters when they have a switch (like --name).

Is there a way to fix that?

#!/usr/bin/env python3    
import sys
import argparse

parser = argparse.ArgumentParser(description=__file__)

# must have
#parser.add_argument('name', metavar='NAME', type=str)

# optional BUT with a switch I don't want
#parser.add_argument('--name', metavar='NAME', type=str)

# store all arguments in objects/variables of the local namespace
locals().update(vars(parser.parse_args()))

print(name)

sys.exit()

Upvotes: 0

Views: 696

Answers (1)

hpaulj
hpaulj

Reputation: 231395

I think all you need is nargs='?'.

parser = argparse.ArgumentParser(description=__file__)
parser.add_argument('name', nargs='?', default='mydefault')
args = parser.parse_args()

I'd expect args to be either:

namespace(name='mydefault')
namespace(name='TEST')

Upvotes: 1

Related Questions