Fabien Bauer
Fabien Bauer

Reputation: 1

Argparse optional arguments with default values

I'm working on something where I need to use argparse. Here's the code I got a problem with:

parser = argparse.ArgumentParser()
parser.add_argument('--create n file', dest='create',
                    nargs=2, default=(1, 'world1.json'),
                    help='Create a party of n player with mission parameters in file')

I'm trying to find a way to either set both n and file to another value, or set only one of them. n is an int and file a str.

Here's what I would like to get, using the following command:

Command Expected result
python mission.py --create 2 create = [2, 'world1.json']
python mission.py --create world2.json create = [1, 'world2.json']
python mission.py --create 3 world2.json create = [3, 'world2.json']

When --create is used (with or without specifying n/file), I'll need to start a function using the list as arguments.

I've tried multiple things and read argparse documentation more than once but can't find a way to do it.

Upvotes: 0

Views: 271

Answers (1)

Pierre de Buyl
Pierre de Buyl

Reputation: 7293

The code below returns the expected results for the listed usecases. I decided to use an extra function to handle the argument, as the program must accept either an int or a string for the first argument passed.

I use a "try" block to see whether the single argument can be parsed as an int before proceeding.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--create n file', dest='create', nargs='+', default=(1,'world1.json'),
                    help='Create a party of n player with mission parameters in file')
args = parser.parse_args()

def get_n_file(arg):
    if len(arg)==1:
        try:
            i = int(arg[0])
            result = int(arg[0]), 'world'+str(arg[0])+'.json'
        except:
            s = arg[0]
            result = 1, s
        return result
    elif len(arg)==2:
        return int(arg[0]), arg[1]

print(args.create)

n, f = get_n_file(args.create)

print(n, f)

Upvotes: 1

Related Questions