简体   繁体   English

如何在python中构造可选参数

[英]How to structure optional arguments in python

I'm pretty new to python and im wondering whats the best way is to stucture and build my code in a specific data validation case. 我是python的新手,我想知道最好的方法是在特定的数据验证案例中构建和构建代码。 I'm building cmd line script that takes 3 arguments and save them to variables. 我正在构建使用3个参数并将其保存到变量的cmd行脚本。 The third argument is optional. 第三个参数是可选的。 How should i handle the optional argument. 我应该如何处理可选参数。 I get promted for "IndexError: list index out of range" when im not specifing the third argument. 当我未指定第三个参数时,提示“ IndexError:列表索引超出范围”。

Whats the most simple and practical why to validate user input with a optional argument? 为什么最简单,最实用的方法是使用可选参数来验证用户输入?

user_cat = sys.argv[1]
user_id = sys.argv[2]
user_guid = sys.argv[3]

def validate(user_cat, argv_cat_list, user_guid):
    if len(user_cat) > 10 or user_cat not in argv_cat_list:
        print("Error! Please specify a valid category (AddDevice, GetAccount, c, p, GetDevices, r ,s)")
        sys.exit()
    elif len(user_id) == 36 or user_id.startswith("SAM-") and len(user_guid) == False:
        getInfo()
        sys.exit()
    elif len(user_cat) >= 10 and len(user_guid) == 36 and user_id.startswith("FRA-"):
        print ("Test-hest!")
    else:
        print("Error! Please specify a valid input")
        sys.exit()

I would recommend the argparse library. 我会推荐argparse库。 Tutorial here. 教程在这里。

Write something like: 写类似:

parser = argparse.ArgumentParser(description = "[insert some description here]")
parser.add_argument('-i', "--user_cat", help = '[insert some help]')
parser.add_argument('-i', "--cat_list", help = '[insert more help]')
parser.add_argument('-u', "--user_guid", nargs = '?', help = '[insert some help]')
args = parser.parse_arg()
# Access the variables with args.user_cat, args.cat_list, etc.

You should use argparse for this. 您应该为此使用argparse You don't always need flags, sometimes just a positional argument is better as it saves typing, compare eg with cat . 您并不总是需要标志,有时只是位置参数会更好,因为它可以节省键入内容,例如与cat比较。 Try the following example 试试下面的例子

parser = argparse.ArgumentParser(description='LOLCATZ')
parser.add_argument('cat')
parser.add_argument('id')
parser.add_argument('guid')
parser.add_argument('optional1', nargs='?')  # positional and optional
parser.add_argument('--optional2')  # optional flag
args = parser.parse_args()
print(args)

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

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