samuel
samuel

Reputation: 487

python get specific arg

I got a programme with initial values:

SIZE = 100
NB = 100
WIDTH_CANVAS = 150
[...]

But I want to allow the user to update these values from terminal:

python3 main.py NB=10
python3 main.py NB=10 WIDTH_CANVAS=200 SIZE=50

or nothing to change :

python3 main.py

so I tried something like that:

import sys

SIZE = sys.argv[1]
NB = sys.argv[2]
WIDTH_CANVAS = sys.argv[3]

but the problem is: what if they don't want to specify the NB for example?

Upvotes: 0

Views: 163

Answers (2)

Gabio
Gabio

Reputation: 9494

argparse is exactly what you need. Here is a short example (https://docs.python.org/3/library/argparse.html):

import argparse

SIZE = 100
NB = 100

parser = argparse.ArgumentParser()
parser.add_argument('--NB', dest='NB', type=int, default=NB)
parser.add_argument('--SIZE', dest='SIZE', type=int, default=SIZE)


args = parser.parse_args()


print(args.SIZE)
print(args.NB)

So for running python prog.py --SIZE 3 you will get:

3
100

Upvotes: 2

tripleee
tripleee

Reputation: 189397

If you want to use exactly that syntax, probably set up a dict with your defaults.

value = {'NB': 100, 'SIZE': 100, 'WIDTH_CANVAS': 150}

for arg in sys.argv[1:]:
    if '=' in arg:
        k, v = arg.split('=', 1)
        if k not in value:
            raise KeyError('Invalid command-line argument %s' % k)
        value[k] = v
    else:
        raise MaybeGripe('Some other error here?')

Now go ahead and use value['SIZE'] as you would have used the bare SIZE variable previously, etc.

As suggested in comments, a more common arrangement is to have command-line options and use the standard ArgParse module to parse them. Maybe then your syntax would look more like

python main.py --size 25 --canvas-width 100

which will be more familiar and less distracting to most users.

Upvotes: 2

Related Questions