Reputation: 135
I want to pass a short product code when running my script:
./myscript.py --productcode r|u|c
Then use the short product code to look up data stored in a tuple in the python code:
# create tuples for each product
r=("Redhat","7.2")
u=("Ubuntu","7.5")
c=("Centos","8.1")
# parse the command line
parser = argparse.ArgumentParser()
parser.add_argument("--productcode", help="Short code for product")
options=parser.parse_args()
# get the product code
product_code=options.productcode
# Access elements in the relevant tuple
product_name=product_code[0]
product_version=product_code[1]
Upvotes: 0
Views: 75
Reputation: 448
As was already mentioned in the comment, you can store tuples in a dictionary with the matching keys.
import argparse
mapping = {
'r': ("Redhat", "7.2"),
'u': ("Ubuntu", "7.5"),
'c': ("Centos", "8.1"),
}
parser = argparse.ArgumentParser()
parser.add_argument("--productcode", help="Short code for product")
options = parser.parse_args()
product = mapping[options.productcode]
print(product[0])
print(product[1])
In this case:
$ python script.py --productcode c
Centos
8.1
Alternatively, you can create the mapping dynamically (here I used namedtuple instead of a regular tuple).
import argparse
import sys
from collections import namedtuple
Product = namedtuple('Product', ['name', 'version', 'code'])
redhat = Product("Redhat", "7.2", 'r')
ubuntu = Product("Ubuntu", "7.5", 'u')
centos = Product("Centos", "8.1", 'c')
mapping = {
item.code: item
for item in locals().values()
if isinstance(item, Product)
}
parser = argparse.ArgumentParser()
parser.add_argument("--productcode", help="Short code for product")
options = parser.parse_args()
product = mapping[options.productcode]
print(product.name)
print(product.version)
Upvotes: 1