0

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?

Gabio
9,5643 gold badges17 silver badges38 bronze badges
asked Nov 9, 2020 at 12:23
1

2 Answers 2

2

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
answered Nov 9, 2020 at 12:43
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Nov 9, 2020 at 12:36

1 Comment

I believe the Unix dd command was implemented with a syntax like you propose partly as a joke. Unfortunately, it stuck, and we all swear over it.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.