3

I would like to pass arguments to a python script as follows.

python test.py --env_a 5 --env_b 8

So that all the arguments beginning with "env" are added to a dictionary like:

env = {
"a": 5,
"b": 8
}

Of course the whole point is that the number and the names of those arguments are not predefined.

Do you know if this is possible or if there is a better way of doing this?

I am using argparse so something along the lines of

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--env-*", type=dict, default=0)
args = parser.parse_args()

print(args.env)

would be ideal.

1
  • 1
    Would a slightly different syntax be ok? It is almost trivial to support --env=a:5
    – MegaIng
    Commented Apr 19, 2021 at 15:02

2 Answers 2

5

I see no other method than doing it manually:

import argparse

parser = argparse.ArgumentParser()
args, unknown = parser.parse_known_args()

# unknown == ['--env_a', '5', '--env_b', '8']

env = {}
for i in range(0, len(unknown), 2):
    if not unknown[i].startswith('--env'): continue
    assert unknown[i+1].isdigit()
    env[unknown[i][len('--env_'):]] = int(unknown[i+1])

# env == {'a': 5, 'b': 8}
2

If you'd be fine with specifying arguments like so: python argtest.py --env a 1 b 2 c hello, you could use nargs='*' and then create a dictionary using the list that you get out of it

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--env", nargs='*', default='')
args = parser.parse_args()

print(args.env)
#Outputs 
# ['a', '1', 'b', '2']

keys = args.env[::2] # Every even element is a key
vals = args.env[1::2] # Every odd element is a value

# Make the dict you want
args.env = {k: int(v) if v.isdigit() else v for k, v in zip(keys, vals)} 
#####
# you can also write this as:
# 
# vals = [int(v) if v.isdigit() else v for v in args.env[1::2]]
# args.env = dict(zip(keys, vals))
#
####

print(args.env)
# Outputs
# {'a': '1', 'b': '2'}
2
  • 2
    dict(zip(keys, vals)) instead of {k: v for k, v in zip(keys, vals)} ?
    – thebjorn
    Commented Apr 19, 2021 at 15:18
  • @thebjorn sure, that works too! Don't know if it's more efficient though, and I like having the comprehension because it makes it obvious what is happening.
    – pho
    Commented Apr 19, 2021 at 15:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.