jpact
jpact

Reputation: 1072

Python argparse with multiple actions within one argument

I'm trying to solve a problem with python's argparse function

What I would like to achieve is, that if -k argument is specified, it's set to its default value (let's say 5), however if -k=3 is set, 'k' now contains 3...

Here is an example:

python3 test.py -k

Namespace(k==5)

python3 test.py -k=3

Namespace(k==3)

Is it possible to get something like this ?

test.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-k ', metavar='n', type=int, default=5, dest='number')
args = parser.parse_args()
print(args)

Thanks in advance

Upvotes: 3

Views: 4088

Answers (2)

Spferical
Spferical

Reputation: 166

It's a bit of a hack, but you could replace all equal signs in the arguments with spaces and then use argparse on them. This could work better if you want to still use argparse, e.g. for other arguments.

It would mean both -k=3 and -k 3 would work. Though also -k=3=-k=4=-k would be parsed without error.

Adapted from jmunsch's answer:

import argparse
import sys

# split all args with equal sign
args = []
for arg in sys.argv[1:]:
    args.extend(arg.split('='))

# parse the args
parser = argparse.ArgumentParser()
parser.add_argument('-k', metavar='n', type=int, dest='number',
                    action='append', nargs='?', const=5)
args = parser.parse_args(args)
print(args.number[0])

This could be made more intelligent by only splitting args that start with '-k=':

# split all args with equal sign
args = []
for arg in sys.argv[1:]:
    if arg[:2] == '-k=':
        args.extend(arg.split('='))
    else:
        args.append(arg)

Upvotes: 0

jmunsch
jmunsch

Reputation: 24139

What about this:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-k',metavar='n', dest='number', action='append', nargs='?', const=5)
args = parser.parse_args()

print(args.number[0])

'python3 test.py -k' outputs:

5

'python3 test.py -k=3' outputs:

3

An example using sys:

import sys

k = 5
for opt in sys.argv:
    if opt.split('=')[0] == '-k':
        if '=' in opt:
            print(opt.split('=')[1])
        if '=' not in opt:
            print(k)
    elif len(sys.argv) is 1:
        print('No arguments were supplied')

Upvotes: 1

Related Questions