繁体   English   中英

Python:使用命令行选项访问元组

[英]Python: using command-line option to access a tuple

我想在运行我的脚本时传递一个简短的产品代码: ./myscript.py --productcode r|u|c然后使用简短的产品代码查找存储在 python 代码中的元组中的数据:

# 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]

正如评论中已经提到的,您可以将元组存储在具有匹配键的字典中。

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])

在这种情况下:

$ python script.py --productcode c
Centos
8.1

或者,您可以动态创建映射(这里我使用 namedtuple 而不是常规元组)。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM