Reputation: 115
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.
Upvotes: 3
Views: 802
Reputation: 25489
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'}
Upvotes: 2
Reputation: 1732
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}
Upvotes: 5